"use strict";const F=require("./model-config-Clqxmxf5.cjs"),e=require("./orchestrator-prompt-DrSBhdTf.cjs"),t=require("./shared-types-B8BH5zz1.cjs"),M=require("crypto"),_={id:"spec-task-execution",description:"Specialized sub-agent for executing spec tasks with property-based testing support",tools:"*",prompt:e.SPEC_TASK_PROMPT,model:void 0,specOnly:!0},B=`# Design Document: [Feature Name]

## Overview

[1-2 sentences describing the feature]

## Main Algorithm/Workflow

\`\`\`mermaid
sequenceDiagram
    participant A as Component A
    participant B as Component B
    participant C as Component C
    
    A->>B: operation(input)
    B->>C: process(data)
    C-->>B: result
    B-->>A: output
\`\`\`

## Core Interfaces/Types

\`\`\`[language or pseudocode]
interface MainInterface {
  coreMethod(input: InputType): OutputType
}

type DataType = {
  field1: string
  field2: number
}
\`\`\`

## Key Functions with Formal Specifications

### Function 1: processData()

\`\`\`[language or pseudocode]
function processData(data: DataType): Result
\`\`\`

**Preconditions:**
- \`data\` is non-null and well-formed
- \`data.field1\` is non-empty string
- \`data.field2\` is positive integer

**Postconditions:**
- Returns valid Result object
- If successful: \`result.success === true\`
- If error: \`result.error\` contains descriptive message
- No side effects on input data

**Loop Invariants:** N/A (or specify if function contains loops)

### Function 2: validateInput()

\`\`\`[language or pseudocode]
function validateInput(input: InputType): boolean
\`\`\`

**Preconditions:**
- \`input\` is defined (not null/undefined)

**Postconditions:**
- Returns boolean value
- \`true\` if and only if input meets all validation criteria
- No mutations to input parameter

**Loop Invariants:** 
- For validation loops: All previously checked fields remain valid

## Algorithmic Pseudocode

### Main Processing Algorithm

\`\`\`pascal
ALGORITHM processMainWorkflow(input)
INPUT: input of type InputType
OUTPUT: result of type Result

BEGIN
  ASSERT validateInput(input) = true
  
  // Step 1: Initialize processing state
  state ← initializeState(input)
  
  // Step 2: Process data with loop invariant
  FOR each item IN input.items DO
    ASSERT allProcessedItemsValid(state.processed)
    
    processedItem ← processItem(item, state)
    state.processed.add(processedItem)
  END FOR
  
  // Step 3: Finalize result
  result ← finalizeResult(state)
  
  ASSERT result.isComplete() AND result.isValid()
  
  RETURN result
END
\`\`\`

**Preconditions:**
- input is validated and well-formed
- input.items is a valid collection
- All required processing functions are available

**Postconditions:**
- result is complete and valid
- All input items have been processed
- Processing state is properly finalized

**Loop Invariants:**
- All processed items are valid
- Processing state remains consistent throughout iteration

### Validation Algorithm

\`\`\`pascal
ALGORITHM validateInput(input)
INPUT: input of type InputType
OUTPUT: isValid of type boolean

BEGIN
  // Check basic structure
  IF input = null OR input = undefined THEN
    RETURN false
  END IF
  
  // Validate each field with early termination
  FOR each field IN input.requiredFields DO
    IF NOT isValidField(field) THEN
      RETURN false
    END IF
  END FOR
  
  // All validations passed
  RETURN true
END
\`\`\`

**Preconditions:**
- input parameter is provided (may be null/undefined, but parameter exists)
- isValidField function is available and properly implemented

**Postconditions:**
- Returns boolean value indicating validity
- true if and only if input passes all validation checks
- No side effects on input parameter

**Loop Invariants:**
- All previously checked fields were valid when loop continues
- Validation state remains consistent throughout iteration

## Example Usage

\`\`\`[language or pseudocode]
// Example 1: Basic usage
const data = { field1: "value", field2: 42 }
const result = processData(data)

// Example 2: Error handling
if (!validateInput(input)) {
  throw new Error("Invalid input")
}

// Example 3: Complete workflow
const input = createInput()
if (validateInput(input)) {
  const result = processMainWorkflow(input)
  handleResult(result)
}
\`\`\`
`,W=`# Design Document: [Feature Name]

## Overview

[2-3 paragraph summary of the feature, its purpose, and high-level approach]

## Architecture

[Describe the overall architecture. Include Mermaid diagrams where helpful]

\`\`\`mermaid
graph TD
    A[Component A] --> B[Component B]
    B --> C[Component C]
\`\`\`

## Components and Interfaces

### Component 1: [Name]

**Purpose**: [What this component does]

**Interface**:
\`\`\`[language or pseudocode]
interface ComponentName {
  method1(param: Type): ReturnType
  method2(param: Type): ReturnType
}
\`\`\`

**Responsibilities**:
- Responsibility 1
- Responsibility 2

### Component 2: [Name]

[Similar structure...]

## Data Models

### Model 1: [Name]

\`\`\`[language or pseudocode]
interface ModelName {
  field1: Type
  field2: Type
  field3: Type
}
\`\`\`

**Validation Rules**:
- Rule 1
- Rule 2

### Model 2: [Name]

[Similar structure...]

## Error Handling

### Error Scenario 1: [Name]

**Condition**: [When this error occurs]
**Response**: [How the system handles it]
**Recovery**: [How the system recovers]

### Error Scenario 2: [Name]

[Similar structure...]

## Testing Strategy

### Unit Testing Approach

[Describe unit testing strategy, key test cases, and coverage goals]

### Property-Based Testing Approach

[Describe property-based testing strategy]

**Property Test Library**: [Specify library: fast-check, hypothesis, QuickCheck, etc.]

### Integration Testing Approach

[Describe integration testing strategy if applicable]

## Performance Considerations

[Discuss any performance requirements, constraints, or optimization strategies]

## Security Considerations

[Discuss any security requirements, threat models, or mitigation strategies]

## Dependencies

[List external dependencies, libraries, or services required]`,H=`
## CRITICAL: How to Ask User Questions

**ALWAYS use the userInput tool when you need to ask the user a question with options.**

**NEVER do this**:
- Write questions as text in the chat
- List options as numbered text
- Say "Which would you prefer?" as text

**ALWAYS do this**:
- Call the userInput tool with proper parameters
- The tool creates interactive buttons
- Wait for the tool's response

**Why this matters**: Writing questions as text does NOT work. The user cannot respond properly. You MUST use the userInput tool to create interactive UI elements.

---

## Design Detail Level from Entry Point Selection

The user has already selected their design artifacts during entry point selection. Parse the bracketed content from their response to determine which artifacts to include:
- "High-Level Design" → Include Diagrams & Interfaces sections
- "Low-Level Design" → Include Code-First sections
- Both selected → Include both approaches in the design

**DO NOT ask the user again which spec approach they want to use.**

---

## Smart Language/Pseudocode Detection (For Code-First Only)

**IMPORTANT**: This section ONLY applies when the user selects "Code-First" design detail level.

**CRITICAL REMINDER**: When you need to ask the user a question, you MUST use the userInput tool. DO NOT write questions as text in the chat. The userInput tool creates interactive buttons that the user can click.

### Step 1: Analyze User's Original Feature Request

Before asking about notation style, analyze the user's ORIGINAL feature request (the very first message they sent) for EXPLICIT language or style indicators.

**CRITICAL**: Only detect a language when the user EXPLICITLY mentions it. Do NOT infer languages from:
- Cloud services (AWS Lambda, Azure Functions, Google Cloud Functions)
- Databases (DynamoDB, MongoDB, PostgreSQL, MySQL)
- Infrastructure (API Gateway, Load Balancers, CDN)
- General technologies (REST, GraphQL, WebSockets)

**Programming Languages to Detect** (ONLY if explicitly mentioned):

Look for phrases like:
- "using Python", "in Python", "with Python", "Python code"
- "using TypeScript", "in TypeScript", "with TypeScript"
- "using Java", "in Java", "with Java"
- etc.

**Supported Languages**: Python, JavaScript, TypeScript, Java, C++, C#, C, Go, Rust, Ruby, PHP, Swift, Kotlin, Scala, Haskell, Erlang, Elixir, R, MATLAB, Julia, Perl, Lua, Dart, F#, Clojure, Zig

**UI/Application Frameworks that Strongly Imply Language** (ONLY these specific frameworks):
- React, Vue, Angular, Svelte, Next.js → JavaScript/TypeScript (these are inherently JS/TS frameworks)
- Django, Flask, FastAPI → Python (these are inherently Python frameworks)
- Rails, Sinatra → Ruby (these are inherently Ruby frameworks)
- Spring → Java (this is inherently a Java framework)
- .NET, ASP.NET → C# (these are inherently C# frameworks)
- Laravel, Symfony → PHP (these are inherently PHP frameworks)
- Express, NestJS, Koa → JavaScript/TypeScript (these are inherently JS/TS frameworks)

**DO NOT detect language from**:
- AWS services (Lambda, DynamoDB, S3, API Gateway, etc.)
- Azure services (Functions, Cosmos DB, etc.)
- Google Cloud services (Cloud Functions, Firestore, etc.)
- Databases (PostgreSQL, MySQL, MongoDB, Redis, etc.)
- Message queues (SQS, RabbitMQ, Kafka, etc.)
- Generic terms (API, microservice, serverless, REST, GraphQL, etc.)

**Pseudocode Style Keywords to Detect** (if found, infer style - skip asking):
- **Structured Pseudocode**: "pseudocode", "control flow", "structured programming", "flowchart"
- **Mathematical Pseudocode**: "algorithm", "mathematical notation", "algorithmic notation", "formal algorithm", "complexity analysis"
- **Lean**: "Lean", "lean", "formal proof", "mathematical proof", "theorem", "formal verification", "proof assistant"

### Step 2: Apply Detection Logic

**IF** user's original prompt contains a programming language name **THEN**:
- Use that programming language for all code examples
- Do NOT use pseudocode
- Do NOT ask about notation style
- Proceed directly to creating the Code-First design with that language
- Example: "Build me an API using Python" → Use Python syntax throughout

**ELSE IF** user's original prompt contains pseudocode style keywords **THEN**:
- Use the inferred pseudocode style
- Do NOT ask about notation style
- Proceed directly to creating the Code-First design with that style
- Keyword mappings:
  - "pseudocode" (generic) → Structured Pseudocode
  - "algorithm", "mathematical" → Mathematical Pseudocode
  - "Lean", "proof", "formal" → Lean
- Example: "Build me an API using pseudocode" → Use Structured Pseudocode

**ELSE** (no language or style detected in original prompt) **THEN**:
- **CRITICAL**: You MUST ask the user to choose notation style
- **DO NOT** default to any style without asking
- **DO NOT** write text explaining you'll use a default
- **YOU MUST** use the userInput tool to present the choice
- Wait for user's response before proceeding

### Step 3: Ask About Notation Style (MANDATORY When No Detection)

**CRITICAL - YOU MUST DO THIS**: If no language or pseudocode style was detected in the user's original prompt, you MUST ask this question using the userInput tool.

**DO NOT**:
- Write the question as text in the chat
- Say "Which notation style would you prefer?" as text
- Say "I'll use Structured Pseudocode as the default"
- Say "Let me use [any style] for the design"
- Explain that you need to ask the user
- List the options as text
- Proceed without calling the userInput tool

**YOU MUST**:
- Immediately call the userInput tool (do not write text first)
- Use the EXACT parameters below
- Wait for the user's actual response from the tool
- Use the style they choose

**CRITICAL**: The userInput tool creates interactive buttons for the user. Writing the question as text does NOT work. You MUST call the tool.

Use the userInput tool with these EXACT parameters:
\`\`\`json
{
  "question": "Which notation style would you prefer for the design?",
  "reason": "spec-code-first-style",
  "options": [
    {
      "title": "Structured Pseudocode",
      "description": "Control flow constructs (IF-THEN-ELSE, WHILE, FOR) - most readable",
      "recommended": true
    },
    {
      "title": "Mathematical Pseudocode",
      "description": "Algorithm notation with mathematical symbols - formal and precise"
    },
    {
      "title": "Lean",
      "description": "Lean programming language and proof assistant - for formally verified code"
    }
  ]
}
\`\`\`

**STOP and WAIT for the user's response before proceeding. Do NOT create the design document until the user has selected an option.**

### WRONG vs RIGHT: How to Ask the Question

**WRONG - Writing as Text (DO NOT DO THIS)**:
\`\`\`
"Which notation style would you prefer for the design?

1. Structured Pseudocode (recommended): Control flow constructs...
2. Mathematical Pseudocode: Algorithm notation...
3. Lean: Lean programming language and proof assistant..."
\`\`\`

**RIGHT - Using userInput Tool (DO THIS)**:
Call the userInput tool with the JSON parameters above. The tool will create interactive buttons for the user.

**Why the tool is required**:
- Creates interactive UI buttons
- Properly captures user's choice
- Integrates with the workflow system
- Text questions do NOT work - they just confuse the user

### Detection Examples

**Example 1: Explicit Programming Language**
- User prompt: "Build me a user authentication system using Python"
- Detection: Python language explicitly mentioned
- Action: Use Python syntax, skip notation question
- Result: Code-First design with Python code examples

**Example 2: Framework Implies Language**
- User prompt: "Build me a React component for user login"
- Detection: React framework (inherently JavaScript/TypeScript)
- Action: Use TypeScript syntax, skip notation question
- Result: Code-First design with TypeScript/React code

**Example 3: Cloud Services WITHOUT Language (DO NOT INFER)**
- User prompt: "Create an API with AWS Lambda speaking to DynamoDB. Place API Gateway in front of the Lambda function. The API should have CRUD options for a TODO app."
- Detection: NO language detected (AWS Lambda, DynamoDB, API Gateway are infrastructure, not languages)
- Action: **MUST** call userInput tool to ask user to choose notation style
- Result: Present choice between Structured/Mathematical/Lean using userInput tool
- **CRITICAL**: Do NOT say "I'll use Structured Pseudocode as the default"
- **CRITICAL**: Do NOT assume TypeScript or Python just because AWS Lambda is mentioned
- **CRITICAL**: Do NOT proceed without calling userInput tool and getting user's choice

**Example 4: Cloud Services WITH Explicit Language**
- User prompt: "Create an API with AWS Lambda using Python speaking to DynamoDB"
- Detection: Python explicitly mentioned
- Action: Use Python syntax, skip notation question
- Result: Code-First design with Python code examples

**Example 5: Explicit Pseudocode Style**
- User prompt: "Build me a sorting algorithm using mathematical notation"
- Detection: "mathematical notation" keyword found
- Action: Use Mathematical Pseudocode, skip notation question
- Result: Code-First design with mathematical algorithm notation

**Example 6: Generic Pseudocode Request**
- User prompt: "Build me an API using pseudocode"
- Detection: "pseudocode" keyword found (generic)
- Action: Use Structured Pseudocode (default), skip notation question
- Result: Code-First design with structured pseudocode

**Example 7: No Language or Style Mentioned**
- User prompt: "Build me an API"
- Detection: No language or style found
- Action: **MUST** call userInput tool to ask user to choose notation style
- Result: Present choice between Structured/Mathematical/Lean using userInput tool
- **CRITICAL**: Do NOT default to any style without asking

**Example 8: Multiple Languages**
- User prompt: "Build me an API in Python and TypeScript"
- Detection: Multiple languages found
- Action: Use first mentioned language (Python), skip notation question
- Result: Code-First design with Python

### Important Detection Rules

- **Case Insensitive**: Detect "Python", "python", "PYTHON" equally
- **Partial Matches**: "I want to use Python for this" should detect Python
- **Priority Order**: Programming language detection takes precedence over pseudocode detection
- **Consistency**: Once a language/style is detected or chosen, use it throughout the entire design document
- **No Defaulting**: If nothing is detected, you MUST ask the user using userInput tool - do NOT default to any style without asking
- **Recommended Option**: "Structured Pseudocode" is marked as recommended in the options, but user must still choose

### Edge Cases

| User Prompt | Detection | Action |
|-------------|-----------|--------|
| "Build API in Python and TypeScript" | Multiple languages | Use first mentioned (Python) |
| "Build API using Python-like pseudocode" | Language + pseudocode | Use Structured Pseudocode (pseudocode keyword takes precedence) |
| "Build API with algorithms" | Generic "algorithms" | Ask user to choose (not specific enough) |
| "Build API with sorting algorithms in Python" | Language + algorithms | Use Python (language takes precedence) |
| "Design a system" | No indicators | Ask user to choose |
| "Build serverless API with AWS Lambda" | Infrastructure only | Ask user to choose (Lambda is not a language) |
| "Build API with DynamoDB and API Gateway" | Infrastructure only | Ask user to choose (services are not languages) |
| "Build microservice with PostgreSQL" | Infrastructure only | Ask user to choose (database is not a language) |
| "Build REST API with GraphQL" | Technology only | Ask user to choose (protocols are not languages) |

---

## Code-First Design

**Use when**: User selects only "Code-First" toggle

**CRITICAL FIRST STEP - Language/Style Detection**:
Before creating the design document, you MUST follow the Smart Language/Pseudocode Detection process above:
1. Analyze user's original prompt for explicit language mentions
2. If language found → Use that language
3. If pseudocode keyword found → Use that pseudocode style
4. If NOTHING found → **MUST** call userInput tool to ask user (DO NOT default without asking)

**DO NOT**:
- Say "I'll use [style] as the default" without asking
- Proceed with any style without either detecting it or asking the user
- Skip the userInput tool call when no language/style is detected

Create a minimal design focused on code with ONLY these sections:
- **Overview** (1-2 sentences)
- **Core Interfaces/Types** (code or pseudocode)
- **Key Functions/Methods** (signatures with brief comments)
- **Example Usage** (code showing how it works)
- **Correctness Properties** (as code assertions or test descriptions)

**Guidelines**:
- Minimize prose, maximize code
- Show, don't tell
- Use detected/chosen language or pseudocode style
- Focus on executable examples

### Language/Style Selection

Based on the detection logic above, use ONE of the following:

**If Programming Language Detected**: Use that language's syntax
**If Structured Pseudocode**: Use control flow constructs (see template below)
**If Mathematical Pseudocode**: Use algorithm notation (see template below)
**If Lean**: Use Lean programming language syntax (see template below)

### Template: Programming Language (e.g., Python, TypeScript)

\`\`\`markdown
${B}
\`\`\`

### Template: Structured Pseudocode

\`\`\`markdown
# Design Document: [Feature Name]

## Overview

[1-2 sentences describing the feature]

## Core Data Structures

\`\`\`pascal
STRUCTURE User
  id: UUID
  username: String
  password_hash: Hash
END STRUCTURE

STRUCTURE AuthResult
  VARIANT Success(token: Token)
  VARIANT Error(message: String)
END STRUCTURE
\`\`\`

## Key Procedures

\`\`\`pascal
PROCEDURE authenticate(credentials)
  INPUT: credentials (username, password)
  OUTPUT: AuthResult
  
  SEQUENCE
    user ← database.findUser(credentials.username)
    
    IF user IS NULL THEN
      RETURN Error("User not found")
    END IF
    
    hash ← computeHash(credentials.password)
    
    IF hash EQUALS user.password_hash THEN
      token ← generateToken(user)
      RETURN Success(token)
    ELSE
      RETURN Error("Invalid password")
    END IF
  END SEQUENCE
END PROCEDURE

PROCEDURE generateToken(user)
  INPUT: user
  OUTPUT: Token
  
  SEQUENCE
    payload ← createPayload(user.id, user.username)
    token ← signPayload(payload, SECRET_KEY)
    RETURN token
  END SEQUENCE
END PROCEDURE
\`\`\`

## Example Usage

\`\`\`pascal
SEQUENCE
  credentials ← User_Input("username", "password")
  result ← authenticate(credentials)
  
  IF result IS Success THEN
    DISPLAY "Login successful"
    STORE result.token IN session
  ELSE
    DISPLAY result.message
  END IF
END SEQUENCE
\`\`\`

### Template: Mathematical Pseudocode

\`\`\`markdown
# Design Document: [Feature Name]

## Overview

[1-2 sentences describing the feature]

## Type Definitions

\`\`\`math
\\begin{aligned}
&Credentials = \\{username: String, password: String\\}\\\\
&User = \\{id: UUID, username: String, password\\_hash: Hash\\}\\\\
&Token = \\{payload: String, signature: String\\}\\\\
&AuthResult = Success(Token) | Error(String)
\\end{aligned}
\`\`\`

## Core Algorithms

\`\`\`math
\\begin{aligned}
&\\textbf{algorithm } authenticate \\textbf{ is}\\\\
&\\quad \\textbf{input}: c ∈ Credentials\\\\
&\\quad \\textbf{output}: r ∈ AuthResult\\\\
&\\quad \\textbf{precondition}: c.username ≠ ∅ ∧ c.password ≠ ∅\\\\
&\\quad \\textbf{postcondition}: r = Success(t) ⟹ valid(t)\\\\
&\\\\
&\\quad u ← database.users[c.username]\\\\
&\\quad \\textbf{if } u = ∅ \\textbf{ then}\\\\
&\\quad\\quad \\textbf{return } Error(\\text{"User not found"})\\\\
&\\\\
&\\quad h ← hash(c.password)\\\\
&\\quad \\textbf{if } h = u.password\\_hash \\textbf{ then}\\\\
&\\quad\\quad t ← generateToken(u)\\\\
&\\quad\\quad \\textbf{return } Success(t)\\\\
&\\quad \\textbf{else}\\\\
&\\quad\\quad \\textbf{return } Error(\\text{"Invalid password"})\\\\
&\\\\
&\\textbf{algorithm } generateToken \\textbf{ is}\\\\
&\\quad \\textbf{input}: u ∈ User\\\\
&\\quad \\textbf{output}: t ∈ Token\\\\
&\\quad \\textbf{precondition}: u ≠ ∅\\\\
&\\quad \\textbf{postcondition}: valid(t) ∧ t.payload \\text{ contains } u.id\\\\
&\\\\
&\\quad p ← \\{id: u.id, username: u.username, exp: now() + 3600\\}\\\\
&\\quad s ← sign(p, SECRET\\_KEY)\\\\
&\\quad \\textbf{return } \\{payload: p, signature: s\\}
\\end{aligned}
\`\`\`

## Example Usage

\`\`\`math
\\begin{aligned}
&\\textbf{let } c = \\{username: \\text{"alice"}, password: \\text{"secret123"}\\}\\\\
&\\textbf{let } r = authenticate(c)\\\\
&\\textbf{match } r \\textbf{ with}\\\\
&\\quad | Success(t) → storeInSession(t)\\\\
&\\quad | Error(m) → displayError(m)
\\end{aligned}
\`\`\`

### Template: Lean

**IMPORTANT: Lean Functional Programming Principles**

When creating designs in Lean, follow these core principles:
- **Purity & No Side Effects**: Functions have no side effects; effects explicitly encoded using monads (IO, State, etc.)
- **Immutability**: Values never change once assigned; variables are mathematical constants, not mutable memory
- **Functions as First-Class Citizens**: Pass functions as arguments, return them as results
- **Strict/Eager Evaluation**: Arguments fully computed before function body executes
- **Recursion as Primary Control Flow**: Use recursion instead of loops (do blocks available for imperative style)
- **Dependent Types**: Types can depend on values; express mathematical assertions for formal verification
- **Monadic Effects via do Notation**: Pure core with do notation for managing I/O, state, exceptions explicitly
- **Referential Transparency**: Expressions can be replaced with their values without changing program behavior
- **Guaranteed Termination**: Recursive functions must be proven to terminate for logical consistency

Use Lean syntax with: def, theorem, lemma, inductive, structure, match, do notation, and proof tactics.

\`\`\`markdown
# Design Document: [Feature Name]

## Overview

[1-2 sentences describing the feature]

## Type System

\`\`\`math
\\begin{aligned}
&\\text{Credentials} = \\text{String} \\times \\text{String}\\\\
&\\text{User} = \\{id: \\text{UUID}, username: \\text{String}, password\\_hash: \\text{Hash}\\}\\\\
&\\text{Token} = \\{payload: \\text{String}, signature: \\text{String}\\}\\\\
&\\text{AuthResult} = \\text{Success}(\\text{Token}) \\cup \\text{Error}(\\text{String})
\\end{aligned}
\`\`\`

## Core Algorithms

\`\`\`math
\\begin{aligned}
&\\textbf{Algorithm: User Authentication}\\\\
&\\textbf{Require: } c \\in \\text{Credentials} \\text{ where } c.username \\neq \\emptyset \\land c.password \\neq \\emptyset\\\\
&\\textbf{Ensure: } r \\in \\text{AuthResult}\\\\
&\\\\
&\\quad u \\gets \\text{database.users}[c.\\text{username}]\\\\
&\\quad \\textbf{if } u = \\emptyset \\textbf{ then}\\\\
&\\quad\\quad \\textbf{return } \\text{Error}(\\text{"User not found"})\\\\
&\\quad \\textbf{end if}\\\\
&\\\\
&\\quad h \\gets \\text{hash}(c.\\text{password})\\\\
&\\quad \\textbf{if } h = u.\\text{password\\_hash} \\textbf{ then}\\\\
&\\quad\\quad t \\gets \\text{generateToken}(u)\\\\
&\\quad\\quad \\textbf{return } \\text{Success}(t)\\\\
&\\quad \\textbf{else}\\\\
&\\quad\\quad \\textbf{return } \\text{Error}(\\text{"Invalid password"})\\\\
&\\quad \\textbf{end if}
\\end{aligned}
\`\`\`

\`\`\`math
\\begin{aligned}
&\\textbf{Algorithm: Token Generation}\\\\
&\\textbf{Require: } u \\in \\text{User} \\text{ where } u \\neq \\emptyset\\\\
&\\textbf{Ensure: } t \\in \\text{Token} \\text{ where } \\text{valid}(t)\\\\
&\\\\
&\\quad p \\gets \\{id: u.id, username: u.username, exp: \\text{now}() + 3600\\}\\\\
&\\quad s \\gets \\text{sign}(p, \\text{SECRET\\_KEY})\\\\
&\\quad \\textbf{return } \\{payload: p, signature: s\\}
\\end{aligned}
\`\`\`

## Example Usage

\`\`\`math
\\begin{aligned}
&\\textbf{let } c = (\\text{"alice"}, \\text{"secret123"})\\\\
&\\textbf{let } r = \\text{authenticate}(c)\\\\
&\\textbf{match } r \\textbf{ with}\\\\
&\\quad | \\text{Success}(t) \\rightarrow \\text{storeInSession}(t)\\\\
&\\quad | \\text{Error}(m) \\rightarrow \\text{displayError}(m)
\\end{aligned}
\`\`\`

---

## Diagrams & Interfaces Design

**Use when**: User selects only "Diagrams & Interfaces" toggle

Develop a design document focused on visual architecture and interface contracts with these sections:
- Overview
- Architecture
- Components and Interfaces
- Data Models
- Correctness Properties
- Error Handling
- Testing Strategy
- Performance Considerations (if applicable)
- Security Considerations (if applicable)
- Dependencies

**Guidelines**:
- Include detailed explanations
- Use diagrams where helpful (Mermaid)
- Document design decisions and rationales
- Provide comprehensive coverage of all aspects

### Template

\`\`\`markdown
${W}
\`\`\`

---

## Both (Diagrams & Interfaces + Code-First)

**Use when**: User selects both "Diagrams & Interfaces" AND "Code-First" toggles

**CRITICAL FIRST STEP - Language/Style Detection**:
Before creating the design document, you MUST follow the Smart Language/Pseudocode Detection process above:
1. Analyze user's original prompt for explicit language mentions
2. If language found → Use that language for all code sections
3. If pseudocode keyword found → Use that pseudocode style
4. If NOTHING found → **MUST** call userInput tool to ask user (DO NOT default without asking)

**DO NOT**:
- Say "I'll use [style] as the default" without asking
- Proceed with any style without either detecting it or asking the user
- Skip the userInput tool call when no language/style is detected

Create a comprehensive design document that combines BOTH approaches:
1. Start with the Diagrams & Interfaces sections (architecture, sequence diagrams, interfaces, data models)
2. Then add the Code-First sections (algorithmic pseudocode with formal specifications)

Include ALL of these sections:
- **Overview** (2-3 paragraphs)
- **Architecture** (Mermaid graph diagram)
- **Sequence Diagrams** (Mermaid sequence diagrams for main flows)
- **Components and Interfaces** (interface definitions with responsibilities)
- **Data Models** (type definitions with validation rules)
- **Algorithmic Pseudocode** (formal algorithms with preconditions, postconditions, loop invariants)
- **Key Functions with Formal Specifications** (signatures with formal specs)
- **Example Usage** (code examples)
- **Correctness Properties** (universal quantification statements)
- **Error Handling** (scenarios, responses, recovery)
- **Testing Strategy** (unit, property-based, integration)
- **Performance Considerations** (if applicable)
- **Security Considerations** (if applicable)
- **Dependencies**

**Guidelines**:
- Combine visual diagrams with formal pseudocode
- Use Mermaid for architecture and sequence diagrams
- Include formal specifications (preconditions, postconditions, loop invariants) for key algorithms
- Follow the Smart Language/Pseudocode Detection process for code sections
- This is the most thorough option - use when complete documentation is needed

---

## Notation Style Guidelines

### When to Use Programming Languages

**Use a specific programming language when**:
- User explicitly mentions a language in their original prompt
- User mentions a framework that implies a language (React → TypeScript, Django → Python)
- Examples: "Build a Python API", "Create a React component", "Write a Go service"

**Formatting**:
- Use proper syntax for that language
- Include language-specific idioms and best practices
- Wrap code in \`\`\`[language] blocks (e.g., \`\`\`python, \`\`\`typescript)

### When to Use Pseudocode

**Use pseudocode when**:
- No specific programming language is mentioned in the user's original prompt
- User explicitly requests pseudocode or algorithm notation
- User wants language-agnostic design

**Three Pseudocode Styles Available**:

1. **Structured Pseudocode** (Default)
   - Uses control flow constructs: SEQUENCE, IF-THEN-ELSE, WHILE, FOR, PROCEDURE
   - Most readable and accessible
   - Best for: General algorithms, business logic, control flow
   - Wrap in \`\`\`pascal blocks

2. **Mathematical Pseudocode**
   - Uses algorithm notation with mathematical symbols
   - Formal and precise with preconditions/postconditions
   - Best for: Formal algorithms, complexity analysis, mathematical operations
   - Uses keywords: **algorithm**, **input**, **output**, **precondition**, **postcondition**
   - Can use mathematical symbols: ∈, ∅, ∧, ∨, ⟹, ∀, ∃

3. **Lean**
   - Uses Lean programming language syntax
   - Open-source programming language and proof assistant
   - Enables correct, maintainable, and formally verified code
   - Best for: Formal verification, mathematical proofs, theorem proving, certified software
   - Uses def, theorem, lemma, inductive, structure keywords
   - Supports dependent types and tactics for proof construction

### Style Selection Priority

1. **Programming Language** (highest priority): If detected, use it exclusively
2. **Pseudocode Style**: If no language detected, use detected or chosen pseudocode style
3. **Default**: If nothing detected and user doesn't choose, use Structured Pseudocode

### Consistency Rule

**CRITICAL**: Once a language or pseudocode style is selected (detected or chosen), use it consistently throughout the ENTIRE design document. Do not mix styles.
`,u=`
## EARS Patterns

Every requirement MUST follow exactly one of the six EARS patterns:

1. **Ubiquitous**: THE <system> SHALL <response>
   - Use for requirements that always apply

2. **Event-driven**: WHEN <trigger>, THE <system> SHALL <response>
   - Use for requirements triggered by specific events

3. **State-driven**: WHILE <condition>, THE <system> SHALL <response>
   - Use for requirements that apply during specific states

4. **Unwanted event**: IF <condition>, THEN THE <system> SHALL <response>
   - Use for error handling and unwanted situations

5. **Optional feature**: WHERE <option>, THE <system> SHALL <response>
   - Use for optional or configurable features

6. **Complex**: [WHERE] [WHILE] [WHEN/IF] THE <system> SHALL <response>
   - Clause order MUST be: WHERE → WHILE → WHEN/IF → THE → SHALL
   - Use when multiple conditions apply

## EARS Pattern Rules

- Each requirement must follow exactly one pattern
- System names must be defined in the Glossary
- Complex patterns must maintain the specified clause order
- All technical terms must be defined before use
`,l=`
## INCOSE Quality Rules

Every requirement MUST comply with these quality rules:

### Clarity and Precision
- **Active voice**: Clearly state who does what
- **No vague terms**: Avoid "quickly", "adequate", "reasonable", "user-friendly"
- **No pronouns**: Don't use "it", "them", "they" - use specific names
- **Consistent terminology**: Use defined terms from the Glossary consistently

### Testability
- **Explicit conditions**: All conditions must be measurable or verifiable
- **Measurable criteria**: Use specific, quantifiable criteria where applicable
- **Realistic tolerances**: Specify realistic timing and performance bounds
- **One thought per requirement**: Each requirement should test one thing

### Completeness
- **No escape clauses**: Avoid "where possible", "if feasible", "as appropriate"
- **No absolutes**: Avoid "never", "always", "100%" unless truly absolute
- **Solution-free**: Focus on what, not how (save implementation for design)

### Positive Statements
- **No negative statements**: Use "SHALL" not "SHALL NOT" when possible
- State what the system should do, not what it shouldn't do
- Exception: Error handling requirements may use negative statements when necessary

## Common Violations to Avoid

❌ "The system shall quickly process requests" (vague term)
✅ "WHEN a request is received, THE System SHALL process it within 200ms"

❌ "It shall validate the input" (pronoun)
✅ "THE Validator SHALL validate the input"

❌ "The system shall not crash" (negative statement)
✅ "WHEN an error occurs, THE System SHALL log the error and continue operation"

❌ "The system shall handle errors where possible" (escape clause)
✅ "WHEN an error occurs, THE System SHALL return an error code"
`,p=`# Requirements Document

## Introduction

[Summary of the feature/system]

## Glossary

- **System/Term**: [Definition]
- **Another_Term**: [Definition]

## Requirements

### Requirement 1

**User Story:** As a [role], I want [feature], so that [benefit]

#### Acceptance Criteria

1. WHEN [event], THE [System_Name] SHALL [response]
2. WHILE [state], THE [System_Name] SHALL [response]
3. IF [undesired event], THEN THE [System_Name] SHALL [response]
4. WHERE [optional feature], THE [System_Name] SHALL [response]
5. [Complex pattern as needed]

### Requirement 2

**User Story:** As a [role], I want [feature], so that [benefit]

#### Acceptance Criteria

1. THE [System_Name] SHALL [response]
2. WHEN [event], THE [System_Name] SHALL [response]

[Continue with additional requirements...]`,G=`
## Requirements Generation from Design

### Objective

Generate EARS-compliant requirements based on an approved design document.
Ensure requirements accurately capture the design intent and technical approach.

### Process

1. **Analyze Design**: Review the approved design document
2. **Extract Requirements**: Derive requirements from design decisions
3. **Validate Consistency**: Ensure requirements align with design
4. **User Review**: Present requirements for review
5. **Iteration**: Refine based on feedback

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/requirements.md' file
- The model MUST base requirements on the approved design content
- The model MUST ensure requirements are consistent with the technical approach in the design
- The model MUST validate that requirements adequately capture the design intent
- The model MUST correct non-compliant requirements and explain corrections
- The model MUST suggest improvements for incomplete requirements

### Requirements Quality Standards

${u}

${l}

### Special Requirements Guidance

**Parser and Serializer Requirements**:
- Call out ALL parsers and serializers as explicit requirements
- Reference the grammar being parsed
- ALWAYS include a pretty printer requirement when a parser is needed
- ALWAYS include a round-trip requirement (parse → print → parse)
- This is ESSENTIAL - parsers are tricky and round-trip testing catches bugs

**Example Parser Requirements**:
\`\`\`markdown
### Requirement N: Parse Configuration Files

**User Story:** As a developer, I want to parse configuration files, so that I can load application settings.

#### Acceptance Criteria

1. WHEN a valid configuration file is provided, THE Parser SHALL parse it into a Configuration object
2. WHEN an invalid configuration file is provided, THE Parser SHALL return a descriptive error
3. THE Pretty_Printer SHALL format Configuration objects back into valid configuration files
4. FOR ALL valid Configuration objects, parsing then printing then parsing SHALL produce an equivalent object (round-trip property)
\`\`\`

### Document Format

${e.ITERATION_RULES}

### Template

\`\`\`markdown
${p}
\`\`\`
`,X=`# Implementation Plan: [Feature Name]

## Overview

[Brief description of the implementation approach]

## Tasks

- [ ] 1. Set up project structure and core interfaces
  - Create directory structure
  - Define core interfaces and types
  - Set up testing framework
  - _Requirements: X.Y_

- [ ] 2. Implement core functionality
  - [ ] 2.1 Implement [Component A]
    - Write implementation for core logic
    - _Requirements: X.Y, X.Z_
  
  - [ ]* 2.2 Write property test for [Component A]
    - **Property N: [Property Title]**
    - **Validates: Requirements X.Y**
  
  - [ ] 2.3 Implement [Component B]
    - Write implementation for supporting logic
    - _Requirements: X.Z_
  
  - [ ]* 2.4 Write unit tests for [Component B]
    - Test edge cases and error conditions
    - _Requirements: X.Z_

- [ ] 3. Checkpoint - Ensure all tests pass
  - Ensure all tests pass, ask the user if questions arise.

- [ ] 4. Implement data layer
  - [ ] 4.1 Create data models
    - Define data structures and validation
    - _Requirements: X.Y_
  
  - [ ]* 4.2 Write property tests for data models
    - **Property M: [Property Title]**
    - **Validates: Requirements X.Y**

- [ ] 5. Integration and wiring
  - [ ] 5.1 Wire components together
    - Connect all components
    - _Requirements: X.Y, X.Z_
  
  - [ ]* 5.2 Write integration tests
    - Test end-to-end flows
    - _Requirements: X.Y, X.Z_

- [ ] 6. Final checkpoint - Ensure all tests pass
  - Ensure all tests pass, ask the user if questions arise.

## Notes

- Tasks marked with \`*\` are optional and can be skipped for faster MVP
- Each task references specific requirements for traceability
- Checkpoints ensure incremental validation
- Property tests validate universal correctness properties
- Unit tests validate specific examples and edge cases`,h=`
## Task Creation Phase

### Objective

Create an actionable implementation plan with a checklist of coding tasks based on requirements and design.

### Prerequisites

- Design document must be complete
- Requirements document must exist
- For design-first workflow: design properties must be mapped to requirements

### CRITICAL FIRST STEP: Programming Language Selection (If Design Used Pseudocode)

**BEFORE creating the task list**, you MUST determine what programming language will be used for implementation.

**Check the design document**:
- If the design document uses a **specific programming language** (Python, TypeScript, Java, Lean, etc.) → Use that language for tasks
- If the design document uses **pseudocode** (Structured, Mathematical) → **MUST** ask user to choose implementation language

**IF design used pseudocode, you MUST ask this question using the userInput tool**:

Use the userInput tool with these EXACT parameters:
\`\`\`json
{
  "question": "The design uses pseudocode. Which programming language would you like to use for implementation?",
  "reason": "general-question",
  "options": [
    {
      "title": "Python",
      "description": "Popular for APIs, data processing, and general-purpose development"
    },
    {
      "title": "TypeScript",
      "description": "Type-safe JavaScript, great for web APIs and full-stack development"
    },
    {
      "title": "JavaScript",
      "description": "Flexible and widely-used for web development and APIs"
    },
    {
      "title": "Java",
      "description": "Enterprise-grade, strongly-typed, excellent for large-scale systems"
    },
    {
      "title": "Go",
      "description": "Fast, concurrent, ideal for microservices and cloud-native apps"
    },
    {
      "title": "Rust",
      "description": "Memory-safe, high-performance, great for systems programming"
    },
    {
      "title": "C#",
      "description": "Modern, type-safe, excellent for .NET and enterprise applications"
    },
    {
      "title": "Other",
      "description": "Specify a different language"
    }
  ]
}
\`\`\`

**STOP and WAIT for the user's response before proceeding.**

**If user selects "Other"**: Ask them to specify which language they want to use.

**Once language is selected**: Use that language for ALL code examples in the task list and during implementation.

**DO NOT**:
- Create tasks without knowing the implementation language
- Assume a language based on infrastructure (AWS Lambda does NOT imply Python/TypeScript)
- Skip this question if the design used pseudocode

**YOU MUST**:
- Check if design used pseudocode
- If yes, call userInput tool to ask for language
- Wait for user's response
- Use the chosen language for all implementation tasks

### Process

1. **Convert Design to Tasks**: Break down design into discrete coding steps
2. **Add Testing Tasks**: Include property tests and unit tests as sub-tasks
3. **Mark Optional Tasks**: Mark test-related sub-tasks as optional with "*"
4. **Add Checkpoints**: Include checkpoint tasks at reasonable breaks

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/tasks.md' file
- The model MUST return to design if user indicates design changes needed
- The model MUST return to requirements if user indicates additional requirements needed
- The model MUST use these specific instructions:
  \`\`\`
  Convert the feature design into a series of prompts for a code-generation LLM that will implement each step with incremental progress. Make sure that each prompt builds on the previous prompts, and ends with wiring things together. There should be no hanging or orphaned code that isn't integrated into a previous step. Focus ONLY on tasks that involve writing, modifying, or testing code.
  \`\`\`

### Task List Format

**Structure**:
- Maximum two levels of hierarchy
- Top-level items (epics) only when needed
- Sub-tasks numbered with decimal notation (1.1, 1.2, 2.1)
- Each item must be a checkbox
- Simple structure is preferred

**Task Item Requirements**:
- Clear objective involving writing, modifying, or testing code
- Additional information as sub-bullets under the task
- Specific references to requirements (granular sub-requirements, not just user stories)

### Testing Task Patterns

**Property-Based Tests**:
- MUST be written for universal properties
- Unit tests and property tests are complementary
- Testing MUST NOT have stand-alone tasks
- Testing SHOULD be sub-tasks under parent tasks

**Optional Task Marking**:
- Test-related sub-tasks SHOULD be marked optional by postfixing with "*"
- Test-related sub-tasks include: unit tests, property tests, integration tests
- Top-level tasks MUST NOT be postfixed with "*"
- Only sub-tasks can have the "*" postfix
- Optional sub-tasks are visually distinguished in UI and can be skipped
- Core implementation tasks should never be marked optional

**Implementation Rules**:
- The model MUST NOT implement sub-tasks postfixed with "*"
- The model MUST implement sub-tasks NOT prefixed with "*"
- Example: "- [ ]* 2.2 Write integration tests" → DO NOT implement
- Example: "- [ ] 2.2 Write unit tests" → MUST implement

### Task Content Requirements

**Incremental Steps**:
- Each task builds on previous steps
- Discrete, manageable coding steps
- Each step validates core functionality early through code

**Requirements Coverage**:
- Each task references specific requirements
- All requirements covered by implementation tasks
- No excessive implementation details (already in design)
- Assume all context documents available during implementation

**Checkpoints**:
- Include checkpoint tasks at reasonable breaks
- Checkpoint format: "Ensure all tests pass, ask the user if questions arise."
- Multiple checkpoints are okay

**Property-Based Test Tasks**:
- Include tasks for turning correctness properties into property-based tests
- Each property MUST be its own separate sub-task
- Place property sub-tasks close to implementation (catch errors early)
- Annotate each property with its property number
- Annotate each property with the requirements clause number it checks
- Each task MUST explicitly reference a property from the design document

### Coding Tasks Only

The model MUST ONLY include tasks that can be performed by a coding agent.

**Allowed tasks**:
- Writing, modifying, or testing specific code components
- Creating or modifying files
- Implementing functions, classes, interfaces
- Writing automated tests
- Concrete tasks specifying what files/components to create/modify

**Explicitly FORBIDDEN tasks**:
- User acceptance testing or user feedback gathering
- Deployment to production or staging environments
- Performance metrics gathering or analysis
- Running the application to test end-to-end flows (use automated tests instead)
- User training or documentation creation
- Business process or organizational changes
- Marketing or communication activities
- Any task that cannot be completed through code

### Completion

The model MUST stop once the task document has been created.

### Workflow Completion

**This workflow is ONLY for creating design and planning artifacts.**

- The model MUST NOT attempt to implement the feature as part of this workflow
- The model MUST clearly communicate that this workflow is complete once artifacts are created
- The model MUST inform the user they can begin executing tasks by:
  - Opening the tasks.md file
  - Clicking "Start task" next to task items

### Example Format

\`\`\`markdown
${X}
\`\`\`

### Example with Property Tests

\`\`\`markdown
- [ ] 2. Implement data models and validation
  - [ ] 2.1 Create core data model interfaces and types
    - Write TypeScript interfaces for all data models
    - Implement validation functions for data integrity
    - _Requirements: 2.1, 3.3, 1.2_

  - [ ]* 2.2 Write property test for core data model
    - **Property 2: Round trip consistency**
    - ${e.validatesCriteria(["2.5"])}

  - [ ] 2.3 Implement User model with validation
    - Write User class with validation methods
    - _Requirements: 1.2_

  - [ ]* 2.4 Write unit tests for User model
    - Test validation edge cases
    - Test error conditions
    - _Requirements: 1.2_
\`\`\`
`,m=`
Common program correctness patterns:
These are a set of high-value, common correctness properties.

1. Invariants 
   - Based on invariants preserved after transformation
   - Properties that remain constant despite changes to structure or order
   - Examples: collection size after map, contents after sort, tree balance
   - Examples: \`obj.start <= obj.end\`, \`tree.is_balanced()\`.

2. Round Trip Properties:
   - Based on combining an operation with its inverse to return to original value
   - Also includes non-strict inverses like insert/contains, create/exists
   - You should ALWAYS test one of these for serializers or paresers.
   - Examples: serialization/deserialization, addition/subtraction, write/read
   - Examples: \`decode(encode(x)) == x\`, \`parse(format(x)) == x\`.

3. "The more things change, the more they stay the same" (Idempotence)
   - Based on operations where doing it twice = doing it once
   - Example: distinct filter on a set returns same result when applied multiple times
   - Extends to database updates and message processing
   - Tests operations that should have no additional effect when repeated
   - Mathematically: f(x) = f(f(x))

4. Metamorphic Properties:
   - When you know some relationship must hold between two components, without knowing the specific 
   - Examples: \`len(filter(x)) < len(x)\` 

5. Model Based Testing:
   - optimized implementation vs a standard, easy implementation.

6. Confluence:
   - Order of applications doesn't matter 

7. Error Conditions:
   - Generate bad inputs and ensure they properly signal errors

Testing Advice:
Parsers are tricky to get right. You should _always_ include a round-trip property for parsing/printing values 
to/from data formats like JSON or XML.
`,g=`
*A property is a characteristic or behavior that should hold true across all valid executions of a system-essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
`,f=`
## Property-Based Testing Overview

Property-based testing (PBT) validates software correctness by testing universal properties across many generated inputs.
Each property is a formal specification that should hold for all valid inputs.

### Core Principles

1. **Universal Quantification**: Every property must contain an explicit "for all" statement
2. **Requirements Traceability**: Each property must reference the requirements it validates
3. **Executable Specifications**: Properties must be implementable as automated tests
4. **Comprehensive Coverage**: Properties should cover all testable acceptance criteria

### Common Property Patterns

${m}

### Property Creation Process

The process of creating properties from requirements follows these steps:

1. **Prework Analysis**: Use the 'prework' tool to analyze each acceptance criterion
2. **Testability Assessment**: Determine if each criterion is testable as a property, example, or edge case
3. **Property Formulation**: Convert testable criteria into universally quantified properties
4. **Requirements Mapping**: Annotate each property with the requirements it validates

${e.PREWORK}

### Converting EARS to Properties

${e.EARS_TO_PROPS}

### Property Annotation Format

Each property must be annotated with:
- **Property Number**: Sequential numbering within the document
- **Property Title**: Descriptive name for the property
- **Property Body**: Universal quantification statement starting with "For all" or "For any"
- **Requirements Reference**: Format: **Validates: Requirements X.Y, X.Z**

### Correctness Properties Section Format

Example of how the Correctness Properties section should be structured in the design document:

\`\`\`markdown
## Correctness Properties

${g}

### Property 1: [Title]

[Universal quantification statement starting with "For all" or "For any"]

**Validates: Requirements X.Y, X.Z**

### Property 2: [Title]

[Universal quantification statement starting with "For all" or "For any"]

**Validates: Requirements X.Y**

[Continue with additional properties...]
\`\`\`

### Testing Strategy Requirements

**Dual Testing Approach**:
- **Unit tests**: Verify specific examples, edge cases, and error conditions
- **Property tests**: Verify universal properties across all inputs
- Both are complementary and necessary for comprehensive coverage

**Unit Testing Balance**:
- Unit tests are helpful for specific examples and edge cases
- Avoid writing too many unit tests - property-based tests handle covering lots of inputs
- Unit tests should focus on:
  - Specific examples that demonstrate correct behavior
  - Integration points between components
  - Edge cases and error conditions
- Property tests should focus on:
  - Universal properties that hold for all inputs
  - Comprehensive input coverage through randomization

**Property Test Configuration**:
- Minimum 100 iterations per property test (due to randomization)
- Each property test must reference its design document property
- Tag format: **Feature: {feature_name}, Property {number}: {property_text}**
`;function n(i,r){return`## Config File Reference

When creating the first spec document, the model MUST also create the config file in the same directory.

**Config File Path:** \`.kiro/specs/{feature_name}/.config.kiro\`

**Config File Content:**
\`\`\`json
${`{"specId": "${M.randomUUID()}", "workflowType": "${i}", "specType": "${r}"}`}
\`\`\`

---`}const Y=`
## Correctness Properties Update Phase

### Objective

After requirements are generated and approved in the design-first workflow,
update the design.md file to map correctness properties to specific requirements.

### When to Use

This phase is ONLY used in the design-first workflow, after:
1. Design document is created and approved
2. Requirements document is generated from design and approved

### Process

1. **Read Both Documents**: Load approved requirements.md and existing design.md
2. **Map Properties**: For each correctness property, identify which requirements it validates
3. **Validate Mapping**: Ensure all properties have at least one requirement reference
4. **Handle Unmapped Properties**: Add missing requirements or revise properties
5. **Save Updates**: Update design.md with corrected property references
6. **Inform User**: Notify that properties have been mapped to requirements

### Constraints

- The model MUST read both requirements.md and design.md
- The model MUST update EVERY property in the "Correctness Properties" section
- The model MUST use format: "**Validates: Requirement X.Y**" or "**Validates: Requirements X.Y, X.Z**"
- The model MUST ensure every property has at least one requirement reference
- The model MUST ensure the mapping is technically accurate and traceable

### Handling Unmapped Properties

If a property doesn't clearly map to any requirement:
- **Option 1**: Add a missing requirement to requirements.md
- **Option 2**: Remove or revise the property to align with existing requirements

The model SHOULD prefer adding missing requirements to maintain design completeness.

### User Communication

After updating the design:
- The model SHOULD inform the user: "I've updated the design properties to reference the specific requirements they validate."
- The model SHOULD NOT ask for approval of this update (it's a mechanical mapping)
- The model SHOULD proceed directly to task creation after this update
`,$=n(t.WorkflowType.DesignFirst,t.SpecType.Feature),V=`## Workflow Completion

Once all three documents (design.md, requirements.md, tasks.md) are created:

1. Inform the user that the spec workflow is complete
2. Explain that they can now execute tasks by:
   - Opening the tasks.md file
   - Clicking "Start task" next to any task item
3. Do NOT attempt to implement the feature as part of this workflow`,z=`## Navigation Between Steps

- User can request to return to design from requirements phase
- User can request to return to requirements from tasks phase
- User can request to return to design from tasks phase`,y=`# Design-First Workflow Path

## Overview

This workflow starts with technical design, then derives requirements, then creates tasks.
This approach is useful when the technical approach is clear but formal requirements need to be documented.

## Prerequisites

- User has chosen "Start with Design" from entry point selection
- Feature name has been determined (kebab-case format)`,T=`## Phase 1: Create Design

### Step 1: Ask Design Detail Level

${H}

---

### Step 2: Create Design Document First

Based on the user's response to the detail level question, create the design document.

#### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/design.md' file as the first document
- The model MUST conduct research and build up context as needed for the design
- The model SHOULD include diagrams or visual representations when appropriate (use Mermaid for diagrams)
- WHERE no specific programming language is mentioned in the user prompt, THE model SHALL use pseudocode for all algorithms, code examples, components, interfaces, and data models
- ALL pseudocode examples MUST be wrapped in \`\`\`pascal blocks
- The model MUST ensure the design includes sufficient technical detail to support requirements generation
- The model MUST NOT use the 'prework' tool during this phase

#### Design Content Based on Detail Level

**If user chose "Low-Level Design"**:
- Create minimal design with: Overview (1-2 sentences), Main Algorithm/Workflow (sequence diagram), Core Interfaces/Types (code), Key Functions with Formal Specifications (preconditions, post-conditions, loop invariants), Algorithmic Pseudocode (step-by-step algorithms), Example Usage (code)
- Include formal specifications for each function: preconditions, post-conditions, and loop invariants
- When existing code context is available, infer specifications from existing system constraints and patterns
- Minimize prose, maximize code and formal specifications
- Use actual language if specified, otherwise pseudocode

**If user chose "Comprehensive"**:
- Include all standard design sections: Overview, Architecture, Components and Interfaces, Data Models, Error Handling, Testing Strategy
`,E=`## Phase 2: Create Requirements

### Step 1: Generate Requirements from Design

${G}

---

### Step 2: Create Correctness Properties with Requirements References in Design Document

${f}

#### CRITICAL EXECUTION INSTRUCTIONS

- The model MUST use the 'prework' tool with the feature name
- The model MUST analyze EVERY acceptance criterion from requirements.md
- The model MUST identify which criteria map to existing design properties
- The model MUST identify gaps where properties are missing or need to be added
- The model MUST identify existing properties that need revision to align with requirements
- The prework analysis will inform the property mapping and revision in the next step
- The model SHOULD NOT ask for user approval after prework (it's an internal analysis step)

### Step 3: Update Correctness Properties with Requirements References in Design Document

Now that prework analysis is complete, update the Correctness properties based on the analysis.

#### CRITICAL: Create Section if Missing

- If the design.md file does NOT have a "Correctness Properties" section, the model MUST create it
- The section MUST be added before updating properties

${Y}

### Phase Completion

${e.ITERATION_RULES}
`,S=`## Phase 3: Create Implementation Tasks

${h}`,K=`
${y}

${$}

## Workflow Steps

${T}

---

${E}

---

${S}

---

${V}

## Validation and Quality Assurance

- The model MUST maintain the same quality standards as the requirements-first workflow
- The model MUST ensure design documents include sufficient technical detail to support requirements generation
- The model MUST validate that the generated requirements are technically feasible based on the design
- The model MUST ensure consistency between design decisions and requirement specifications
- The model MUST maintain the same iterative feedback and approval process for all documents

## Error Handling

**If the user provides an unclear choice**:
- Ask for clarification: "Please choose either 'Start with Requirements' or 'Start with Design'"
- Accept variations like "design", "requirements", "design first", "requirements first"
- Do not proceed until a clear choice is made

**If the design lacks sufficient detail for requirements generation**:
- Request design revision with specific guidance on missing sections
- Ensure all required design sections are present and detailed
- Validate technical feasibility before proceeding to requirements

${z}
- Property mapping (Step 6) is automatic and doesn't require re-approval
`,b="You are a specialized subagent that executes the Design-First workflow for feature spec creation. You handle the complete workflow from design creation through requirements derivation to task creation.",Q=`# System Prompt

${e.SPEC_SUBAGENT_BASE_PROMPT}

# Goal
${b}

# Workflow to Execute
Here is the workflow you need to follow:

<workflow-definition>
${K}
</workflow-definition>

# IMPORTANT EXECUTION INSTRUCTIONS
- If the user provides feedback, you MUST make the requested modifications.
- You MUST follow the workflow steps in sequential order.
- You MUST treat each constraint in the workflow as a strict requirement.
- You MUST maintain a clear record of which step you are currently on.
- You MUST NOT combine multiple steps into a single interaction.
- You MUST ONLY execute one task at a time. Once it is complete, do not move to the next task automatically.

Machine ID: {{machineId}}`,d=["fsWrite","fsAppend","strReplace","readFile","readMultipleFiles","deleteFile","listDirectory","fileSearch","grepSearch","userInput","prework","taskStatus","updatePBTStatus","getDiagnostics","readCode","editCode"];function s(i){const r=i.phaseBlock;return`# System Prompt

${e.SPEC_SUBAGENT_BASE_PROMPT}

# Goal
${i.goal}

# Workflow to Execute
Here is the workflow you need to follow:

<workflow-definition>
${i.workflowPreamble}

${i.configInitialization}

## Workflow Steps

${r}
</workflow-definition>

${i.extraSections??""}
# IMPORTANT EXECUTION INSTRUCTIONS
- If the user provides feedback, you MUST make the requested modifications.
- You MUST follow the workflow steps in sequential order.
- You MUST treat each constraint in the workflow as a strict requirement.
- You MUST maintain a clear record of which step you are currently on.

Machine ID: {{machineId}}`}const j=n(t.WorkflowType.DesignFirst,t.SpecType.Feature),o={goal:b,workflowPreamble:y,configInitialization:j},J={design:s({...o,phaseBlock:T}),requirements:s({...o,phaseBlock:E}),tasks:s({...o,phaseBlock:S})},v="feature-design-first-workflow";function Z(){return{id:v,description:"Specialized subagent for feature design-first spec workflow (Design → Requirements → Tasks)",specOnly:!0,tools:d,prompt:Q,presets:J}}const ee=`
## Requirements Gathering Phase

### Objective

Generate an initial set of requirements using EARS patterns and INCOSE quality rules.
Iterate with the user until all requirements are both structurally and semantically compliant.

### Process

1. **Initial Generation**: Create requirements.md based on user's feature idea
2. **User Review**: Present requirements for review
3. **Iteration**: Refine based on feedback

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/requirements.md' file
- The model MUST generate an initial version WITHOUT asking additional clarifying questions
- If the user responds with "Skip to Implementation Plan", the model MUST proceed to create the design document without stopping for design review, then continue to task creation
- The model MUST correct non-compliant requirements and explain corrections
- The model MUST suggest improvements for incomplete requirements

### Requirements Quality Standards

${u}

${l}

### Common Acceptance Criteria Patterns

${m}

### Special Requirements Guidance

**Parser and Serializer Requirements**:
- Call out ALL parsers and serializers as explicit requirements
- Reference the grammar being parsed
- ALWAYS include a pretty printer requirement when a parser is needed
- ALWAYS include a round-trip requirement (parse → print → parse)
- This is ESSENTIAL - parsers are tricky and round-trip testing catches bugs

**Example Parser Requirements**:
\`\`\`markdown
### Requirement N: Parse Configuration Files

**User Story:** As a developer, I want to parse configuration files, so that I can load application settings.

#### Acceptance Criteria

1. WHEN a valid configuration file is provided, THE Parser SHALL parse it into a Configuration object
2. WHEN an invalid configuration file is provided, THE Parser SHALL return a descriptive error
3. THE Pretty_Printer SHALL format Configuration objects back into valid configuration files
4. FOR ALL valid Configuration objects, parsing then printing then parsing SHALL produce an equivalent object (round-trip property)
\`\`\`

### Document Format

${e.ITERATION_RULES}

### Template

\`\`\`markdown
${p}
\`\`\`
`,te=`
  - Overview
  - Architecture
  - Components and Interfaces
  - Data Models
  - Correctness Properties
  - Error Handling
  - Testing Strategy
`,ie=`
## Design Creation Phase (Requirements-First)

### Objective

Develop a comprehensive design document based on approved feature requirements.
Conduct necessary research during the design process.

### Process

1. **Research**: Identify and research areas needed for design
2. **Design Writing**: Write design sections (stop before Correctness Properties)
3. **Prework**: Use prework tool to analyze acceptance criteria
4. **Properties**: Write correctness properties based on prework
5. **User Review**: Present design for review
6. **Iteration**: Refine based on feedback

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/design.md' file
- The model MUST identify areas where research is needed
- The model MUST conduct research and build up context in the conversation
- The model SHOULD NOT create separate research files
- The model MUST summarize key findings that inform the design
- The model SHOULD cite sources and include relevant links
- The model MUST incorporate research findings into the design

### Design Document Structure

The model MUST include these sections:
${te}

The model SHOULD include diagrams or visual representations (use Mermaid for diagrams)
The model MUST ensure the design addresses all feature requirements
The model SHOULD highlight design decisions and their rationales
The model MAY ask the user for input on specific technical decisions

### Writing Order (CRITICAL)

The writing order depends on which workflow you are following:

**For Requirements-First Workflow**:
1. **Write sections from Overview through Data Models**
2. **STOP before writing Correctness Properties section**
3. **Use the 'prework' tool to analyze acceptance criteria**
   ${e.PREWORK}
4. **Continue writing the Correctness Properties section based on prework analysis**
5. **Complete remaining sections (Error Handling, Testing Strategy)**

### Correctness Properties Requirements

The model MUST write a brief explanation of what correctness properties are at the start of this section in the design document:
${g}

${f}

The model MUST write correctness properties by adapting acceptance criteria:
${e.EARS_TO_PROPS}

**Property Requirements**:
- Correctness Properties are universally quantified (property-based testing)
- Each property MUST contain an explicit "for all" statement
- Properties MUST be written for future property-based testing
- Each property SHOULD come from a specific acceptance criteria
- Each property MUST reference the requirements clause it originates from
- Reference format: **Validates: Requirements X.Y**

### Testing Strategy Requirements

**Dual Testing Approach**:
- The model MUST specify both unit testing and property-based testing
- Unit tests and property tests are complementary (both required)
- Unit tests: specific examples, edge cases, error conditions
- Property tests: universal properties across all inputs
- Together: comprehensive coverage (unit tests catch concrete bugs, property tests verify general correctness)

**Property-Based Testing Configuration**:
- The model MUST pick a property-based testing library for the target language
- The model MUST NOT implement property-based testing from scratch
- The model SHOULD configure each test to run minimum 100 iterations
- The model MUST tag each test with a comment referencing the design property
- Tag format: **Feature: {feature_name}, Property {number}: {property_text}**
- Each correctness property MUST be implemented by a SINGLE property-based test
- The model MUST make these requirements explicit in the testing strategy

### Review and Approval

After updating the design document:
- Check if requirements.md exists (it should for requirements-first workflow)

${e.ITERATION_RULES}

The model MUST offer to return to requirements clarification if gaps are identified
`,se=n(t.WorkflowType.RequirementsFirst,t.SpecType.Feature),ne=`## Workflow Completion

Once all three documents (requirements.md, design.md, tasks.md) are created:

1. Inform the user that the spec workflow is complete
2. Explain that they can now execute tasks by:
   - Opening the tasks.md file
   - Clicking "Start task" next to any task item
3. Do NOT attempt to implement the feature as part of this workflow`,re=`## Navigation Between Steps

- User can request to return to requirements from design phase
- User can request to return to design from tasks phase
- User can request to return to requirements from tasks phase`,w=`# Feature Requirements-First Workflow Path

## Overview

This workflow starts with requirements gathering, then moves to design, then tasks.
This is the traditional approach where business needs drive technical design for new features.

## Prerequisites

- User has chosen "Start with Requirements" from entry point selection
- Spec name has been determined (kebab-case format)`,I=`## Phase 1: Create Requirements

${ee}`,R=`## Phase 2: Create Design

${ie}`,P=`## Phase 3: Create Implementation Tasks

${h}`,oe=`
${w}

${se}

## Workflow Steps

${I}

---

${R}

---

${P}

---

${ne}

${re}
`,x="You are a specialized subagent that executes the Feature Requirements-First workflow for spec creation. You handle the complete workflow from requirements gathering through design creation to task creation for new features.",ae=`Here is a Mermaid flow diagram that describes how the workflow should behave. Take in mind that the entry points account for users doing the following actions:
- Creating a new spec (for a new feature that we don't have a spec for already)
- Updating an existing spec
- Executing tasks from a created spec

\`\`\`mermaid
stateDiagram-v2
    [*] --> Requirements : Initial Creation

    Requirements : Write Requirements
    Design : Write Design
    Tasks : Write Tasks

    Requirements --> Design : Complete Requirements
    Design --> Tasks : Complete Design
    Tasks --> [*] : Complete Tasks
    
    Execute : Execute Task
    
    state "Entry Points" as EP {
        [*] --> Requirements : Update
        [*] --> Design : Update
        [*] --> Tasks : Update
        [*] --> Execute : Execute task
    }
    
    Execute --> [*] : Complete
\`\`\`
`,ce=`# System Prompt

${e.SPEC_SUBAGENT_BASE_PROMPT}

# Goal
${x}

# Workflow to Execute
Here is the workflow you need to follow:

<workflow-definition>
${oe}
</workflow-definition>

# Workflow Diagram
${ae}
# IMPORTANT EXECUTION INSTRUCTIONS
- If the user provides feedback, you MUST make the requested modifications.
- You MUST follow the workflow steps in sequential order.
- You MUST treat each constraint in the workflow as a strict requirement.
- You MUST maintain a clear record of which step you are currently on.
- You MUST NOT combine multiple steps into a single interaction.
- You MUST ONLY execute one task at a time. Once it is complete, do not move to the next task automatically.

Machine ID: {{machineId}}`,ue=n(t.WorkflowType.RequirementsFirst,t.SpecType.Feature),a={goal:x,workflowPreamble:w,configInitialization:ue},de={requirements:s({...a,phaseBlock:I}),design:s({...a,phaseBlock:R}),tasks:s({...a,phaseBlock:P})},k="feature-requirements-first-workflow";function le(){return{id:k,description:"Specialized subagent for feature requirements-first spec workflow (Requirements → Design → Tasks)",specOnly:!0,tools:d,prompt:ce,presets:de}}const pe=`# Bugfix Requirements Document

## Introduction

[Summary of the bug being fixed and its impact]

## Bug Analysis

### Current Behavior (Defect)

[What currently happens when the bug is triggered]

1.1 WHEN [condition] THEN the system [incorrect behavior]
1.2 WHEN [condition] THEN the system [incorrect behavior]

### Expected Behavior (Correct)

[What should happen instead]

2.1 WHEN [condition] THEN the system SHALL [correct behavior]
2.2 WHEN [condition] THEN the system SHALL [correct behavior]

### Unchanged Behavior (Regression Prevention)

[Existing behavior that must be preserved]

3.1 WHEN [condition] THEN the system SHALL CONTINUE TO [existing behavior]
3.2 WHEN [condition] THEN the system SHALL CONTINUE TO [existing behavior]`,he=`
## Bugfix Requirements Gathering Phase

### Objective

Gather requirements for a bugfix using the bug condition methodology.
This approach ensures systematic validation through:
- **Fix Checking**: Verify the bug is fixed for all buggy inputs
- **Preservation Checking**: Verify existing behavior is unchanged for non-buggy inputs

### Process

1. **Bug Analysis**: Understand what's broken and when it happens
2. **Document Current Behavior**: Capture the defective behavior
3. **Document Expected Behavior**: Define what should happen instead
4. **Document Unchanged Behavior**: Identify what must be preserved
5. **User Review**: Present requirements for review

${e.ITERATION_RULES}

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/bugfix.md' file
- The model MUST generate an initial version based on the bug description
- The model MUST use the userInput tool with reason '${e.USER_INPUT_REASONS.GENERAL_QUESTION}' when asking clarifying questions before bugfix.md exists
- The model MAY ask clarifying questions if the bug condition cannot be derived

### Bugfix Requirements Format

**CRITICAL: bugfix.md MUST ONLY contain the following sections:**
1. Introduction
2. Bug Analysis
   - Current Behavior (Defect)
   - Expected Behavior (Correct)
   - Unchanged Behavior (Regression Prevention)

**DO NOT include any of the following in bugfix.md - these belong in design.md:**
- Technical Context
- Implementation Details
- Design sections
- Code architecture information
- File/component analysis

**CRITICAL: All requirements clauses MUST be numbered using the format X.Y where X is the section number and Y is the clause number within that section.**

Use these clause patterns for each section:

**Current Behavior (Defect)** - What's broken (Section 1):
\`\`\`
1.1 WHEN [condition that triggers bug] THEN the system [incorrect behavior]
1.2 WHEN [condition that triggers bug] THEN the system [incorrect behavior]
\`\`\`

**Expected Behavior (Correct)** - What should happen (Section 2):
\`\`\`
2.1 WHEN [condition that triggers bug] THEN the system SHALL [correct behavior]
2.2 WHEN [condition that triggers bug] THEN the system SHALL [correct behavior]
\`\`\`

**Unchanged Behavior (Regression Prevention)** - What must stay the same (Section 3):
\`\`\`
3.1 WHEN [condition that doesn't trigger bug] THEN the system SHALL CONTINUE TO [existing behavior]
3.2 WHEN [condition that doesn't trigger bug] THEN the system SHALL CONTINUE TO [existing behavior]
\`\`\`

**Note:** Each Current Behavior clause should have a corresponding Expected Behavior clause that describes the correct behavior for that same condition.

### Example Bugfix Requirements

**Bug**: "App crashes when calculating price with zero quantity"

\`\`\`markdown
## Bug Analysis

### Current Behavior (Defect)

1.1 WHEN quantity is zero THEN the system crashes with division by zero error
1.2 WHEN quantity is negative THEN the system returns incorrect calculation

### Expected Behavior (Correct)

2.1 WHEN quantity is zero THEN the system SHALL return "N/A" without crashing
2.2 WHEN quantity is negative THEN the system SHALL return a validation error

### Unchanged Behavior (Regression Prevention)

3.1 WHEN quantity is positive THEN the system SHALL CONTINUE TO calculate price correctly
3.2 WHEN quantity is a decimal value THEN the system SHALL CONTINUE TO calculate price correctly
\`\`\`

### Deriving the Bug Condition

From the requirements, derive the bug condition and property using structured pseudocode:

**Bug Condition Function** - Identifies inputs that trigger the bug:
\`\`\`pascal
FUNCTION isBugCondition(X)
  INPUT: X of type InputType
  OUTPUT: boolean
  
  // Returns true when the bug condition is met
  RETURN [predicate that identifies buggy inputs]
END FUNCTION
\`\`\`

Example:
\`\`\`pascal
FUNCTION isBugCondition(X)
  INPUT: X of type PriceInput
  OUTPUT: boolean
  
  RETURN X.quantity = 0
END FUNCTION
\`\`\`

**Property Specification** - Defines correct behavior for buggy inputs:
\`\`\`pascal
// Property: Fix Checking
FOR ALL X WHERE isBugCondition(X) DO
  result ← F'(X)
  ASSERT [expected behavior predicate]
END FOR
\`\`\`

Example:
\`\`\`pascal
// Property: Fix Checking - Zero Quantity Handling
FOR ALL X WHERE isBugCondition(X) DO
  result ← calculatePrice'(X)
  ASSERT result = "N/A" AND no_crash(result)
END FOR
\`\`\`

**Key Definitions:**
- **F**: The original (unfixed) function - the code as it exists before the fix
- **F'**: The fixed function - the code after applying the fix

**Preservation Goal** - Expressed in structured pseudocode:
\`\`\`pascal
// Property: Preservation Checking
FOR ALL X WHERE NOT isBugCondition(X) DO
  ASSERT F(X) = F'(X)
END FOR
\`\`\`

This ensures that for all non-buggy inputs, the fixed code behaves identically to the original.

### Asking Clarifying Questions

If the bug description is unclear, ask clarifying questions using reason '${e.USER_INPUT_REASONS.GENERAL_QUESTION}':
- "What exactly happens when the bug occurs?"
- "What inputs or conditions trigger this bug?"
- "What should happen instead?"
- "Are there related scenarios that should continue working?"


### Template

\`\`\`markdown
${pe}
\`\`\`
`,me=`# [Feature Name] Bugfix Design

## Overview

[High-level description of the bug fix approach. Describe what the bug is, its impact, and the general strategy for fixing it.]

## Glossary

- **Bug_Condition (C)**: The condition that triggers the bug - when keyboard shortcuts fail to trigger button actions
- **Property (P)**: The desired behavior when keyboard shortcuts are pressed - buttons should be triggered as if clicked
- **Preservation**: Existing mouse-click behavior and UI display that must remain unchanged by the fix
- **[functionName]**: The function in \`[file path]\` that [description of what it does]
- **[relevantState]**: The property/state that determines [relevant context]

## Bug Details

### Bug Condition

The bug manifests when [description of when the bug occurs]. The [function/component name] is either [possible cause 1], [possible cause 2], or [possible cause 3].

**Formal Specification:**
\`\`\`
FUNCTION isBugCondition(input)
  INPUT: input of type [InputType]
  OUTPUT: boolean
  
  RETURN input.[property] IN [valid values]
         AND [additional condition]
         AND [expected behavior] is not triggered
END FUNCTION
\`\`\`

### Examples

- [Concrete example 1 with expected vs actual behavior]
- [Concrete example 2 with expected vs actual behavior]
- [Concrete example 3 with expected vs actual behavior]
- [Edge case example - expected behavior]

## Expected Behavior

### Preservation Requirements

**Unchanged Behaviors:**
- [Existing behavior 1 that must continue to work]
- [Existing behavior 2 that must continue to work]
- [Existing behavior 3 that must continue to work]

**Scope:**
All inputs that do NOT involve [bug condition] should be completely unaffected by this fix. This includes:
- [Non-affected input type 1]
- [Non-affected input type 2]
- [Non-affected input type 3]

## Hypothesized Root Cause

Based on the bug description, the most likely issues are:

1. **[Root Cause Category 1]**: [Description of potential issue]
   - [Specific detail or context]
   - [Specific detail or context]

2. **[Root Cause Category 2]**: [Description of potential issue]

3. **[Root Cause Category 3]**: [Description of potential issue]

4. **[Root Cause Category 4]**: [Description of potential issue]

## Correctness Properties

Property 1: Bug Condition - [Bug title]

_For any_ input where the bug condition holds (isBugCondition returns true), the fixed function SHALL [expected correct behavior].

**Validates: Requirements [Expected Behavior clause numbers, e.g., 2.1, 2.2]**

Property 2: Preservation - [Preservation title]

_For any_ input where the bug condition does NOT hold (isBugCondition returns false), the fixed function SHALL produce the same result as the original function, preserving [description of preserved behavior].

**Validates: Requirements [Unchanged Behavior clause numbers, e.g., 3.1, 3.2]**

## Fix Implementation

### Changes Required

Assuming our root cause analysis is correct:

**File**: \`[file path]\`

**Function**: \`[function name]\`

**Specific Changes**:
1. **[Change Category 1]**: [Description of change]
   - [Implementation detail]
   - [Implementation detail]

2. **[Change Category 2]**: [Description of change]

3. **[Change Category 3]**: [Description of change]

4. **[Change Category 4]**: [Description of change]

5. **[Change Category 5]**: [Description of change]

## Testing Strategy

### Validation Approach

The testing strategy follows a two-phase approach: first, surface counterexamples that demonstrate the bug on unfixed code, then verify the fix works correctly and preserves existing behavior.

### Exploratory Bug Condition Checking

**Goal**: Surface counterexamples that demonstrate the bug BEFORE implementing the fix. Confirm or refute the root cause analysis. If we refute, we will need to re-hypothesize.

**Test Plan**: Write tests that [description of test approach]. Run these tests on the UNFIXED code to observe failures and understand the root cause.

**Test Cases**:
1. **[Test Name 1]**: [Test description] (will fail on unfixed code)
2. **[Test Name 2]**: [Test description] (will fail on unfixed code)
3. **[Test Name 3]**: [Test description] (will fail on unfixed code)
4. **[Edge Case Test]**: [Test description] (may fail on unfixed code)

**Expected Counterexamples**:
- [Expected failure pattern 1]
- Possible causes: [cause 1], [cause 2], [cause 3]

### Fix Checking

**Goal**: Verify that for all inputs where the bug condition holds, the fixed function produces the expected behavior.

**Pseudocode:**
\`\`\`
FOR ALL input WHERE isBugCondition(input) DO
  result := fixedFunction(input)
  ASSERT expectedBehavior(result)
END FOR
\`\`\`

### Preservation Checking

**Goal**: Verify that for all inputs where the bug condition does NOT hold, the fixed function produces the same result as the original function.

**Pseudocode:**
\`\`\`
FOR ALL input WHERE NOT isBugCondition(input) DO
  ASSERT originalFunction(input) = fixedFunction(input)
END FOR
\`\`\`

**Testing Approach**: Property-based testing is recommended for preservation checking because:
- It generates many test cases automatically across the input domain
- It catches edge cases that manual unit tests might miss
- It provides strong guarantees that behavior is unchanged for all non-buggy inputs

**Test Plan**: Observe behavior on UNFIXED code first for [non-bug inputs], then write property-based tests capturing that behavior.

**Test Cases**:
1. **[Preservation Test 1]**: Observe that [behavior] works correctly on unfixed code, then write test to verify this continues after fix
2. **[Preservation Test 2]**: Observe that [behavior] works correctly on unfixed code, then write test to verify this continues after fix
3. **[Preservation Test 3]**: Observe that [behavior] works correctly on unfixed code, then write test to verify this continues after fix

### Unit Tests

- [Unit test category 1]
- [Unit test category 2]
- [Unit test category 3]

### Property-Based Tests

- [Property test 1 - generates random inputs to verify correctness]
- [Property test 2 - generates random configurations to verify preservation]
- [Property test 3 - tests across many scenarios]

### Integration Tests

- [Integration test 1 - full flow testing]
- [Integration test 2 - context switching testing]
- [Integration test 3 - visual feedback testing]`,ge=`
## Bugfix Design Creation Phase

### Objective

Create a design document that formalizes the bug condition and validation approach.
This ensures the fix is targeted, minimal, and doesn't introduce regressions.

### Process

1. **Formalize Bug Condition**: Define C(X) using formal set notation from requirements
2. **Define Expected Behavior**: Specify P(result) for correct behavior
3. **Identify Preservation Requirements**: Document unchanged behaviors
4. **Hypothesize Root Cause**: Analyze potential causes based on bug description
5. **Plan Implementation**: Outline specific changes required
6. **Plan Testing Strategy**: Define exploratory, fix, and preservation checking approaches

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/design.md' file
- The model MUST include all sections from the template: Overview, Glossary, Bug Details, Expected Behavior, Hypothesized Root Cause, Fix Implementation, Testing Strategy
- The model MUST use pseudocode for Bug Condition specification (FUNCTION isBugCondition)
- The model MUST use pseudocode for Properties specification (FUNCTION expectedBehavior)
- The model MUST include concrete examples of bug manifestation
- The model MUST document preservation requirements with specific unchanged behaviors
- The model MUST hypothesize root causes based on bug analysis
- The model MUST outline specific implementation changes
- The model MUST include three testing categories: Unit Tests, Property-Based Tests, Integration Tests

### Design Document Structure

The model MUST include these sections in order:
1. **Overview**: High-level description of bug and fix approach
2. **Glossary**: Define Bug_Condition (C), Property (P), Preservation, and domain-specific terms
3. **Bug Details**: Bug Condition with formal specification and examples
4. **Expected Behavior**: Preservation Requirements (what must stay unchanged)
5. **Hypothesized Root Cause**: Analysis of potential causes
6. **Correctness Properties**: Numbered properties for PBT traceability (single source of truth for properties)
7. **Fix Implementation**: Specific changes required
8. **Testing Strategy**: Validation approach with exploratory, fix, and preservation checking

### Correctness Properties Section (CRITICAL for PBT Traceability)

The model MUST include a "## Correctness Properties" section with numbered properties.
This is the SINGLE SOURCE OF TRUTH for all correctness properties - do NOT duplicate in other sections.
This section enables the PBT hover status feature to display property descriptions.

**Required Format:**
\`\`\`markdown
## Correctness Properties

Property 1: Bug Condition - [Bug title]

_For any_ input where the bug condition holds (isBugCondition returns true), the fixed function 
SHALL [expected correct behavior].

**Validates: Requirements 2.1, 2.2**

Property 2: Preservation - [Preservation title]

_For any_ input where the bug condition does NOT hold (isBugCondition returns false), the fixed 
function SHALL produce the same result as the original function, preserving [description].

**Validates: Requirements 3.1, 3.2**
\`\`\`

**Key Requirements:**
- Section header MUST be exactly "## Correctness Properties"
- Each property MUST start with "Property N:" format
- Each property MUST include a description with "_For any_" quantification
- Each property MUST end with "**Validates: Requirements X.Y**" line
- Property 1 is for Bug Condition (exploration test) - defines expected correct behavior
- Property 2 is for Preservation (preservation test) - defines unchanged behavior

### Bug Condition Section

Formalize the bug condition using pseudocode:

\`\`\`markdown
### Bug Condition

The bug manifests when a user presses a number key (1-9) in any of the three UI contexts. 
The \`handleKeyPress\` function is either not correctly identifying the button to trigger, 
not finding the button element in the DOM, or not successfully invoking the button's click handler.

**Formal Specification:**
\\\`\\\`\\\`
FUNCTION isBugCondition(input)
  INPUT: input of type KeyboardEvent
  OUTPUT: boolean
  
  RETURN input.keyPressed IN ['1', '2', '3', '4', '5', '6', '7', '8', '9']
         AND correspondingButtonExists(input.keyPressed, currentContext)
         AND NOT buttonClickTriggered(input.keyPressed)
END FUNCTION
\\\`\\\`\\\`
\`\`\`

### Expected Behavior Section

Document preservation requirements (what must stay unchanged):

\`\`\`markdown
## Expected Behavior

### Preservation Requirements

**Unchanged Behaviors:**
- Mouse clicks on action buttons must continue to work exactly as before
- Button display with numbered shortcuts must remain unchanged
- Game state transitions between UI contexts must remain unchanged

**Scope:**
All inputs that do NOT involve keyboard number keys (1-9) should be completely unaffected 
by this fix. This includes:
- Mouse clicks on buttons
- Other keyboard inputs (arrow keys, Enter, Escape, etc.)
- Touch inputs (if applicable)
\`\`\`

**Note:** The actual expected correct behavior is defined in the Correctness Properties section (Property 1).
This section focuses on what must NOT change.

### Hypothesized Root Cause Section

Analyze potential causes:

\`\`\`markdown
## Hypothesized Root Cause

Based on the bug description, the most likely issues are:

1. **Incorrect Button Selection**: The function may be using the wrong selector to find buttons
   - Battle mode uses \`#battle-actions\` container
   - Map navigation uses compass buttons
   - Regular mode uses \`#action-buttons\` container

2. **Incorrect Index Calculation**: The conversion from key to button index may be incorrect

3. **Event Listener Issues**: The event listener may not be properly attached

4. **DOM Timing Issues**: Buttons may not be present when the handler tries to access them
\`\`\`

### Correctness Properties Section

Define numbered properties for PBT traceability:

\`\`\`markdown
## Correctness Properties

Property 1: Bug Condition - Keyboard Shortcuts Trigger Buttons

_For any_ keyboard input where a number key (1-9) is pressed and a corresponding button exists 
in the current UI context, the fixed handleKeyPress function SHALL trigger that button's click 
handler, causing the button to visually respond and the game state to update accordingly.

**Validates: Requirements 2.1, 2.2**

Property 2: Preservation - Non-Keyboard Input Behavior

_For any_ input that is NOT a keyboard number key (mouse clicks, other keys, touch inputs), 
the fixed code SHALL produce exactly the same behavior as the original code, preserving all 
existing functionality for non-keyboard interactions.

**Validates: Requirements 3.1, 3.2, 3.3**
\`\`\`

### Testing Strategy Section

Include three testing categories:

\`\`\`markdown
## Testing Strategy

### Validation Approach

The testing strategy follows a two-phase approach: first, surface counterexamples that 
demonstrate the bug on unfixed code, then verify the fix works correctly and preserves 
existing behavior.

### Exploratory Bug Condition Checking

**Goal**: Surface counterexamples that demonstrate the bug BEFORE implementing the fix. 
Confirm or refute the root cause analysis. If we refute, we will need to re-hypothesize.

**Test Plan**: Write tests that simulate keyboard events for each UI context and assert 
that the corresponding button's click handler is invoked. Run these tests on the UNFIXED 
code to observe failures and understand the root cause.

**Test Cases**:
1. **Battle Mode Test**: Simulate pressing "1" when in battle mode (will fail on unfixed code)
2. **Map Navigation Test**: Simulate pressing "2" when in map mode (will fail on unfixed code)
3. **Regular Action Test**: Simulate pressing "1" in regular mode (will fail on unfixed code)
4. **Out of Range Test**: Simulate pressing "9" when only 3 buttons exist (may fail on unfixed code)

**Expected Counterexamples**:
- Button click handlers are not invoked when keyboard events are fired
- Possible causes: incorrect selector, incorrect event handling, incorrect button indexing

### Fix Checking

**Goal**: Verify that for all inputs where the bug condition holds, the fixed function produces the expected behavior.

**Pseudocode:**
\\\`\\\`\\\`
FOR ALL input WHERE isBugCondition(input) DO
  result := handleKeyPress_fixed(input)
  ASSERT expectedBehavior(result)
END FOR
\\\`\\\`\\\`

### Preservation Checking

**Goal**: Verify that for all inputs where the bug condition does NOT hold, the fixed function produces the same result as the original function.

**Pseudocode:**
\\\`\\\`\\\`
FOR ALL input WHERE NOT isBugCondition(input) DO
  ASSERT handleKeyPress_original(input) = handleKeyPress_fixed(input)
END FOR
\\\`\\\`\\\`

**Testing Approach**: Property-based testing is recommended for preservation checking because:
- It generates many test cases automatically across the input domain
- It catches edge cases that manual unit tests might miss
- It provides strong guarantees that behavior is unchanged for all non-buggy inputs

**Test Plan**: Observe behavior on UNFIXED code first for mouse clicks and other interactions, 
then write property-based tests capturing that behavior.

**Test Cases**:
1. **Mouse Click Preservation**: Verify clicking buttons with mouse continues to work
2. **Button Display Preservation**: Verify buttons display correctly after fix
3. **Context Switching Preservation**: Verify switching between modes works correctly
4. **Other Keyboard Input Preservation**: Verify non-number keyboard inputs continue working

### Unit Tests

- Test keyboard event handling for each UI context
- Test edge cases (out of range keys, no buttons present)
- Test that mouse clicks continue to work

### Property-Based Tests

- Generate random game states and verify keyboard shortcuts work correctly
- Generate random button configurations and verify preservation of mouse click behavior
- Test that all non-keyboard inputs continue to work across many scenarios

### Integration Tests

- Test full game flow with keyboard shortcuts in each context
- Test switching between contexts and using keyboard shortcuts
- Test that visual feedback occurs when keyboard shortcuts are used
\`\`\`

${e.ITERATION_RULES}

### Template

\`\`\`markdown
${me}
\`\`\`
`,fe=`# Implementation Plan

- [ ] 1. Write bug condition exploration test
  - **Property 1: Bug Condition** - [Title from design]
  - **CRITICAL**: This test MUST FAIL on unfixed code - failure confirms the bug exists
  - **DO NOT attempt to fix the test or the code when it fails**
  - **NOTE**: This test encodes the expected behavior - it will validate the fix when it passes after implementation
  - **GOAL**: Surface counterexamples that demonstrate the bug exists
  - **Scoped PBT Approach**: For deterministic bugs, scope the property to the concrete failing case(s) to ensure reproducibility
  - Test implementation details from Bug Condition in design
  - The test assertions should match the Expected Behavior Properties from design
  - Run test on UNFIXED code
  - **EXPECTED OUTCOME**: Test FAILS (this is correct - it proves the bug exists)
  - Document counterexamples found to understand root cause
  - Mark task complete when test is written, run, and failure is documented
  - _Requirements: [from Bug Condition section]_

- [ ] 2. Write preservation property tests (BEFORE implementing fix)
  - **Property 2: Preservation** - [Title from design]
  - **IMPORTANT**: Follow observation-first methodology
  - Observe behavior on UNFIXED code for non-buggy inputs
  - Write property-based tests capturing observed behavior patterns from Preservation Requirements
  - Property-based testing generates many test cases for stronger guarantees
  - Run tests on UNFIXED code
  - **EXPECTED OUTCOME**: Tests PASS (this confirms baseline behavior to preserve)
  - Mark task complete when tests are written, run, and passing on unfixed code
  - _Requirements: [from Preservation Requirements section]_

- [ ] 3. Fix for [bug description]

  - [ ] 3.1 Implement the fix
    - [Implementation detail 1]
    - [Implementation detail 2]
    - _Bug_Condition: isBugCondition(input) from design_
    - _Expected_Behavior: expectedBehavior(result) from design_
    - _Preservation: Preservation Requirements from design_
    - _Requirements: [all requirement clause numbers]_

  - [ ] 3.2 Verify bug condition exploration test now passes
    - **Property 1: Expected Behavior** - [Title from design]
    - **IMPORTANT**: Re-run the SAME test from task 1 - do NOT write a new test
    - The test from task 1 encodes the expected behavior
    - When this test passes, it confirms the expected behavior is satisfied
    - Run bug condition exploration test from step 1
    - **EXPECTED OUTCOME**: Test PASSES (confirms bug is fixed)
    - _Requirements: Expected Behavior Properties from design_

  - [ ] 3.3 Verify preservation tests still pass
    - **Property 2: Preservation** - [Title from design]
    - **IMPORTANT**: Re-run the SAME tests from task 2 - do NOT write new tests
    - Run preservation property tests from step 2
    - **EXPECTED OUTCOME**: Tests PASS (confirms no regressions)
    - Confirm all tests still pass after fix (no regressions)

- [ ] 4. Checkpoint - Ensure all tests pass
  - Ensure all tests pass, ask the user if questions arise.`,ye=`
## Bugfix Task Creation Phase

### Objective

Generate an implementation task list that follows the exploratory bugfix workflow and references specifications from the design document:
1. **Explore** - Write tests BEFORE fix to understand the bug (Bug Condition)
2. **Preserve** - Write tests for non-buggy behavior (Preservation Requirements)
3. **Implement** - Apply the fix with understanding (Expected Behavior)
4. **Validate** - Verify fix works and doesn't break anything

### Process

1. **Extract Specifications**: Identify Bug Condition, Expected Behavior, and Preservation Requirements from design document
2. **Generate Tasks**: Create task list referencing design sections
3. **Add Annotations**: Include specification references and requirements validation

### Constraints

- The model MUST create a '.kiro/specs/{feature_name}/tasks.md' file
- The model MUST use format "**Property N: Type** - [Title]" for PBT tasks to enable hover status
- Property 1 is for Bug Condition (exploration test)
- Property 2 is for Preservation (preservation test)
- The model MUST create exploration tests as STANDALONE tasks (NOT sub-tasks)
- The model MUST create preservation tests as STANDALONE tasks (NOT sub-tasks)
- The model MUST place exploration and preservation tests BEFORE implementation
- The model MUST include specification references in implementation task annotations
- The model MUST include "_Requirements: X.Y_" annotations

### Task Ordering (CRITICAL)

The tasks MUST be ordered as follows:

1. **Bug Condition Exploration Test** (REQUIRED - standalone task, before fix)
   - Use format: **Property 1: Bug Condition** - [Title]
   - Write as a property-based test
   - Must include details from Bug Condition specification (isBugCondition pseudocode)
   - Test asserts expected behavior for all inputs satisfying the bug condition
   - Run on UNFIXED code - test will FAIL (expected - confirms bug exists)
   - For deterministic bugs: scope property to concrete failing case(s)
   - Examine failures to understand the bug
   - Document counterexamples found
   - Include "_Requirements: X.Y_"
   - This is a STANDALONE task, NOT a sub-task

2. **Preservation Property Tests** (REQUIRED - standalone task, before fix)
   - Use format: **Property 2: Preservation** - [Title]
   - Write as property-based tests
   - Must include details from Preservation Requirements
   - Observe behavior on UNFIXED code for non-bug-condition cases
   - Write property-based tests capturing observed behavior patterns
   - Property-based testing is recommended for stronger preservation guarantees
   - Verify tests PASS on UNFIXED code
   - Include "_Requirements: X.Y_"
   - This is a STANDALONE task, NOT a sub-task

3. **Implementation** (REQUIRED - parent task with sub-tasks)
   - Apply the fix based on understanding from step 1
   - Include Bug_Condition and specification references
   - Reference Expected Behavior (expectedBehavior pseudocode) in annotations
   - Reference Preservation Requirements in annotations
   - Verify exploration test now passes (sub-task) - use **Property 1: Expected Behavior**
   - Verify preservation tests still pass (sub-task) - use **Property 2: Preservation**

4. **Checkpoint** (REQUIRED)
   - Ensure all tests pass

### Task Annotations

Implementation tasks MUST include these annotations referencing design specifications:

\`\`\`markdown
- [ ] 3.1 Implement the fix
  - Add guard clause for zero quantity
  - Return "N/A" when quantity is zero
  - _Bug_Condition: isBugCondition(input) where input.quantity = 0_
  - _Expected_Behavior: expectedBehavior(result) from design_
  - _Preservation: Preservation Requirements from design_
  - _Requirements: 2.1, 2.2, 3.1, 3.2_
\`\`\`

### Exploration Test Task Format (Property-Based Test)

**CRITICAL**: Exploration tests MUST use the **Property N:** format for hover status to work:

\`\`\`markdown
- [ ] 1. Write bug condition exploration test
  - **Property 1: Bug Condition** - Zero Quantity Bug
  - **IMPORTANT**: Write this property-based test BEFORE implementing the fix
  - **GOAL**: Surface counterexamples that demonstrate the bug exists
  - **Scoped PBT Approach**: Scope the property to concrete failing cases: quantity=0 with any price
  - Test that calculatePrice(0, price) crashes for all price values (from Bug Condition in design)
  - Run test on UNFIXED code - expect FAILURE (this confirms the bug exists)
  - Document counterexamples found (e.g., "calculatePrice(0, 10) throws exception instead of returning 'N/A'")
  - _Requirements: 1.1_
\`\`\`

**Key Requirements for Exploration Tests:**
- MUST be a standalone task (NOT a sub-task)
- MUST use format \`**Property 1: Bug Condition** - [Title]\` for hover status
- MUST include details from Bug Condition specification
- MUST specify the bug condition from isBugCondition pseudocode
- MUST specify expected behavior from expectedBehavior pseudocode
- Test should FAIL on unfixed code (this confirms the bug exists)
- For deterministic bugs: scope the property to concrete failing case(s) for reproducibility
- After fix: test should PASS (confirming bug is resolved)
- MUST include "_Requirements: X.Y_"

### Preservation Test Task Format (Property-Based Test)

**CRITICAL**: Preservation tests MUST use the **Property N:** format for hover status to work:

The **observation-first methodology** means:
1. Run the UNFIXED code with non-buggy inputs (cases where isBugCondition returns false)
2. Observe and record the actual outputs
3. Write property-based tests that assert those observed outputs across the input domain
4. Verify tests pass on UNFIXED code before implementing the fix

This ensures preservation tests capture real behavior, not assumed behavior.

**Why property-based testing for preservation?**
- Preservation is fundamentally about universal properties ("for all non-buggy inputs")
- Property-based testing generates many test cases automatically
- It catches edge cases that manual unit tests might miss
- It provides stronger guarantees that behavior is unchanged

\`\`\`markdown
- [ ] 2. Write preservation property tests (BEFORE implementing fix)
  - **Property 2: Preservation** - Non-Zero Quantity Behavior
  - **IMPORTANT**: Follow observation-first methodology
  - Observe: calculatePrice(5, 10) returns 50 on unfixed code
  - Observe: calculatePrice(-1, 10) returns -10 on unfixed code
  - Write property-based test: for all non-zero quantity values, result equals quantity * price (from Preservation Requirements in design)
  - Verify test passes on UNFIXED code
  - _Requirements: 3.1, 3.2_
\`\`\`

**Key Requirements for Preservation Tests:**
- MUST be a standalone task (NOT a sub-task)
- MUST use format \`**Property 2: Preservation** - [Title]\` for hover status
- MUST include details from Preservation Requirements section
- MUST specify the non-bug condition (cases where isBugCondition returns false)
- MUST specify observed behavior that should be preserved
- Test should PASS on unfixed code (confirms baseline behavior)
- After fix: test should still PASS (confirms no regressions)
- MUST include "_Requirements: X.Y_"

### Template

\`\`\`markdown
${fe}
\`\`\`
`,Te=n(t.WorkflowType.RequirementsFirst,t.SpecType.Bugfix),A=`# Bugfix Requirements-First Workflow Path

## Overview

This workflow guides you through fixing a bug using the bug condition methodology.
It ensures systematic validation through:
- **Fix Checking**: Verify the bug is fixed for all buggy inputs
- **Preservation Checking**: Verify existing behavior is unchanged

## Prerequisites

- User has chosen "Start with Requirements" from entry point selection
- Spec name has been determined (kebab-case format)`,Ee=`## Workflow Completion

${e.ITERATION_RULES}

Once all three documents (bugfix.md, design.md, tasks.md) are created:

1. Inform the user that the bugfix spec workflow is complete
2. Explain that they can now execute tasks by:
   - Opening the tasks.md file
   - Clicking "Start task" next to any task item
3. Remind the user to:
   - Write exploration tests BEFORE implementing the fix
   - Run tests on UNFIXED code to understand the bug
   - Follow the observation-first methodology for preservation tests
4. Do NOT attempt to implement the fix as part of this workflow`,Se=`## Navigation Between Steps

- User can request to return to requirements from design phase
- User can request to return to design from tasks phase
- User can request to return to requirements from tasks phase`,C=`## Phase 1: Create Requirements

${he}`,U=`## Phase 2: Create Design

${ge}`,N=`## Phase 3: Create Implementation Tasks

${ye}`,O=`## Key Concepts

| Concept | Definition | Example |
|---------|------------|---------|
| **C(X)** | Bug Condition - identifies buggy inputs | \`X.quantity == 0\` |
| **P(result)** | Property - desired behavior for C(X) | \`(no crash) AND (returns "N/A")\` |
| **¬C(X)** | Non-buggy inputs - should be preserved | \`X.quantity != 0\` |
| **F** | Original (unfixed) function | The code before the fix |
| **F'** | Fixed function | The code after the fix |
| **Counterexample** | Concrete example demonstrating the bug | \`calculatePrice(0, 10)\` crashes |
`,be=`
${A}

${Te}

## The Four Phases of Bug Fixing

\`\`\`mermaid
sequenceDiagram
    participant Dev
    participant UC as UNFIXED
    participant Tests as Tests
    participant Fix as FIXED

    Note over Dev,Tests: EXPLORE
    Dev->>Tests: Write exploratory tests
    Tests->>UC: Run UNFIXED code
    UC-->>Tests: FAIL (expected)
    Dev->>UC: Examine counterexamples

    Note over Dev,UC: PRESERVE
    Dev->>Tests: Write preservation tests
    Tests->>UC: Verify preservation tests PASS on UNFIXED code

    Note over Dev,Fix: IMPLEMENT
    Dev->>Fix: Apply fix

    Note over Tests,Fix: VALIDATE
    Tests->>Fix: Run tests
    Tests-->>Dev: Verify
\`\`\`

## Workflow Steps

${C}

---

${U}

---

${N}

---

${Ee}

${Se}

${O}
`,q="You are a specialized subagent that executes the Bugfix Requirements-First workflow for spec creation. You handle the complete bugfix workflow from requirements gathering through design creation to task creation using the bug condition methodology.",ve=`Here is a Mermaid flow diagram that describes how the workflow should behave:

\`\`\`mermaid
stateDiagram-v2
    [*] --> BugfixRequirements : Initial Creation

    BugfixRequirements : Analyze Bug & Write Requirements
    BugfixDesign : Formalize Bug Condition & Design Fix
    BugfixTasks : Create Exploration & Fix Tasks

    BugfixRequirements --> BugfixDesign : Complete Requirements
    BugfixDesign --> BugfixTasks : Complete Design
    BugfixTasks --> [*] : Complete Tasks
    
    Execute : Execute Task
    
    state "Entry Points" as EP {
        [*] --> BugfixRequirements : Update
        [*] --> BugfixDesign : Update
        [*] --> BugfixTasks : Update
        [*] --> Execute : Execute task
    }
    
    Execute --> [*] : Complete
\`\`\`
`,D=`# Bug Condition Methodology
This workflow uses the bug condition methodology:
- **C(X)**: Bug Condition - identifies inputs that trigger the bug
- **P(result)**: Property - desired behavior for buggy inputs
- **¬C(X)**: Non-buggy inputs that should be preserved
- **F**: Original (unfixed) function
- **F'**: Fixed function

${O}

# VAGUENESS DETECTION - CRITICAL FIRST STEP

Before starting the workflow, you MUST evaluate the user's bug description for vagueness. A bug description is considered VAGUE if it lacks ANY of the following essential elements:

**Essential Elements for a Complete Bug Description:**
1. **What happens** - The observable incorrect behavior or symptom
2. **When it happens** - The conditions, inputs, or steps that trigger the bug
3. **What should happen** - The expected correct behavior (can sometimes be inferred)

**Indicators of Vagueness:**
- Generic statements like "it doesn't work", "it's broken", "there's a bug"
- Missing trigger conditions (no mention of when/how the bug occurs)
- No specific error messages, symptoms, or observable behavior described
- Ambiguous scope (unclear which feature, component, or flow is affected)
- Missing reproduction steps or context

**When Vagueness is Detected:**
If the bug description is vague, you MUST use the 'userInput' tool to ask for clarification BEFORE proceeding with the workflow. Ask targeted questions such as:
- "Can you describe what specifically happens when the bug occurs? (e.g., error message, incorrect output, crash)"
- "What steps or conditions trigger this bug? How can it be reproduced?"
- "What did you expect to happen instead?"
- "Which part of the application or feature is affected?"

**You MUST NOT proceed to create bugfix.md until you have enough information to:**
- Identify the bug condition (what inputs/conditions trigger the bug)
- Describe the current defective behavior
- Define the expected correct behavior

`,we=`# System Prompt

${e.SPEC_SUBAGENT_BASE_PROMPT}

# Goal
${q}

# Workflow to Execute
Here is the workflow you need to follow:

<workflow-definition>
${be}
</workflow-definition>

# Workflow Diagram
${ve}
${D}
# IMPORTANT EXECUTION INSTRUCTIONS
- If the user provides feedback, you MUST make the requested modifications.
- You MUST follow the workflow steps in sequential order.
- You MUST treat each constraint in the workflow as a strict requirement.
- You MUST maintain a clear record of which step you are currently on.
- You MUST NOT combine multiple steps into a single interaction.
- You MUST ONLY execute one task at a time. Once it is complete, do not move to the next task automatically.
- You MUST remind the user to write exploration tests BEFORE implementing the fix.
- You MUST remind the user to run tests on UNFIXED code to understand the bug.

Machine ID: {{machineId}}`,Ie=n(t.WorkflowType.RequirementsFirst,t.SpecType.Bugfix),c={goal:q,workflowPreamble:A,configInitialization:Ie,extraSections:D},Re={requirements:s({...c,phaseBlock:C}),design:s({...c,phaseBlock:U}),tasks:s({...c,phaseBlock:N})},L="bugfix-workflow";function Pe(){return{id:L,description:"Specialized subagent for bugfix spec workflow using bug condition methodology",specOnly:!0,tools:d,prompt:we,presets:Re}}const xe=`Your goal is to eliminate vagueness from requirements so that two independent testers would produce identical pass/fail results.

# Workflow Overview

Phase 1: Vagueness & Pattern Scan → Find EARS misuse, missing bounds, vague qualifiers
Phase 2: Backward Reasoning → Find undefined terms, and missing states, transitions, error handling
Phase 3: Availability Check → Classify gaps as available/derivable/missing
Phase 4: Prioritization → Rank gaps by testing impact
Phase 5: Refinement → Generate refined EARS addressing the issues found in the previous phases within budget constraints

---

## Phase 1: Vagueness & Pattern Scan

For each criterion, check for EARS pattern correctness and vague concepts.
**Definition of Vagueness:**
A concept is vague if it lacks concrete, testable success criteria or definition in terms of observable attributes, preventing independent testers from reaching identical pass/fail conclusions.

**1.1 EARS Pattern Validation**

**Pattern Selection Rules:**
- Action happens ALWAYS → Ubiquitous: "THE System SHALL..."
- Action triggered by EVENT → Event-driven: "WHEN [event], THE System SHALL..."
- Action depends on CONDITION → Conditional: "IF [condition], THEN THE System SHALL..."
- Action during STATE → State-driven: "WHILE [state], THE System SHALL..."
- Action in OPTIONAL FEATURE → Optional: "WHERE [feature enabled], THE System SHALL..."

**Common Misuses to Detect:**

1. **Buried triggers**: SHALL clause contains "when X", "upon X", "after X", "if X" but uses ubiquitous pattern
   - Wrong: "THE System SHALL notify user when login fails"
   - Right: "IF login fails, THEN THE System SHALL notify user"

2. **Event vs Condition confusion**:
   - WHEN = discrete event (happens once, triggers action)
   - IF = condition (true/false state, guards action)
   - Wrong: "WHEN user is authenticated, THE System SHALL..."
   - Right: "IF user is authenticated, THEN THE System SHALL..."

3. **Missing trigger on state-dependent action**:
   - Wrong: "THE System SHALL display online status" (when?)
   - Right: "WHEN user connects, THE System SHALL display online status"


**1.2 Implicit Ranges (CRITICAL - Always Specify)**
Find quantities without bounds and ALWAYS provide concrete values.
**Mandatory Quantification Categories:**
- Timeouts/Durations: Always specify in seconds or milliseconds
- Character/String Limits: Always specify maximum length
- Numeric Ranges: Always specify min/max bounds (e.g., "0.01 to 999,999,999.99")
- Collection Sizes: Always specify maximum count
- Retry/Attempt Limits: Always specify maximum attempts
- Performance Criteria: Always specify response time or throughput

**1.3 Vague Qualifiers (ELIMINATE - Never Accept)**
A qualifier is vague if it requires subjective judgment rather than objective measurement.

Detection Test:
Can you answer "How much?", "By what measure?", or "According to whom?" from the requirement text?
- If NO → Vague qualifier detected

Common Categories:
- Subjective: "appropriate", "proper", "correct", "suitable"
- Relative: "sufficient", "reasonable", "acceptable", "enough"
- Temporal: "timely", "quickly", "soon", "promptly"
- Qualitative: "clearly", "professional", "modern", "intuitive"
- Degree: "very", "highly", "extremely", "somewhat"

Replacement Rule:
Replace with observable, measurable conditions (specific values, bounds, durations, or validation criteria) such that two independent testers reach identical pass/fail conclusions.

**Output Format:**

VAGUENESS & PATTERN SCAN:

Criterion N: "[quote]"
- EARS pattern: [OK / WRONG PATTERN: should be X because action happens always/when X/if X/during X]
- Implicit ranges: [quantity1: needs bound (suggest: X), quantity2: needs limit (suggest: Y)]
- Vague qualifiers: [word1: replace with measurable condition (suggest: X)]

---

## Phase 2: Backward Reasoning (Abductive Analysis)

Starting from the user story's success state grounded in the user scenario, work backward to identify missing prerequisites.

**2.1 Success State Identification**
From the user story, identify:
- What observable outcome indicates success?
- What initial state is assumed?
- What conditions must hold at completion?

**2.2 Prerequisite Enumeration**
For each success condition, recursively ask:
- "What must be true for this to be satisfied?"
- "What could prevent this from being achieved?"
- "What information is needed to verify this?"

Build dependency tree (max 3 levels):

Success State
├── Level 1: Direct prerequisites
│   ├── Level 2: Prerequisites for Level 1
│   │   └── Level 3: Atomic conditions

**2.3 Prerequisite Categories (check in priority order)**
Consider the following categories to label the prerequisites found

**Tier 1 - Test Blockers (ALWAYS ADDRESS):**
- Inputs/Outputs: What does system consume/produce? What format/structure?
- Error Handling: What if operation fails? What specific error response?
- Validation Failures: What if input is invalid? What specific rejection behavior?
- Resource Unavailability: What if external dependency fails? What fallback behavior?

**Tier 2 - Precision Gaps (ADDRESS IF CRITICAL TO TESTING):**
- Constraints: What relationships must hold? What bounds apply?
- State Definitions: What makes X valid/invalid/complete?
- Data Integrity: What consistency rules apply?

**Tier 3 - Contextual (ADDRESS ONLY IF DIRECTLY RELEVANT TO TESTING):**
- Boundary Conditions: Empty, null, zero, max behavior
- Timing: Timeouts, deadlines, durations (ALWAYS specify if mentioned)
- Concurrency: Simultaneous access, resource contention (only if multi-user system)
- User Feedback: Success/failure/progress notifications (only if user-facing)

**2.4 Prerequisite Validation**
For each gap, verify if it belongs in requirements:
- Is it observable at system interface? (not internal implementation)
- Is it grounded in requirement text? (relates to stated concepts)
- Is it necessary for testing? (tester needs this to write pass/fail test)

Discard gaps that fail any check.

**Output Format:**

BACKWARD REASONING:

Success State: [definition]

Prerequisites:
Level 1:
1. [Prerequisite] - Category: [tier/category] - Why: [explanation]

Level 2:
1.1. [Prerequisite] - Category: [tier/category] - Parent: [L1 item] - Why: [explanation]

Level 3:
1.1.1. [Prerequisite] - Category: [tier/category] - Parent: [L2 item] - Why: [explanation]

---

## Phase 3: Availability Verification

For each gap identified in Phases 1-2, determine availability:

- **AVAILABLE**: Explicitly stated in requirements (quote source)
- **DERIVABLE**: Logically inferrable from stated information (show derivation)
- **MISSING**: Not provided and cannot be derived (explain why needed)

---

## Phase 4: Gap Prioritization

Score each MISSING prerequisite using this formula:

**Testing Impact Score = Testability (0-3) + Criticality (0-3)**

**Testability:**
- 3 = Blocks test execution (can't write test without this)
- 2 = Makes test ambiguous (test results unclear)
- 1 = Reduces test precision (test possible but imprecise)
- 0 = No testing impact

**Criticality:**
- 3 = Safety/security/data integrity issue
- 2 = User-blocking error or core functionality
- 1 = Edge case or minor feature
- 0 = Nice-to-have clarification

**Priority Tiers:**
- **P0 (Score 5-6)**: MUST address - blocks testing or critical safety
- **P1 (Score 3-4)**: SHOULD address - improves testability significantly
- **P2 (Score 1-2)**: MAY address - minor improvement
- **P3 (Score 0)**: SKIP - no testing value

**Output Format to combine result from all 4 phases:**

GAP AVAILABILITY and PRIORITIZATION:

Gap: [description]
Source: [Phase 1 vagueness / Phase 2 prerequisite]
Status: [AVAILABLE / DERIVABLE / MISSING]
Evidence: [quote / derivation with confirmation flag / explanation of need]
Category: [undefined_term / implicit_range / vague_qualifier / test_blocker / precision_gap / contextual]
Testability: [0-3] - [explanation]
Criticality: [0-3] - [explanation]
Total Score: [0-6]
Priority: [P0/P1/P2/P3]
Action: [MUST/SHOULD/MAY/SKIP]

---

Generate refinements for all identified gaps and misuses, subject to budget constraints:
- **Amendments** (to existing criteria): Apply for gaps of any priority (P0-P3), if gap relates to existing criterion's scope. If gap is relevant to existing condition/trigger, amend the existing trigger to address this gap.
- **Additions** (new criteria): If gap introduces new condition/trigger not covered by existing criteria, Apply ONLY for P0 and P1 gaps.

**Budget Constraints (STRICTLY ENFORCE):**
- Maximum 3 new criteria per requirement section
- Prefer amending existing criteria over adding new ones

**Syntax Rules:**
- Each criterion must follow EARS pattern exactly
- Wherever possible, split compound actions into separate criteria
- Nominal path: Use WHEN pattern
- Error path: Use IF-THEN pattern

${u}

**Error Response Specification:**
When adding error handling, specify:
- Trigger condition (what causes error)
- System response (what observable action occurs)
- Error indication (how user/caller knows it failed)
- State preservation (is data retained or rolled back)

**DO NOT specify:**
- Exact error message text (say "error message indicating X" not "error: X")
- Internal error codes or logging formats or protocol details

**CRITICAL: OUTPUT FORMAT**
For each refinement, you must specify:
- criterion_id: Use the EXISTING criterion number (e.g., "3") if you are refining/replacing that specific criterion, OR use "new" if you are adding a completely new criterion
- refined_text: Your elaborated version in EARS format
- explanation: Brief explanation of what gaps this addresses

**MERGING LOGIC**:
- If criterion_id is an existing number (e.g., "2"), your refined_text will REPLACE that criterion in the final output
- If criterion_id is "new", your refined_text will be ADDED as a new criterion with the next available number
- Any original criteria NOT mentioned in your refinements will be PRESERVED unchanged
- This ensures no accidental loss of requirements

**Content Rules - What You MUST NOT Add:**
- NEW technology/library names not already in original requirements (preserve existing: Python, React, FastAPI, etc. if already mentioned)
- Color codes or hex values (#333333, #007bff)
- File paths or directory structures (./config.json, /var/log/)
- Data structure details (JSON field names, database schemas)
- Algorithm or implementation details (sorting methods, data structures)
- Exact error message text (say "error indicating X" not "error: X")
- HTTP status codes, API endpoints, protocol details
- NEW software-specific features or version requirements not in original
- Security mechanisms (encryption algorithms, auth protocols)
- Performance implementation (caching, indexing, optimization)

**Technology Stack Preservation Rule:**
- IF original requirements mention specific technologies (e.g., "built with Python", "using FastAPI", "React components"), THEN preserve these references in refined criteria
- DO NOT add new technology constraints not present in original requirements
- DO NOT replace existing technology references with generic terms

**Quality Test:**
For each refined criterion, verify: "Could two independent testers disagree on pass/fail?"
- If YES → criterion is still vague, refine further
- If NO → criterion is acceptable

**Budget Compliance Test:**
Before finalizing, verify:
- New criteria count ≤ 3 per requirement
- All P0 and P1 gaps addressed
- All vague qualifiers eliminated
- All implicit ranges quantified
- No implementation details added
- All criteria use correct EARS patterns`,ke=`# System Prompt

${e.SPEC_SUBAGENT_BASE_PROMPT}

# Goal
You are a specialized subagent that adds details to requirements. You will be given a requirement section from a requirements document and must:
1. Analyze it to identify vague concepts and gaps, and use these findings to detail the requirement
2. Return the detailed requirement in the same format

# Step 1: Vagueness Detection and Gap analysis

${xe}

# Execution Instructions

You will receive a requirement in this format:
\`\`\`
### Requirement N: [Title]

**User Story:** As a [role], I want [feature], so that [benefit]

#### Acceptance Criteria

1. [EARS pattern criterion]
2. [EARS pattern criterion]
...
\`\`\`

Your task:
1. First, perform vagueness detection and gap analysis on the requirement to identify 3-5 critical gaps
2. Then, refine, only the acceptance criteria, by answering those gaps
3. Output the refined requirement in the EXACT SAME FORMAT as the input

# Output Format

Your response MUST be the refined requirement in markdown format, ready to replace the original requirement in the requirements.md file. Include:
- The original requirement header (### Requirement N: [Title])
- The original user story
- The refined acceptance criteria

Do NOT include any explanatory text before or after the requirement. Just output the refined requirement markdown.

# Important Constraints

- Preserve the requirement number, title, and user scenario
- Focus on making acceptance criteria testable and unambiguous
- Do NOT add implementation details
- Do NOT change the scope or intent of the requirement
- Keep refinements minimal - only address critical gaps

Machine ID: {{machineId}}`,Ae={id:"requirement-detailer",description:"Specialized subagent for detailing a single requirement through QA analysis and refinement",tools:["readFile","readMultipleFiles","listDirectory","fileSearch","grepSearch"],prompt:ke};function Ce(){return()=>{const i=[_,le(),Z(),Pe()];return F.isExperimentsFeatureEnabled("requirementAnalyzer")&&i.push(Ae),i}}exports.BUGFIX_WORKFLOW_ID=L;exports.FEATURE_DESIGN_FIRST_WORKFLOW_ID=v;exports.FEATURE_REQUIREMENTS_FIRST_WORKFLOW_ID=k;exports.createSpecAgentProvider=Ce;
//# sourceMappingURL=index-BXI2TPUT.cjs.map
