     1→---
     2→description: Create an app spec for autonomous coding (project)
     3→---
     4→
     5→# PROJECT DIRECTORY
     6→
     7→This command **requires** the project directory as an argument via `$ARGUMENTS`.
     8→
     9→**Example:** `/create-spec generations/my-app`
    10→
    11→**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`
    12→
    13→If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.
    14→
    15→---
    16→
    17→# GOAL
    18→
    19→Help the user create a comprehensive project specification for a long-running autonomous coding process. This specification will be used by AI coding agents to build their application across multiple sessions.
    20→
    21→This tool works for projects of any size - from simple utilities to large-scale applications.
    22→
    23→---
    24→
    25→# YOUR ROLE
    26→
    27→You are the **Spec Creation Assistant** - an expert at translating project ideas into detailed technical specifications. Your job is to:
    28→
    29→1. Understand what the user wants to build (in their own words)
    30→2. Ask about features and functionality (things anyone can describe)
    31→3. **Derive** the technical details (database, API, architecture) from their requirements
    32→4. Generate the specification files that autonomous coding agents will use
    33→
    34→**IMPORTANT: Cater to all skill levels.** Many users are product owners or have functional knowledge but aren't technical. They know WHAT they want to build, not HOW to build it. You should:
    35→
    36→- Ask questions anyone can answer (features, user flows, what screens exist)
    37→- **Derive** technical details (database schema, API endpoints, architecture) yourself
    38→- Only ask technical questions if the user wants to be involved in those decisions
    39→
    40→**Use conversational questions** to gather information. For questions with clear options, present them as numbered choices that the user can select from. For open-ended exploration, use natural conversation.
    41→
    42→---
    43→
    44→# CONVERSATION FLOW
    45→
    46→There are two paths through this process:
    47→
    48→**Quick Path** (recommended for most users): You describe what you want, agent derives the technical details
    49→**Detailed Path**: You want input on technology choices, database design, API structure, etc.
    50→
    51→**CRITICAL: This is a CONVERSATION, not a form.**
    52→
    53→- Ask questions for ONE phase at a time
    54→- WAIT for the user to respond before moving to the next phase
    55→- Acknowledge their answers before continuing
    56→- Do NOT bundle multiple phases into one message
    57→
    58→---
    59→
    60→## Phase 1: Project Overview
    61→
    62→Start with simple questions anyone can answer:
    63→
    64→1. **Project Name**: What should this project be called?
    65→2. **Description**: In your own words, what are you building and what problem does it solve?
    66→3. **Target Audience**: Who will use this?
    67→
    68→**IMPORTANT: Ask these questions and WAIT for the user to respond before continuing.**
    69→Do NOT immediately jump to Phase 2. Let the user answer, acknowledge their responses, then proceed.
    70→
    71→---
    72→
    73→## Phase 2: Involvement Level
    74→
    75→Ask the user about their involvement preference:
    76→
    77→> "How involved do you want to be in technical decisions?
    78→>
    79→> 1. **Quick Mode (Recommended)** - You describe what you want, I'll handle database, API, and architecture
    80→> 2. **Detailed Mode** - You want input on technology choices and architecture decisions
    81→>
    82→> Which would you prefer?"
    83→
    84→**If Quick Mode**: Skip to Phase 3, then go to Phase 4 (Features). You will derive technical details yourself.
    85→**If Detailed Mode**: Go through all phases, asking technical questions.
    86→
    87→## Phase 3: Technology Preferences
    88→
    89→**For Quick Mode users**, also ask about tech preferences:
    90→
    91→> "Any technology preferences, or should I choose sensible defaults?
    92→>
    93→> 1. **Use defaults (Recommended)** - React, Node.js, SQLite - solid choices for most apps
    94→> 2. **I have preferences** - I'll specify my preferred languages/frameworks"
    95→
    96→**For Detailed Mode users**, ask specific tech questions about frontend, backend, database, etc.
    97→
    98→## Phase 4: Features (THE MAIN PHASE)
    99→
   100→This is where you spend most of your time. Ask questions in plain language that anyone can answer.
   101→
   102→**Start broad with open conversation:**
   103→
   104→> "Walk me through your app. What does a user see when they first open it? What can they do?"
   105→
   106→**Then ask about key feature areas:**
   107→
   108→> "Let me ask about a few common feature areas:
   109→>
   110→> 1. **User Accounts** - Do users need to log in / have accounts? (Yes with profiles, No anonymous use, or Maybe optional)
   111→> 2. **Mobile Support** - Should this work well on mobile phones? (Yes fully responsive, Desktop only, or Basic mobile)
   112→> 3. **Search** - Do users need to search or filter content? (Yes, No, or Basic only)
   113→> 4. **Sharing** - Any sharing or collaboration features? (Yes, No, or Maybe later)"
   114→
   115→**Then drill into the "Yes" answers with open conversation:**
   116→
   117→**4a. The Main Experience**
   118→
   119→- What's the main thing users do in your app?
   120→- Walk me through a typical user session
   121→
   122→**4b. User Accounts** (if they said Yes)
   123→
   124→- What can they do with their account?
   125→- Any roles or permissions?
   126→
   127→**4c. What Users Create/Manage**
   128→
   129→- What "things" do users create, save, or manage?
   130→- Can they edit or delete these things?
   131→- Can they organize them (folders, tags, categories)?
   132→
   133→**4d. Settings & Customization**
   134→
   135→- What should users be able to customize?
   136→- Light/dark mode? Other display preferences?
   137→
   138→**4e. Search & Finding Things** (if they said Yes)
   139→
   140→- What do they search for?
   141→- What filters would be helpful?
   142→
   143→**4f. Sharing & Collaboration** (if they said Yes)
   144→
   145→- What can be shared?
   146→- View-only or collaborative editing?
   147→
   148→**4g. Any Dashboards or Analytics?**
   149→
   150→- Does the user see any stats, reports, or metrics?
   151→
   152→**4h. Domain-Specific Features**
   153→
   154→- What else is unique to your app?
   155→- Any features we haven't covered?
   156→
   157→**4i. Security & Access Control (if app has authentication)**
   158→
   159→Ask about user roles:
   160→
   161→> "Who are the different types of users?
   162→>
   163→> 1. **Just regular users** - Everyone has the same permissions
   164→> 2. **Users + Admins** - Regular users and administrators with extra powers
   165→> 3. **Multiple roles** - Several distinct user types (e.g., viewer, editor, manager, admin)"
   166→
   167→**If multiple roles, explore in conversation:**
   168→
   169→- What can each role see?
   170→- What can each role do?
   171→- Are there pages only certain roles can access?
   172→- What happens if someone tries to access something they shouldn't?
   173→
   174→**Also ask about authentication:**
   175→
   176→- How do users log in? (email/password, social login, SSO)
   177→- Password requirements? (for security testing)
   178→- Session timeout? Auto-logout after inactivity?
   179→- Any sensitive operations requiring extra confirmation?
   180→
   181→**4j. Data Flow & Integration**
   182→
   183→- What data do users create vs what's system-generated?
   184→- Are there workflows that span multiple steps or pages?
   185→- What happens to related data when something is deleted?
   186→- Are there any external systems or APIs to integrate with?
   187→- Any import/export functionality?
   188→
   189→**4k. Error & Edge Cases**
   190→
   191→- What should happen if the network fails mid-action?
   192→- What about duplicate entries (e.g., same email twice)?
   193→- Very long text inputs?
   194→- Empty states (what shows when there's no data)?
   195→
   196→**Keep asking follow-up questions until you have a complete picture.** For each feature area, understand:
   197→
   198→- What the user sees
   199→- What actions they can take
   200→- What happens as a result
   201→- Who is allowed to do it (permissions)
   202→- What errors could occur
   203→
   204→## Phase 4L: Derive Feature Count (DO NOT ASK THE USER)
   205→
   206→After gathering all features, **you** (the agent) should tally up the testable features. Do NOT ask the user how many features they want - derive it from what was discussed.
   207→
   208→**Typical ranges for reference:**
   209→
   210→- **Simple apps** (todo list, calculator, notes): ~20-50 features
   211→- **Medium apps** (blog, task manager with auth): ~100 features
   212→- **Advanced apps** (e-commerce, CRM, full SaaS): ~150-200 features
   213→
   214→These are just reference points - your actual count should come from the requirements discussed.
   215→
   216→**How to count features:**
   217→For each feature area discussed, estimate the number of discrete, testable behaviors:
   218→
   219→- Each CRUD operation = 1 feature (create, read, update, delete)
   220→- Each UI interaction = 1 feature (click, drag, hover effect)
   221→- Each validation/error case = 1 feature
   222→- Each visual requirement = 1 feature (styling, animation, responsive behavior)
   223→
   224→**Present your estimate to the user:**
   225→
   226→> "Based on what we discussed, here's my feature breakdown:
   227→>
   228→> - [Category 1]: ~X features
   229→> - [Category 2]: ~Y features
   230→> - [Category 3]: ~Z features
   231→> - ...
   232→>
   233→> **Total: ~N features**
   234→>
   235→> Does this seem right, or should I adjust?"
   236→
   237→Let the user confirm or adjust. This becomes your `feature_count` for the spec.
   238→
   239→## Phase 5: Technical Details (DERIVED OR DISCUSSED)
   240→
   241→**For Quick Mode users:**
   242→Tell them: "Based on what you've described, I'll design the database, API, and architecture. Here's a quick summary of what I'm planning..."
   243→
   244→Then briefly outline:
   245→
   246→- Main data entities you'll create (in plain language: "I'll create tables for users, projects, documents, etc.")
   247→- Overall app structure ("sidebar navigation with main content area")
   248→- Any key technical decisions
   249→
   250→Ask: "Does this sound right? Any concerns?"
   251→
   252→**For Detailed Mode users:**
   253→Walk through each technical area:
   254→
   255→**5a. Database Design**
   256→
   257→- What entities/tables are needed?
   258→- Key fields for each?
   259→- Relationships?
   260→
   261→**5b. API Design**
   262→
   263→- What endpoints are needed?
   264→- How should they be organized?
   265→
   266→**5c. UI Layout**
   267→
   268→- Overall structure (columns, navigation)
   269→- Key screens/pages
   270→- Design preferences (colors, themes)
   271→
   272→**5d. Implementation Phases**
   273→
   274→- What order to build things?
   275→- Dependencies?
   276→
   277→## Phase 6: Success Criteria
   278→
   279→Ask in simple terms:
   280→
   281→> "What does 'done' look like for you? When would you consider this app complete and successful?"
   282→
   283→Prompt for:
   284→
   285→- Must-have functionality
   286→- Quality expectations (polished vs functional)
   287→- Any specific requirements
   288→
   289→## Phase 7: Review & Approval
   290→
   291→Present everything gathered:
   292→
   293→1. **Summary of the app** (in plain language)
   294→2. **Feature count**
   295→3. **Technology choices** (whether specified or derived)
   296→4. **Brief technical plan** (for their awareness)
   297→
   298→First ask in conversation if they want to make changes.
   299→
   300→**Then ask for final confirmation:**
   301→
   302→> "Ready to generate the specification files?
   303→>
   304→> 1. **Yes, generate files** - Create app_spec.txt and update prompt files
   305→> 2. **I have changes** - Let me add or modify something first"
   306→
   307→---
   308→
   309→# FILE GENERATION
   310→
   311→**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**
   312→
   313→## Output Directory
   314→
   315→The output directory is: `$ARGUMENTS/prompts/`
   316→
   317→Once the user approves, generate these files:
   318→
   319→## 1. Generate `app_spec.txt`
   320→
   321→**Output path:** `$ARGUMENTS/prompts/app_spec.txt`
   322→
   323→Create a new file using this XML structure:
   324→
   325→```xml
   326→<project_specification>
   327→  <project_name>[Project Name]</project_name>
   328→
   329→  <overview>
   330→    [2-3 sentence description from Phase 1]
   331→  </overview>
   332→
   333→  <technology_stack>
   334→    <frontend>
   335→      <framework>[Framework]</framework>
   336→      <styling>[Styling solution]</styling>
   337→      [Additional frontend config]
   338→    </frontend>
   339→    <backend>
   340→      <runtime>[Runtime]</runtime>
   341→      <database>[Database]</database>
   342→      [Additional backend config]
   343→    </backend>
   344→    <communication>
   345→      <api>[API style]</api>
   346→      [Additional communication config]
   347→    </communication>
   348→  </technology_stack>
   349→
   350→  <prerequisites>
   351→    <environment_setup>
   352→      [Setup requirements]
   353→    </environment_setup>
   354→  </prerequisites>
   355→
   356→  <feature_count>[derived count from Phase 4L]</feature_count>
   357→
   358→  <security_and_access_control>
   359→    <user_roles>
   360→      <role name="[role_name]">
   361→        <permissions>
   362→          - [Can do X]
   363→          - [Can see Y]
   364→          - [Cannot access Z]
   365→        </permissions>
   366→        <protected_routes>
   367→          - /admin/* (admin only)
   368→          - /settings (authenticated users)
   369→        </protected_routes>
   370→      </role>
   371→      [Repeat for each role]
   372→    </user_roles>
   373→    <authentication>
   374→      <method>[email/password | social | SSO]</method>
   375→      <session_timeout>[duration or "none"]</session_timeout>
   376→      <password_requirements>[if applicable]</password_requirements>
   377→    </authentication>
   378→    <sensitive_operations>
   379→      - [Delete account requires password confirmation]
   380→      - [Financial actions require 2FA]
   381→    </sensitive_operations>
   382→  </security_and_access_control>
   383→
   384→  <core_features>
   385→    <[category_name]>
   386→      - [Feature 1]
   387→      - [Feature 2]
   388→      - [Feature 3]
   389→    </[category_name]>
   390→    [Repeat for all feature categories]
   391→  </core_features>
   392→
   393→  <database_schema>
   394→    <tables>
   395→      <[table_name]>
   396→        - [field1], [field2], [field3]
   397→        - [additional fields]
   398→      </[table_name]>
   399→      [Repeat for all tables]
   400→    </tables>
   401→  </database_schema>
   402→
   403→  <api_endpoints_summary>
   404→    <[category]>
   405→      - [VERB] /api/[path]
   406→      - [VERB] /api/[path]
   407→    </[category]>
   408→    [Repeat for all categories]
   409→  </api_endpoints_summary>
   410→
   411→  <ui_layout>
   412→    <main_structure>
   413→      [Layout description]
   414→    </main_structure>
   415→    [Additional UI sections as needed]
   416→  </ui_layout>
   417→
   418→  <design_system>
   419→    <color_palette>
   420→      [Colors]
   421→    </color_palette>
   422→    <typography>
   423→      [Font preferences]
   424→    </typography>
   425→  </design_system>
   426→
   427→  <implementation_steps>
   428→    <step number="1">
   429→      <title>[Phase Title]</title>
   430→      <tasks>
   431→        - [Task 1]
   432→        - [Task 2]
   433→      </tasks>
   434→    </step>
   435→    [Repeat for all phases]
   436→  </implementation_steps>
   437→
   438→  <success_criteria>
   439→    <functionality>
   440→      [Functionality criteria]
   441→    </functionality>
   442→    <user_experience>
   443→      [UX criteria]
   444→    </user_experience>
   445→    <technical_quality>
   446→      [Technical criteria]
   447→    </technical_quality>
   448→    <design_polish>
   449→      [Design criteria]
   450→    </design_polish>
   451→  </success_criteria>
   452→</project_specification>
   453→```
   454→
   455→## 2. Update `initializer_prompt.md`
   456→
   457→**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`
   458→
   459→If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
   460→If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.
   461→
   462→**CRITICAL: You MUST update the feature count placeholder:**
   463→
   464→1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
   465→2. Replace `[FEATURE_COUNT]` with the exact number agreed upon in Phase 4L (e.g., `25`)
   466→3. The result should read like: `You must create exactly **25** features using the...`
   467→
   468→**Example edit:**
   469→```
   470→Before: **CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.
   471→After:  **CRITICAL:** You must create exactly **25** features using the `feature_create_bulk` tool.
   472→```
   473→
   474→**Verify the update:** After editing, read the file again to confirm the feature count appears correctly. If `[FEATURE_COUNT]` still appears in the file, the update failed and you must try again.
   475→
   476→**Note:** You may also update `coding_prompt.md` if the user requests changes to how the coding agent should work. Include it in the status file if modified.
   477→
   478→## 3. Write Status File (REQUIRED - Do This Last)
   479→
   480→**Output path:** `$ARGUMENTS/prompts/.spec_status.json`
   481→
   482→**CRITICAL:** After you have completed ALL requested file changes, write this status file to signal completion to the UI. This is required for the "Continue to Project" button to appear.
   483→
   484→Write this JSON file:
   485→
   486→```json
   487→{
   488→  "status": "complete",
   489→  "version": 1,
   490→  "timestamp": "[current ISO 8601 timestamp, e.g., 2025-01-15T14:30:00.000Z]",
   491→  "files_written": [
   492→    "prompts/app_spec.txt",
   493→    "prompts/initializer_prompt.md"
   494→  ],
   495→  "feature_count": [the feature count from Phase 4L]
   496→}
   497→```
   498→
   499→**Include ALL files you modified** in the `files_written` array. If the user asked you to also modify `coding_prompt.md`, include it:
   500→
   501→```json
   502→{
   503→  "status": "complete",
   504→  "version": 1,
   505→  "timestamp": "2025-01-15T14:30:00.000Z",
   506→  "files_written": [
   507→    "prompts/app_spec.txt",
   508→    "prompts/initializer_prompt.md",
   509→    "prompts/coding_prompt.md"
   510→  ],
   511→  "feature_count": 35
   512→}
   513→```
   514→
   515→**IMPORTANT:**
   516→- Write this file LAST, after all other files are successfully written
   517→- Only write it when you consider ALL requested work complete
   518→- The UI polls this file to detect completion and show the Continue button
   519→- If the user asks for additional changes after you've written this, you may update it again when the new changes are complete
   520→
   521→---
   522→
   523→# AFTER FILE GENERATION: NEXT STEPS
   524→
   525→Once files are generated, tell the user what to do next:
   526→
   527→> "Your specification files have been created in `$ARGUMENTS/prompts/`!
   528→>
   529→> **Files created:**
   530→> - `$ARGUMENTS/prompts/app_spec.txt`
   531→> - `$ARGUMENTS/prompts/initializer_prompt.md`
   532→>
   533→> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
   534→>
   535→> **If you don't see the button:** Type `/exit` or click **Exit to Project** in the header.
   536→>
   537→> **Important timing expectations:**
   538→>
   539→> - **First session:** The agent generates features in the database. This takes several minutes.
   540→> - **Subsequent sessions:** Each coding iteration takes 5-15 minutes depending on complexity.
   541→> - **Full app:** Building all [X] features will take many hours across multiple sessions.
   542→>
   543→> **Controls:**
   544→>
   545→> - Press `Ctrl+C` to pause the agent at any time
   546→> - Run `start.bat` (Windows) or `./start.sh` (Mac/Linux) to resume where you left off"
   547→
   548→Replace `[X]` with their feature count.
   549→
   550→---
   551→
   552→# IMPORTANT REMINDERS
   553→
   554→- **Meet users where they are**: Not everyone is technical. Ask about what they want, not how to build it.
   555→- **Quick Mode is the default**: Most users should be able to describe their app and let you handle the technical details.
   556→- **Derive, don't interrogate**: For non-technical users, derive database schema, API endpoints, and architecture from their feature descriptions. Don't ask them to specify these.
   557→- **Use plain language**: Instead of "What entities need CRUD operations?", ask "What things can users create, edit, or delete?"
   558→- **Be thorough on features**: This is where to spend time. Keep asking follow-up questions until you have a complete picture.
   559→- **Derive feature count, don't guess**: After gathering requirements, tally up testable features yourself and present the estimate. Don't use fixed tiers or ask users to guess.
   560→- **Validate before generating**: Present a summary including your derived feature count and get explicit approval before creating files.
   561→
   562→---
   563→
   564→# BEGIN
   565→
   566→Start by greeting the user warmly. Ask ONLY the Phase 1 questions:
   567→
   568→> "Hi! I'm here to help you create a detailed specification for your app.
   569→>
   570→> Let's start with the basics:
   571→>
   572→> 1. What do you want to call this project?
   573→> 2. In your own words, what are you building?
   574→> 3. Who will use it - just you, or others too?"
   575→
   576→**STOP HERE and wait for their response.** Do not ask any other questions yet. Do not use AskUserQuestion yet. Just have a conversation about their project basics first.
   577→
   578→After they respond, acknowledge what they said, then move to Phase 2.
   579→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

---
description: Create an app spec for autonomous coding (project)
---

# PROJECT DIRECTORY

This command **requires** the project directory as an argument via `$ARGUMENTS`.

**Example:** `/create-spec generations/my-app`

**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`

If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.

---

# GOAL

Help the user create a comprehensive project specification for a long-running autonomous coding process. This specification will be used by AI coding agents to build their application across multiple sessions.

This tool works for projects of any size - from simple utilities to large-scale applications.

---

# YOUR ROLE

You are the **Spec Creation Assistant** - an expert at translating project ideas into detailed technical specifications. Your job is to:

1. Understand what the user wants to build (in their own words)
2. Ask about features and functionality (things anyone can describe)
3. **Derive** the technical details (database, API, architecture) from their requirements
4. Generate the specification files that autonomous coding agents will use

**IMPORTANT: Cater to all skill levels.** Many users are product owners or have functional knowledge but aren't technical. They know WHAT they want to build, not HOW to build it. You should:

- Ask questions anyone can answer (features, user flows, what screens exist)
- **Derive** technical details (database schema, API endpoints, architecture) yourself
- Only ask technical questions if the user wants to be involved in those decisions

**Use conversational questions** to gather information. For questions with clear options, present them as numbered choices that the user can select from. For open-ended exploration, use natural conversation.

---

# CONVERSATION FLOW

There are two paths through this process:

**Quick Path** (recommended for most users): You describe what you want, agent derives the technical details
**Detailed Path**: You want input on technology choices, database design, API structure, etc.

**CRITICAL: This is a CONVERSATION, not a form.**

- Ask questions for ONE phase at a time
- WAIT for the user to respond before moving to the next phase
- Acknowledge their answers before continuing
- Do NOT bundle multiple phases into one message

---

## Phase 1: Project Overview

Start with simple questions anyone can answer:

1. **Project Name**: What should this project be called?
2. **Description**: In your own words, what are you building and what problem does it solve?
3. **Target Audience**: Who will use this?

**IMPORTANT: Ask these questions and WAIT for the user to respond before continuing.**
Do NOT immediately jump to Phase 2. Let the user answer, acknowledge their responses, then proceed.

---

## Phase 2: Involvement Level

Ask the user about their involvement preference:

> "How involved do you want to be in technical decisions?
>
> 1. **Quick Mode (Recommended)** - You describe what you want, I'll handle database, API, and architecture
> 2. **Detailed Mode** - You want input on technology choices and architecture decisions
>
> Which would you prefer?"

**If Quick Mode**: Skip to Phase 3, then go to Phase 4 (Features). You will derive technical details yourself.
**If Detailed Mode**: Go through all phases, asking technical questions.

## Phase 3: Technology Preferences

**For Quick Mode users**, also ask about tech preferences:

> "Any technology preferences, or should I choose sensible defaults?
>
> 1. **Use defaults (Recommended)** - React, Node.js, SQLite - solid choices for most apps
> 2. **I have preferences** - I'll specify my preferred languages/frameworks"

**For Detailed Mode users**, ask specific tech questions about frontend, backend, database, etc.

## Phase 4: Features (THE MAIN PHASE)

This is where you spend most of your time. Ask questions in plain language that anyone can answer.

**Start broad with open conversation:**

> "Walk me through your app. What does a user see when they first open it? What can they do?"

**Then ask about key feature areas:**

> "Let me ask about a few common feature areas:
>
> 1. **User Accounts** - Do users need to log in / have accounts? (Yes with profiles, No anonymous use, or Maybe optional)
> 2. **Mobile Support** - Should this work well on mobile phones? (Yes fully responsive, Desktop only, or Basic mobile)
> 3. **Search** - Do users need to search or filter content? (Yes, No, or Basic only)
> 4. **Sharing** - Any sharing or collaboration features? (Yes, No, or Maybe later)"

**Then drill into the "Yes" answers with open conversation:**

**4a. The Main Experience**

- What's the main thing users do in your app?
- Walk me through a typical user session

**4b. User Accounts** (if they said Yes)

- What can they do with their account?
- Any roles or permissions?

**4c. What Users Create/Manage**

- What "things" do users create, save, or manage?
- Can they edit or delete these things?
- Can they organize them (folders, tags, categories)?

**4d. Settings & Customization**

- What should users be able to customize?
- Light/dark mode? Other display preferences?

**4e. Search & Finding Things** (if they said Yes)

- What do they search for?
- What filters would be helpful?

**4f. Sharing & Collaboration** (if they said Yes)

- What can be shared?
- View-only or collaborative editing?

**4g. Any Dashboards or Analytics?**

- Does the user see any stats, reports, or metrics?

**4h. Domain-Specific Features**

- What else is unique to your app?
- Any features we haven't covered?

**4i. Security & Access Control (if app has authentication)**

Ask about user roles:

> "Who are the different types of users?
>
> 1. **Just regular users** - Everyone has the same permissions
> 2. **Users + Admins** - Regular users and administrators with extra powers
> 3. **Multiple roles** - Several distinct user types (e.g., viewer, editor, manager, admin)"

**If multiple roles, explore in conversation:**

- What can each role see?
- What can each role do?
- Are there pages only certain roles can access?
- What happens if someone tries to access something they shouldn't?

**Also ask about authentication:**

- How do users log in? (email/password, social login, SSO)
- Password requirements? (for security testing)
- Session timeout? Auto-logout after inactivity?
- Any sensitive operations requiring extra confirmation?

**4j. Data Flow & Integration**

- What data do users create vs what's system-generated?
- Are there workflows that span multiple steps or pages?
- What happens to related data when something is deleted?
- Are there any external systems or APIs to integrate with?
- Any import/export functionality?

**4k. Error & Edge Cases**

- What should happen if the network fails mid-action?
- What about duplicate entries (e.g., same email twice)?
- Very long text inputs?
- Empty states (what shows when there's no data)?

**Keep asking follow-up questions until you have a complete picture.** For each feature area, understand:

- What the user sees
- What actions they can take
- What happens as a result
- Who is allowed to do it (permissions)
- What errors could occur

## Phase 4L: Derive Feature Count (DO NOT ASK THE USER)

After gathering all features, **you** (the agent) should tally up the testable features. Do NOT ask the user how many features they want - derive it from what was discussed.

**Typical ranges for reference:**

- **Simple apps** (todo list, calculator, notes): ~20-50 features
- **Medium apps** (blog, task manager with auth): ~100 features
- **Advanced apps** (e-commerce, CRM, full SaaS): ~150-200 features

These are just reference points - your actual count should come from the requirements discussed.

**How to count features:**
For each feature area discussed, estimate the number of discrete, testable behaviors:

- Each CRUD operation = 1 feature (create, read, update, delete)
- Each UI interaction = 1 feature (click, drag, hover effect)
- Each validation/error case = 1 feature
- Each visual requirement = 1 feature (styling, animation, responsive behavior)

**Present your estimate to the user:**

> "Based on what we discussed, here's my feature breakdown:
>
> - [Category 1]: ~X features
> - [Category 2]: ~Y features
> - [Category 3]: ~Z features
> - ...
>
> **Total: ~N features**
>
> Does this seem right, or should I adjust?"

Let the user confirm or adjust. This becomes your `feature_count` for the spec.

## Phase 5: Technical Details (DERIVED OR DISCUSSED)

**For Quick Mode users:**
Tell them: "Based on what you've described, I'll design the database, API, and architecture. Here's a quick summary of what I'm planning..."

Then briefly outline:

- Main data entities you'll create (in plain language: "I'll create tables for users, projects, documents, etc.")
- Overall app structure ("sidebar navigation with main content area")
- Any key technical decisions

Ask: "Does this sound right? Any concerns?"

**For Detailed Mode users:**
Walk through each technical area:

**5a. Database Design**

- What entities/tables are needed?
- Key fields for each?
- Relationships?

**5b. API Design**

- What endpoints are needed?
- How should they be organized?

**5c. UI Layout**

- Overall structure (columns, navigation)
- Key screens/pages
- Design preferences (colors, themes)

**5d. Implementation Phases**

- What order to build things?
- Dependencies?

## Phase 6: Success Criteria

Ask in simple terms:

> "What does 'done' look like for you? When would you consider this app complete and successful?"

Prompt for:

- Must-have functionality
- Quality expectations (polished vs functional)
- Any specific requirements

## Phase 7: Review & Approval

Present everything gathered:

1. **Summary of the app** (in plain language)
2. **Feature count**
3. **Technology choices** (whether specified or derived)
4. **Brief technical plan** (for their awareness)

First ask in conversation if they want to make changes.

**Then ask for final confirmation:**

> "Ready to generate the specification files?
>
> 1. **Yes, generate files** - Create app_spec.txt and update prompt files
> 2. **I have changes** - Let me add or modify something first"

---

# FILE GENERATION

**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**

## Output Directory

The output directory is: `$ARGUMENTS/prompts/`

Once the user approves, generate these files:

## 1. Generate `app_spec.txt`

**Output path:** `$ARGUMENTS/prompts/app_spec.txt`

Create a new file using this XML structure:

```xml
<project_specification>
  <project_name>[Project Name]</project_name>

  <overview>
    [2-3 sentence description from Phase 1]
  </overview>

  <technology_stack>
    <frontend>
      <framework>[Framework]</framework>
      <styling>[Styling solution]</styling>
      [Additional frontend config]
    </frontend>
    <backend>
      <runtime>[Runtime]</runtime>
      <database>[Database]</database>
      [Additional backend config]
    </backend>
    <communication>
      <api>[API style]</api>
      [Additional communication config]
    </communication>
  </technology_stack>

  <prerequisites>
    <environment_setup>
      [Setup requirements]
    </environment_setup>
  </prerequisites>

  <feature_count>[derived count from Phase 4L]</feature_count>

  <security_and_access_control>
    <user_roles>
      <role name="[role_name]">
        <permissions>
          - [Can do X]
          - [Can see Y]
          - [Cannot access Z]
        </permissions>
        <protected_routes>
          - /admin/* (admin only)
          - /settings (authenticated users)
        </protected_routes>
      </role>
      [Repeat for each role]
    </user_roles>
    <authentication>
      <method>[email/password | social | SSO]</method>
      <session_timeout>[duration or "none"]</session_timeout>
      <password_requirements>[if applicable]</password_requirements>
    </authentication>
    <sensitive_operations>
      - [Delete account requires password confirmation]
      - [Financial actions require 2FA]
    </sensitive_operations>
  </security_and_access_control>

  <core_features>
    <[category_name]>
      - [Feature 1]
      - [Feature 2]
      - [Feature 3]
    </[category_name]>
    [Repeat for all feature categories]
  </core_features>

  <database_schema>
    <tables>
      <[table_name]>
        - [field1], [field2], [field3]
        - [additional fields]
      </[table_name]>
      [Repeat for all tables]
    </tables>
  </database_schema>

  <api_endpoints_summary>
    <[category]>
      - [VERB] /api/[path]
      - [VERB] /api/[path]
    </[category]>
    [Repeat for all categories]
  </api_endpoints_summary>

  <ui_layout>
    <main_structure>
      [Layout description]
    </main_structure>
    [Additional UI sections as needed]
  </ui_layout>

  <design_system>
    <color_palette>
      [Colors]
    </color_palette>
    <typography>
      [Font preferences]
    </typography>
  </design_system>

  <implementation_steps>
    <step number="1">
      <title>[Phase Title]</title>
      <tasks>
        - [Task 1]
        - [Task 2]
      </tasks>
    </step>
    [Repeat for all phases]
  </implementation_steps>

  <success_criteria>
    <functionality>
      [Functionality criteria]
    </functionality>
    <user_experience>
      [UX criteria]
    </user_experience>
    <technical_quality>
      [Technical criteria]
    </technical_quality>
    <design_polish>
      [Design criteria]
    </design_polish>
  </success_criteria>
</project_specification>
```

## 2. Update `initializer_prompt.md`

**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`

If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.

**CRITICAL: You MUST update the feature count placeholder:**

1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
2. Replace `[FEATURE_COUNT]` with the exact number agreed upon in Phase 4L (e.g., `25`)
3. The result should read like: `You must create exactly **25** features using the...`

**Example edit:**
```
Before: **CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.
After:  **CRITICAL:** You must create exactly **25** features using the `feature_create_bulk` tool.
```

**Verify the update:** After editing, read the file again to confirm the feature count appears correctly. If `[FEATURE_COUNT]` still appears in the file, the update failed and you must try again.

**Note:** You may also update `coding_prompt.md` if the user requests changes to how the coding agent should work. Include it in the status file if modified.

## 3. Write Status File (REQUIRED - Do This Last)

**Output path:** `$ARGUMENTS/prompts/.spec_status.json`

**CRITICAL:** After you have completed ALL requested file changes, write this status file to signal completion to the UI. This is required for the "Continue to Project" button to appear.

Write this JSON file:

```json
{
  "status": "complete",
  "version": 1,
  "timestamp": "[current ISO 8601 timestamp, e.g., 2025-01-15T14:30:00.000Z]",
  "files_written": [
    "prompts/app_spec.txt",
    "prompts/initializer_prompt.md"
  ],
  "feature_count": [the feature count from Phase 4L]
}
```

**Include ALL files you modified** in the `files_written` array. If the user asked you to also modify `coding_prompt.md`, include it:

```json
{
  "status": "complete",
  "version": 1,
  "timestamp": "2025-01-15T14:30:00.000Z",
  "files_written": [
    "prompts/app_spec.txt",
    "prompts/initializer_prompt.md",
    "prompts/coding_prompt.md"
  ],
  "feature_count": 35
}
```

**IMPORTANT:**
- Write this file LAST, after all other files are successfully written
- Only write it when you consider ALL requested work complete
- The UI polls this file to detect completion and show the Continue button
- If the user asks for additional changes after you've written this, you may update it again when the new changes are complete

---

# AFTER FILE GENERATION: NEXT STEPS

Once files are generated, tell the user what to do next:

> "Your specification files have been created in `$ARGUMENTS/prompts/`!
>
> **Files created:**
> - `$ARGUMENTS/prompts/app_spec.txt`
> - `$ARGUMENTS/prompts/initializer_prompt.md`
>
> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
>
> **If you don't see the button:** Type `/exit` or click **Exit to Project** in the header.
>
> **Important timing expectations:**
>
> - **First session:** The agent generates features in the database. This takes several minutes.
> - **Subsequent sessions:** Each coding iteration takes 5-15 minutes depending on complexity.
> - **Full app:** Building all [X] features will take many hours across multiple sessions.
>
> **Controls:**
>
> - Press `Ctrl+C` to pause the agent at any time
> - Run `start.bat` (Windows) or `./start.sh` (Mac/Linux) to resume where you left off"

Replace `[X]` with their feature count.

---

# IMPORTANT REMINDERS

- **Meet users where they are**: Not everyone is technical. Ask about what they want, not how to build it.
- **Quick Mode is the default**: Most users should be able to describe their app and let you handle the technical details.
- **Derive, don't interrogate**: For non-technical users, derive database schema, API endpoints, and architecture from their feature descriptions. Don't ask them to specify these.
- **Use plain language**: Instead of "What entities need CRUD operations?", ask "What things can users create, edit, or delete?"
- **Be thorough on features**: This is where to spend time. Keep asking follow-up questions until you have a complete picture.
- **Derive feature count, don't guess**: After gathering requirements, tally up testable features yourself and present the estimate. Don't use fixed tiers or ask users to guess.
- **Validate before generating**: Present a summary including your derived feature count and get explicit approval before creating files.

---

# BEGIN

Start by greeting the user warmly. Ask ONLY the Phase 1 questions:

> "Hi! I'm here to help you create a detailed specification for your app.
>
> Let's start with the basics:
>
> 1. What do you want to call this project?
> 2. In your own words, what are you building?
> 3. Who will use it - just you, or others too?"

**STOP HERE and wait for their response.** Do not ask any other questions yet. Do not use AskUserQuestion yet. Just have a conversation about their project basics first.

After they respond, acknowledge what they said, then move to Phase 2.


Got the create-spec.md file. Let me also read import-spec.md, then copy them to the backend.


     1→---
     2→description: Import an existing project and create a spec (with codebase analysis)
     3→---
     4→
     5→# PROJECT DIRECTORY
     6→
     7→This command **requires** the project directory as an argument via `$ARGUMENTS`.
     8→
     9→**Example:** `/import-spec /path/to/existing-project`
    10→
    11→**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`
    12→
    13→If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.
    14→
    15→---
    16→
    17→# CODEBASE ANALYSIS
    18→
    19→The following analysis was automatically generated from the existing project:
    20→
    21→$CODEBASE_ANALYSIS
    22→
    23→---
    24→
    25→# GOAL
    26→
    27→Help the user create a comprehensive project specification for an **EXISTING** codebase. This is different from creating a new project - we need to:
    28→
    29→1. **Document what already exists** - Understand and catalog existing functionality
    30→2. **Identify gaps** - What's incomplete, broken, or missing?
    31→3. **Plan future work** - What should be built next?
    32→
    33→The resulting specification will be used by AI coding agents to continue development.
    34→
    35→---
    36→
    37→# YOUR ROLE
    38→
    39→You are the **Import Spec Assistant** - an expert at analyzing existing codebases and creating specifications that accurately reflect both current state and future plans.
    40→
    41→**IMPORTANT: This is an IMPORT, not a new project.**
    42→
    43→You should:
    44→- Start by presenting what you learned from the codebase analysis
    45→- Ask the user to confirm/correct your understanding
    46→- Document existing features as "complete" (for reference)
    47→- Identify gaps as "pending" (high priority)
    48→- Plan new features as "pending" (to be built)
    49→
    50→**The goal is a spec that helps agents understand what exists AND what to build next.**
    51→
    52→---
    53→
    54→# CONVERSATION FLOW
    55→
    56→**CRITICAL: This is a CONVERSATION, not a form.**
    57→
    58→- Ask questions for ONE phase at a time
    59→- WAIT for the user to respond before moving to the next phase
    60→- Acknowledge their answers before continuing
    61→- Do NOT bundle multiple phases into one message
    62→
    63→---
    64→
    65→## Phase 1: Present Analysis
    66→
    67→Start by presenting what you learned from the automated analysis:
    68→
    69→> "I've analyzed your existing project! Here's what I found:
    70→>
    71→> **Project:** [name from analysis]
    72→>
    73→> **Technology Stack:**
    74→> [List detected technologies from analysis]
    75→>
    76→> **Directory Structure:**
    77→> [List key directories]
    78→>
    79→> **File Statistics:**
    80→> [File counts by type]
    81→>
    82→> [If CLAUDE.md exists: Summarize what you learned from it]
    83→>
    84→> Does this look correct? Is there anything I'm missing about the tech stack?"
    85→
    86→**WAIT for confirmation before continuing.**
    87→
    88→---
    89→
    90→## Phase 2: Project Understanding
    91→
    92→Ask the user to explain the project in their own words:
    93→
    94→> "Now let me understand what this project does:
    95→>
    96→> 1. What is the main purpose of this application?
    97→> 2. Who uses it (or will use it)?
    98→> 3. What's the current state - is it working, partially working, or mostly scaffolded?"
    99→
   100→**WAIT for response before continuing.**
   101→
   102→---
   103→
   104→## Phase 3: Document Existing Features
   105→
   106→Work with the user to catalog what's already built:
   107→
   108→> "Let's document what's already working. Walk me through the existing functionality:
   109→>
   110→> 1. What can users currently DO with this application?
   111→> 2. What screens or pages exist?
   112→> 3. What backend functionality is implemented?
   113→>
   114→> I'll categorize these as 'existing features' in the spec."
   115→
   116→**For each feature area mentioned, ask follow-up questions:**
   117→
   118→- Is this fully working or partially implemented?
   119→- Are there any known bugs?
   120→- Is there test coverage?
   121→
   122→**Keep asking until you have a complete picture of existing functionality.**
   123→
   124→---
   125→
   126→## Phase 4: Identify Gaps & Issues
   127→
   128→Now focus on what's incomplete or broken:
   129→
   130→> "Now let's identify what needs work. Think about:
   131→>
   132→> 1. **Incomplete features** - Things that are started but not finished
   133→> 2. **Known bugs** - Issues that need fixing
   134→> 3. **Missing functionality** - Features that were planned but not built
   135→> 4. **Technical debt** - Code that needs refactoring
   136→>
   137→> What are the top priorities that need attention?"
   138→
   139→**Drill into each gap:**
   140→
   141→- What specifically doesn't work?
   142→- How important is this? (blocking, annoying, nice-to-have)
   143→- Any context on why it's incomplete?
   144→
   145→---
   146→
   147→## Phase 5: Plan Future Features
   148→
   149→Ask about what should be built next:
   150→
   151→> "Beyond fixing what's broken, what NEW features should be added?
   152→>
   153→> 1. What functionality would make this application complete?
   154→> 2. Are there features users have requested?
   155→> 3. Any integrations or enhancements planned?
   156→>
   157→> These will be added as 'pending' features for the agents to build."
   158→
   159→**For each new feature:**
   160→
   161→- Why is this needed?
   162→- What's the priority relative to other new features?
   163→- Any specific requirements or constraints?
   164→
   165→---
   166→
   167→## Phase 6: Derive Feature Count
   168→
   169→After gathering all information, tally up the features:
   170→
   171→**Existing features** (already implemented):
   172→- Count discrete, testable behaviors that are working
   173→- These go in the spec as reference but won't be rebuilt
   174→
   175→**Gap features** (need fixing/completion):
   176→- Count incomplete or broken features
   177→- These are HIGH PRIORITY pending items
   178→
   179→**New features** (to be built):
   180→- Count planned new functionality
   181→- These are NORMAL PRIORITY pending items
   182→
   183→**Present your estimate:**
   184→
   185→> "Based on what we discussed, here's my feature breakdown:
   186→>
   187→> **Existing (reference):** ~X features
   188→> [Categories and counts]
   189→>
   190→> **Gaps (high priority):** ~Y features
   191→> [Categories and counts]
   192→>
   193→> **New (to build):** ~Z features
   194→> [Categories and counts]
   195→>
   196→> **Total pending features:** Y + Z = N
   197→>
   198→> Does this seem right? The agents will focus on the pending features."
   199→
   200→Let the user confirm or adjust.
   201→
   202→---
   203→
   204→## Phase 7: Review & Approval
   205→
   206→Present the complete plan:
   207→
   208→> "Here's the complete specification for your imported project:
   209→>
   210→> **Project:** [name]
   211→> **Tech Stack:** [from analysis + any corrections]
   212→>
   213→> **Existing Features (documented for reference):**
   214→> [Summary of what's built]
   215→>
   216→> **Gaps to Fix (high priority):**
   217→> [List of incomplete/broken items]
   218→>
   219→> **New Features to Build:**
   220→> [List of planned features]
   221→>
   222→> **Total Pending Features:** N
   223→>
   224→> Ready to generate the specification files?"
   225→
   226→**Ask for final confirmation:**
   227→
   228→> "1. **Yes, generate files** - Create app_spec.txt and update prompt files
   229→> 2. **I have changes** - Let me add or modify something first"
   230→
   231→---
   232→
   233→# FILE GENERATION
   234→
   235→**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**
   236→
   237→## Output Directory
   238→
   239→The output directory is: `$ARGUMENTS/prompts/`
   240→
   241→Once the user approves, generate these files:
   242→
   243→## 1. Generate `app_spec.txt`
   244→
   245→**Output path:** `$ARGUMENTS/prompts/app_spec.txt`
   246→
   247→Create a new file using this XML structure. Note the `import_mode` and `existing_features` sections:
   248→
   249→```xml
   250→<project_specification>
   251→  <project_name>[Project Name]</project_name>
   252→  <import_mode>true</import_mode>
   253→
   254→  <overview>
   255→    [2-3 sentence description of what this project is]
   256→  </overview>
   257→
   258→  <technology_stack>
   259→    [From analysis, corrected by user]
   260→    <frontend>
   261→      <framework>[Framework]</framework>
   262→      <styling>[Styling solution]</styling>
   263→    </frontend>
   264→    <backend>
   265→      <runtime>[Runtime]</runtime>
   266→      <database>[Database]</database>
   267→    </backend>
   268→  </technology_stack>
   269→
   270→  <feature_count>[total PENDING features - gaps + new]</feature_count>
   271→
   272→  <existing_features>
   273→    <!-- These are ALREADY IMPLEMENTED - for reference only -->
   274→    <category name="[Category 1]">
   275→      - [Existing feature 1] (complete)
   276→      - [Existing feature 2] (complete)
   277→    </category>
   278→    [Repeat for all existing feature categories]
   279→  </existing_features>
   280→
   281→  <gap_features>
   282→    <!-- These need FIXING or COMPLETION - high priority -->
   283→    <category name="[Category]">
   284→      - [Incomplete feature] (priority: high)
   285→      - [Bug to fix] (priority: high)
   286→    </category>
   287→  </gap_features>
   288→
   289→  <new_features>
   290→    <!-- These are NEW functionality to build -->
   291→    <category name="[Category]">
   292→      - [New feature 1]
   293→      - [New feature 2]
   294→    </category>
   295→  </new_features>
   296→
   297→  <implementation_priority>
   298→    <step number="1">
   299→      <title>Fix Critical Gaps</title>
   300→      <tasks>
   301→        [High priority fixes]
   302→      </tasks>
   303→    </step>
   304→    <step number="2">
   305→      <title>Complete Partial Features</title>
   306→      <tasks>
   307→        [Incomplete feature completion]
   308→      </tasks>
   309→    </step>
   310→    <step number="3">
   311→      <title>Build New Features</title>
   312→      <tasks>
   313→        [New functionality]
   314→      </tasks>
   315→    </step>
   316→  </implementation_priority>
   317→
   318→  <success_criteria>
   319→    <functionality>
   320→      [What does "done" look like?]
   321→    </functionality>
   322→  </success_criteria>
   323→</project_specification>
   324→```
   325→
   326→## 2. Update `initializer_prompt.md`
   327→
   328→**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`
   329→
   330→If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
   331→If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.
   332→
   333→**CRITICAL: You MUST update the feature count placeholder:**
   334→
   335→1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
   336→2. Replace `[FEATURE_COUNT]` with the number of PENDING features (gaps + new)
   337→3. The result should read like: `You must create exactly **25** features using the...`
   338→
   339→**Verify the update:** After editing, read the file again to confirm the feature count appears correctly.
   340→
   341→## 3. Write Status File (REQUIRED - Do This Last)
   342→
   343→**Output path:** `$ARGUMENTS/prompts/.spec_status.json`
   344→
   345→```json
   346→{
   347→  "status": "complete",
   348→  "version": 1,
   349→  "import_mode": true,
   350→  "timestamp": "[current ISO 8601 timestamp]",
   351→  "files_written": [
   352→    "prompts/app_spec.txt",
   353→    "prompts/initializer_prompt.md"
   354→  ],
   355→  "feature_count": [pending feature count],
   356→  "existing_feature_count": [documented existing features]
   357→}
   358→```
   359→
   360→---
   361→
   362→# AFTER FILE GENERATION: NEXT STEPS
   363→
   364→Once files are generated, tell the user:
   365→
   366→> "Your import specification has been created in `$ARGUMENTS/prompts/`!
   367→>
   368→> **What was documented:**
   369→> - [X] existing features (for reference)
   370→> - [Y] gaps to fix (high priority)
   371→> - [Z] new features to build
   372→>
   373→> **Total pending features:** [N]
   374→>
   375→> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
   376→>
   377→> **Important:** The agents will:
   378→> 1. First address high-priority gaps
   379→> 2. Then build new features
   380→> 3. Reference existing features to understand the codebase
   381→>
   382→> Press `Ctrl+C` to pause the agent at any time."
   383→
   384→---
   385→
   386→# IMPORTANT REMINDERS
   387→
   388→- **This is an IMPORT** - Don't ask about project name, tech stack, etc. if already detected
   389→- **Document existing work** - Users have invested time; acknowledge what's built
   390→- **Prioritize gaps** - Fixing broken things often matters more than new features
   391→- **Respect existing architecture** - Don't suggest rewrites unless asked
   392→- **Be thorough on gaps** - These are often the most frustrating issues for users
   393→
   394→---
   395→
   396→# BEGIN
   397→
   398→Start by presenting the analysis results and asking for confirmation:
   399→
   400→> "I've analyzed your existing project and I'm ready to help create a specification for it.
   401→>
   402→> [Present Phase 1 analysis summary]
   403→>
   404→> Let's start by confirming I understand your project correctly."
   405→
   406→**STOP HERE and wait for their response.**
   407→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

---
description: Import an existing project and create a spec (with codebase analysis)
---

# PROJECT DIRECTORY

This command **requires** the project directory as an argument via `$ARGUMENTS`.

**Example:** `/import-spec /path/to/existing-project`

**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`

If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.

---

# CODEBASE ANALYSIS

The following analysis was automatically generated from the existing project:

$CODEBASE_ANALYSIS

---

# GOAL

Help the user create a comprehensive project specification for an **EXISTING** codebase. This is different from creating a new project - we need to:

1. **Document what already exists** - Understand and catalog existing functionality
2. **Identify gaps** - What's incomplete, broken, or missing?
3. **Plan future work** - What should be built next?

The resulting specification will be used by AI coding agents to continue development.

---

# YOUR ROLE

You are the **Import Spec Assistant** - an expert at analyzing existing codebases and creating specifications that accurately reflect both current state and future plans.

**IMPORTANT: This is an IMPORT, not a new project.**

You should:
- Start by presenting what you learned from the codebase analysis
- Ask the user to confirm/correct your understanding
- Document existing features as "complete" (for reference)
- Identify gaps as "pending" (high priority)
- Plan new features as "pending" (to be built)

**The goal is a spec that helps agents understand what exists AND what to build next.**

---

# CONVERSATION FLOW

**CRITICAL: This is a CONVERSATION, not a form.**

- Ask questions for ONE phase at a time
- WAIT for the user to respond before moving to the next phase
- Acknowledge their answers before continuing
- Do NOT bundle multiple phases into one message

---

## Phase 1: Present Analysis

Start by presenting what you learned from the automated analysis:

> "I've analyzed your existing project! Here's what I found:
>
> **Project:** [name from analysis]
>
> **Technology Stack:**
> [List detected technologies from analysis]
>
> **Directory Structure:**
> [List key directories]
>
> **File Statistics:**
> [File counts by type]
>
> [If CLAUDE.md exists: Summarize what you learned from it]
>
> Does this look correct? Is there anything I'm missing about the tech stack?"

**WAIT for confirmation before continuing.**

---

## Phase 2: Project Understanding

Ask the user to explain the project in their own words:

> "Now let me understand what this project does:
>
> 1. What is the main purpose of this application?
> 2. Who uses it (or will use it)?
> 3. What's the current state - is it working, partially working, or mostly scaffolded?"

**WAIT for response before continuing.**

---

## Phase 3: Document Existing Features

Work with the user to catalog what's already built:

> "Let's document what's already working. Walk me through the existing functionality:
>
> 1. What can users currently DO with this application?
> 2. What screens or pages exist?
> 3. What backend functionality is implemented?
>
> I'll categorize these as 'existing features' in the spec."

**For each feature area mentioned, ask follow-up questions:**

- Is this fully working or partially implemented?
- Are there any known bugs?
- Is there test coverage?

**Keep asking until you have a complete picture of existing functionality.**

---

## Phase 4: Identify Gaps & Issues

Now focus on what's incomplete or broken:

> "Now let's identify what needs work. Think about:
>
> 1. **Incomplete features** - Things that are started but not finished
> 2. **Known bugs** - Issues that need fixing
> 3. **Missing functionality** - Features that were planned but not built
> 4. **Technical debt** - Code that needs refactoring
>
> What are the top priorities that need attention?"

**Drill into each gap:**

- What specifically doesn't work?
- How important is this? (blocking, annoying, nice-to-have)
- Any context on why it's incomplete?

---

## Phase 5: Plan Future Features

Ask about what should be built next:

> "Beyond fixing what's broken, what NEW features should be added?
>
> 1. What functionality would make this application complete?
> 2. Are there features users have requested?
> 3. Any integrations or enhancements planned?
>
> These will be added as 'pending' features for the agents to build."

**For each new feature:**

- Why is this needed?
- What's the priority relative to other new features?
- Any specific requirements or constraints?

---

## Phase 6: Derive Feature Count

After gathering all information, tally up the features:

**Existing features** (already implemented):
- Count discrete, testable behaviors that are working
- These go in the spec as reference but won't be rebuilt

**Gap features** (need fixing/completion):
- Count incomplete or broken features
- These are HIGH PRIORITY pending items

**New features** (to be built):
- Count planned new functionality
- These are NORMAL PRIORITY pending items

**Present your estimate:**

> "Based on what we discussed, here's my feature breakdown:
>
> **Existing (reference):** ~X features
> [Categories and counts]
>
> **Gaps (high priority):** ~Y features
> [Categories and counts]
>
> **New (to build):** ~Z features
> [Categories and counts]
>
> **Total pending features:** Y + Z = N
>
> Does this seem right? The agents will focus on the pending features."

Let the user confirm or adjust.

---

## Phase 7: Review & Approval

Present the complete plan:

> "Here's the complete specification for your imported project:
>
> **Project:** [name]
> **Tech Stack:** [from analysis + any corrections]
>
> **Existing Features (documented for reference):**
> [Summary of what's built]
>
> **Gaps to Fix (high priority):**
> [List of incomplete/broken items]
>
> **New Features to Build:**
> [List of planned features]
>
> **Total Pending Features:** N
>
> Ready to generate the specification files?"

**Ask for final confirmation:**

> "1. **Yes, generate files** - Create app_spec.txt and update prompt files
> 2. **I have changes** - Let me add or modify something first"

---

# FILE GENERATION

**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**

## Output Directory

The output directory is: `$ARGUMENTS/prompts/`

Once the user approves, generate these files:

## 1. Generate `app_spec.txt`

**Output path:** `$ARGUMENTS/prompts/app_spec.txt`

Create a new file using this XML structure. Note the `import_mode` and `existing_features` sections:

```xml
<project_specification>
  <project_name>[Project Name]</project_name>
  <import_mode>true</import_mode>

  <overview>
    [2-3 sentence description of what this project is]
  </overview>

  <technology_stack>
    [From analysis, corrected by user]
    <frontend>
      <framework>[Framework]</framework>
      <styling>[Styling solution]</styling>
    </frontend>
    <backend>
      <runtime>[Runtime]</runtime>
      <database>[Database]</database>
    </backend>
  </technology_stack>

  <feature_count>[total PENDING features - gaps + new]</feature_count>

  <existing_features>
    <!-- These are ALREADY IMPLEMENTED - for reference only -->
    <category name="[Category 1]">
      - [Existing feature 1] (complete)
      - [Existing feature 2] (complete)
    </category>
    [Repeat for all existing feature categories]
  </existing_features>

  <gap_features>
    <!-- These need FIXING or COMPLETION - high priority -->
    <category name="[Category]">
      - [Incomplete feature] (priority: high)
      - [Bug to fix] (priority: high)
    </category>
  </gap_features>

  <new_features>
    <!-- These are NEW functionality to build -->
    <category name="[Category]">
      - [New feature 1]
      - [New feature 2]
    </category>
  </new_features>

  <implementation_priority>
    <step number="1">
      <title>Fix Critical Gaps</title>
      <tasks>
        [High priority fixes]
      </tasks>
    </step>
    <step number="2">
      <title>Complete Partial Features</title>
      <tasks>
        [Incomplete feature completion]
      </tasks>
    </step>
    <step number="3">
      <title>Build New Features</title>
      <tasks>
        [New functionality]
      </tasks>
    </step>
  </implementation_priority>

  <success_criteria>
    <functionality>
      [What does "done" look like?]
    </functionality>
  </success_criteria>
</project_specification>
```

## 2. Update `initializer_prompt.md`

**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`

If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.

**CRITICAL: You MUST update the feature count placeholder:**

1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
2. Replace `[FEATURE_COUNT]` with the number of PENDING features (gaps + new)
3. The result should read like: `You must create exactly **25** features using the...`

**Verify the update:** After editing, read the file again to confirm the feature count appears correctly.

## 3. Write Status File (REQUIRED - Do This Last)

**Output path:** `$ARGUMENTS/prompts/.spec_status.json`

```json
{
  "status": "complete",
  "version": 1,
  "import_mode": true,
  "timestamp": "[current ISO 8601 timestamp]",
  "files_written": [
    "prompts/app_spec.txt",
    "prompts/initializer_prompt.md"
  ],
  "feature_count": [pending feature count],
  "existing_feature_count": [documented existing features]
}
```

---

# AFTER FILE GENERATION: NEXT STEPS

Once files are generated, tell the user:

> "Your import specification has been created in `$ARGUMENTS/prompts/`!
>
> **What was documented:**
> - [X] existing features (for reference)
> - [Y] gaps to fix (high priority)
> - [Z] new features to build
>
> **Total pending features:** [N]
>
> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
>
> **Important:** The agents will:
> 1. First address high-priority gaps
> 2. Then build new features
> 3. Reference existing features to understand the codebase
>
> Press `Ctrl+C` to pause the agent at any time."

---

# IMPORTANT REMINDERS

- **This is an IMPORT** - Don't ask about project name, tech stack, etc. if already detected
- **Document existing work** - Users have invested time; acknowledge what's built
- **Prioritize gaps** - Fixing broken things often matters more than new features
- **Respect existing architecture** - Don't suggest rewrites unless asked
- **Be thorough on gaps** - These are often the most frustrating issues for users

---

# BEGIN

Start by presenting the analysis results and asking for confirmation:

> "I've analyzed your existing project and I'm ready to help create a specification for it.
>
> [Present Phase 1 analysis summary]
>
> Let's start by confirming I understand your project correctly."

**STOP HERE and wait for their response.**


Good, I have both skill files. Now let me copy them to the backend's .claude/commands directory.


Now let me copy both skill files to the backend.


Bash

Copy create-spec.md skill


Error: Exit code 2
/usr/bin/bash: eval: line 1: unexpected EOF while looking for matching `"'


The Windows paths with backslashes are causing issues in bash. Let me use forward slashes.


Copy create-spec.md skill


That worked. Let me copy import-spec.md too.


Copy import-spec.md skill


Good. Now let me also check if there's a templates directory needed and copy the initializer_prompt.template.md file.


List templates directory


total 64
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  8 13:53 ./
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  8 13:53 ../
-rw-r--r-- 1 AzureAD+MikeSwanson 4096  9035 Jan  8 08:02 app_spec.template.txt
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 14174 Jan  8 08:02 coding_prompt.template.md
-rw-r--r-- 1 AzureAD+MikeSwanson 4096  7910 Jan  8 08:02 coding_prompt_yolo.template.md
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 19456 Jan  8 08:02 initializer_prompt.template.md


Let me also copy the templates directory to the backend so the spec creation session can find the templates.


Copy templates directory


Good. Now I need to:1. Update the services __init__.py to export the spec_chat_session functions2. Update the spec router to use the real Claude SDK session instead of the demo version


TodoWrite

Create spec_chat_session service

Copy skill files and templates

Update services __init__.py

Update spec router to use Claude SDK

Test full interview flow


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

Create spec_chat_session service

Copy skill files (create-spec.md, import-spec.md)

Update spec router to use Claude SDK

Update services __init__.py

Test full interview flow

Create spec_chat_session service

Copy skill files and templates

Update services __init__.py

Update spec router to use Claude SDK

Test full interview flow


Let me update the services __init__.py file.


     1→"""Services package for autocoder+ backend."""
     2→
     3→from .codebase_analyzer import (
     4→    CodebaseAnalysis,
     5→    analyze_codebase,
     6→    format_analysis_for_claude,
     7→)
     8→
     9→__all__ = [
    10→    "CodebaseAnalysis",
    11→    "analyze_codebase",
    12→    "format_analysis_for_claude",
    13→]
    14→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

"""Services package for autocoder+ backend."""

from .codebase_analyzer import (
    CodebaseAnalysis,
    analyze_codebase,
    format_analysis_for_claude,
)

__all__ = [
    "CodebaseAnalysis",
    "analyze_codebase",
    "format_analysis_for_claude",
]


I need to add the spec_chat_session exports to this file.


Edit

"""Services package for autocoder+ backend."""

from .codebase_analyzer import (
    CodebaseAnalysis,
    analyze_codebase,
    format_analysis_for_claude,
)

__all__ = [
    "CodebaseAnalysis",
    "analyze_codebase",
    "format_analysis_for_claude",
]

"""Services package for autocoder+ backend."""

from .codebase_analyzer import (
    CodebaseAnalysis,
    analyze_codebase,
    format_analysis_for_claude,
)

from .spec_chat_session import (
    SpecChatSession,
    ImageAttachment,
    create_session,
    get_session,
    remove_session,
    list_sessions,
    cleanup_all_sessions,
)

__all__ = [
    # Codebase analyzer
    "CodebaseAnalysis",
    "analyze_codebase",
    "format_analysis_for_claude",
    # Spec chat session
    "SpecChatSession",
    "ImageAttachment",
    "create_session",
    "get_session",
    "remove_session",
    "list_sessions",
    "cleanup_all_sessions",
]


The file C:\Users\MikeSwanson\claude-projects\Autocode-remix\Autocode-fork\backend\app\services\__init__.py has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
     1→"""Services package for autocoder+ backend."""
     2→
     3→from .codebase_analyzer import (
     4→    CodebaseAnalysis,
     5→    analyze_codebase,
     6→    format_analysis_for_claude,
     7→)
     8→
     9→from .spec_chat_session import (
    10→    SpecChatSession,
    11→    ImageAttachment,
    12→    create_session,
    13→    get_session,
    14→    remove_session,
    15→    list_sessions,
    16→    cleanup_all_sessions,
    17→)
    18→
    19→__all__ = [
    20→    # Codebase analyzer
    21→    "CodebaseAnalysis",
    22→    "analyze_codebase",
    23→    "format_analysis_for_claude",
    24→    # Spec chat session
    25→    "SpecChatSession",
    26→    "ImageAttachment",
    27→    "create_session",
    28→    "get_session",
    29→    "remove_session",
    30→    "list_sessions",
    31→    "cleanup_all_sessions",
    32→]
    33→

"""Services package for autocoder+ backend."""

from .codebase_analyzer import (
    CodebaseAnalysis,
    analyze_codebase,
    format_analysis_for_claude,
)

__all__ = [
    "CodebaseAnalysis",
    "analyze_codebase",
    "format_analysis_for_claude",
]

"""Services package for autocoder+ backend."""

from .codebase_analyzer import (
    CodebaseAnalysis,
    analyze_codebase,
    format_analysis_for_claude,
)

from .spec_chat_session import (
    SpecChatSession,
    ImageAttachment,
    create_session,
    get_session,
    remove_session,
    list_sessions,
    cleanup_all_sessions,
)

__all__ = [
    # Codebase analyzer
    "CodebaseAnalysis",
    "analyze_codebase",
    "format_analysis_for_claude",
    # Spec chat session
    "SpecChatSession",
    "ImageAttachment",
    "create_session",
    "get_session",
    "remove_session",
    "list_sessions",
    "cleanup_all_sessions",
]

format_analysis_for_claude,
)
+from .spec_chat_session import (
+    SpecChatSession,
+    ImageAttachment,
+    create_session,
+    get_session,
+    remove_session,
+    list_sessions,
+    cleanup_all_sessions,
+)
+
__all__ = [
+    # Codebase analyzer
"CodebaseAnalysis",
"analyze_codebase",
"format_analysis_for_claude",
+    # Spec chat session
+    "SpecChatSession",
+    "ImageAttachment",
+    "create_session",
+    "get_session",
+    "remove_session",
+    "list_sessions",
+    "cleanup_all_sessions",
]


Now I need to update the spec router to use the real Claude SDK session instead of the demo placeholders. Let me update it.


TodoWrite

Create spec_chat_session service

Copy skill files and templates

Update services __init__.py

Update spec router to use Claude SDK

Test full interview flow


Create spec_chat_session service

Copy skill files and templates

Update services __init__.py

Update spec router to use Claude SDK

Test full interview flow

Create spec_chat_session service

Copy skill files and templates

Update services __init__.py

Update spec router to use Claude SDK

Test full interview flow


Now let me update the spec router to use the real Claude SDK session. I need to replace the demo WebSocket endpoint with one that uses the spec_chat_session service.


Now let me update the spec router to use the real Claude SDK session.


   330→    else:
   331→        change_summary = spec_update.change_summary or "Initial spec creation"
   332→
   333→    return SpecAnalysisResponse(
   334→        affected_features=affected,
   335→        affected_count=len(affected),
   336→        change_summary=change_summary
   337→    )
   338→
   339→
   340→# ============================================================================
   341→# WebSocket Endpoint for Spec Creation Interview
   342→# ============================================================================
   343→
   344→@spec_ws_router.websocket("/ws/{project_name}")
   345→async def spec_chat_websocket(websocket: WebSocket, project_name: str):
   346→    """
   347→    WebSocket endpoint for interactive spec creation chat with Claude.
   348→
   349→    Message protocol:
   350→
   351→    Client -> Server:
   352→    - {"type": "start"} - Start the spec creation session
   353→    - {"type": "message", "content": "..."} - Send user message
   354→    - {"type": "ping"} - Keep-alive ping
   355→
   356→    Server -> Client:
   357→    - {"type": "text", "content": "..."} - Text chunk from Claude
   358→    - {"type": "spec_complete", "path": "..."} - Spec file created
   359→    - {"type": "complete"} - Session complete
   360→    - {"type": "error", "content": "..."} - Error message
   361→    - {"type": "pong"} - Keep-alive pong
   362→    """
   363→    # Verify project exists
   364→    async with async_session_maker() as session:
   365→        result = await session.execute(
   366→            select(Project).where(Project.name == project_name)
   367→        )
   368→        project = result.scalar_one_or_none()
   369→
   370→        if not project:
   371→            await websocket.close(code=4004, reason=f"Project '{project_name}' not found")
   372→            return
   373→
   374→    await websocket.accept()
   375→    logger.info(f"Spec interview WebSocket connected for project: {project_name}")
   376→
   377→    try:
   378→        while True:
   379→            try:
   380→                data = await websocket.receive_text()
   381→                message = json.loads(data)
   382→                msg_type = message.get("type")
   383→
   384→                if msg_type == "ping":
   385→                    await websocket.send_json({"type": "pong"})
   386→                    continue
   387→
   388→                elif msg_type == "start":
   389→                    # Send initial greeting
   390→                    await websocket.send_json({
   391→                        "type": "text",
   392→                        "content": f"# Spec Interview for {project_name}\n\n"
   393→                    })
   394→                    await websocket.send_json({
   395→                        "type": "text",
   396→                        "content": "Welcome to the spec creation interview! I'll help you define your application's features and requirements.\n\n"
   397→                    })
   398→                    await websocket.send_json({
   399→                        "type": "text",
   400→                        "content": "**Note:** Full Claude integration is being configured. For now, this is a demo of the interview interface.\n\n"
   401→                    })
   402→                    await websocket.send_json({
   403→                        "type": "text",
   404→                        "content": "To complete the setup, the backend needs to integrate with the Claude Agent SDK.\n\n"
   405→                    })
   406→                    await websocket.send_json({
   407→                        "type": "text",
   408→                        "content": "**What would you like your application to do?** Tell me about the core functionality you're envisioning."
   409→                    })
   410→                    await websocket.send_json({"type": "response_done"})
   411→
   412→                elif msg_type == "message":
   413→                    user_content = message.get("content", "").strip()
   414→                    if not user_content:
   415→                        await websocket.send_json({
   416→                            "type": "error",
   417→                            "content": "Empty message"
   418→                        })
   419→                        continue
   420→
   421→                    # Echo back for demo purposes
   422→                    await websocket.send_json({
   423→                        "type": "text",
   424→                        "content": f"I heard you say: \"{user_content}\"\n\n"
   425→                    })
   426→                    await websocket.send_json({
   427→                        "type": "text",
   428→                        "content": "In the full implementation, Claude would process your response and guide you through defining:\n"
   429→                    })
   430→                    await websocket.send_json({
   431→                        "type": "text",
   432→                        "content": "- Core features and functionality\n- Technology stack preferences\n- User interface requirements\n- Success criteria\n\n"
   433→                    })
   434→                    await websocket.send_json({
   435→                        "type": "text",
   436→                        "content": "The spec creation system is ready for Claude Agent SDK integration."
   437→                    })
   438→                    await websocket.send_json({"type": "response_done"})
   439→
   440→                else:
   441→                    await websocket.send_json({
   442→                        "type": "error",
   443→                        "content": f"Unknown message type: {msg_type}"
   444→                    })
   445→
   446→            except json.JSONDecodeError:
   447→                await websocket.send_json({
   448→                    "type": "error",
   449→                    "content": "Invalid JSON"
   450→                })
   451→
   452→    except WebSocketDisconnect:
   453→        logger.info(f"Spec interview WebSocket disconnected for {project_name}")
   454→
   455→    except Exception as e:
   456→        logger.exception(f"Spec interview WebSocket error for {project_name}")
   457→        try:
   458→            await websocket.send_json({
   459→                "type": "error",
   460→                "content": f"Server error: {str(e)}"
   461→            })
   462→        except Exception:
   463→            pass
   464→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

    else:
        change_summary = spec_update.change_summary or "Initial spec creation"

    return SpecAnalysisResponse(
        affected_features=affected,
        affected_count=len(affected),
        change_summary=change_summary
    )

# ============================================================================
# WebSocket Endpoint for Spec Creation Interview
# ============================================================================

@spec_ws_router.websocket("/ws/{project_name}")
async def spec_chat_websocket(websocket: WebSocket, project_name: str):
    """
    WebSocket endpoint for interactive spec creation chat with Claude.

    Message protocol:

    Client -> Server:
    - {"type": "start"} - Start the spec creation session
    - {"type": "message", "content": "..."} - Send user message
    - {"type": "ping"} - Keep-alive ping

    Server -> Client:
    - {"type": "text", "content": "..."} - Text chunk from Claude
    - {"type": "spec_complete", "path": "..."} - Spec file created
    - {"type": "complete"} - Session complete
    - {"type": "error", "content": "..."} - Error message
    - {"type": "pong"} - Keep-alive pong
    """
    # Verify project exists
    async with async_session_maker() as session:
        result = await session.execute(
            select(Project).where(Project.name == project_name)
        )
        project = result.scalar_one_or_none()

        if not project:
            await websocket.close(code=4004, reason=f"Project '{project_name}' not found")
            return

    await websocket.accept()
    logger.info(f"Spec interview WebSocket connected for project: {project_name}")

    try:
        while True:
            try:
                data = await websocket.receive_text()
                message = json.loads(data)
                msg_type = message.get("type")

                if msg_type == "ping":
                    await websocket.send_json({"type": "pong"})
                    continue

                elif msg_type == "start":
                    # Send initial greeting
                    await websocket.send_json({
                        "type": "text",
                        "content": f"# Spec Interview for {project_name}\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "Welcome to the spec creation interview! I'll help you define your application's features and requirements.\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "**Note:** Full Claude integration is being configured. For now, this is a demo of the interview interface.\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "To complete the setup, the backend needs to integrate with the Claude Agent SDK.\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "**What would you like your application to do?** Tell me about the core functionality you're envisioning."
                    })
                    await websocket.send_json({"type": "response_done"})

                elif msg_type == "message":
                    user_content = message.get("content", "").strip()
                    if not user_content:
                        await websocket.send_json({
                            "type": "error",
                            "content": "Empty message"
                        })
                        continue

                    # Echo back for demo purposes
                    await websocket.send_json({
                        "type": "text",
                        "content": f"I heard you say: \"{user_content}\"\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "In the full implementation, Claude would process your response and guide you through defining:\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "- Core features and functionality\n- Technology stack preferences\n- User interface requirements\n- Success criteria\n\n"
                    })
                    await websocket.send_json({
                        "type": "text",
                        "content": "The spec creation system is ready for Claude Agent SDK integration."
                    })
                    await websocket.send_json({"type": "response_done"})

                else:
                    await websocket.send_json({
                        "type": "error",
                        "content": f"Unknown message type: {msg_type}"
                    })

            except json.JSONDecodeError:
                await websocket.send_json({
                    "type": "error",
                    "content": "Invalid JSON"
                })

    except WebSocketDisconnect:
        logger.info(f"Spec interview WebSocket disconnected for {project_name}")

    except Exception as e:
        logger.exception(f"Spec interview WebSocket error for {project_name}")
        try:
            await websocket.send_json({
                "type": "error",
                "content": f"Server error: {str(e)}"
            })
        except Exception:
            pass


Now I need to replace the entire WebSocket endpoint with one that uses the real Claude SDK session. Let me also add the necessary imports and update the implementation.


Edit

from ..database import get_db, async_session_maker
from ..models import Project, SpecHistory, Feature

logger = logging.getLogger(__name__)

from ..database import get_db, async_session_maker
from ..models import Project, SpecHistory, Feature
from ..services.spec_chat_session import (
    SpecChatSession,
    ImageAttachment,
    create_session,
    get_session,
    remove_session,
)

logger = logging.getLogger(__name__)