audit-mike-actions.ps1
Autocode-remix/
bgbuilders-dns-records.txt
bgbuildersllc-godaddy-zonefile.txt
check-firewall.ps1
check-fresh-logs.ps1
check-mailbox-rules.ps1
check-mike-signins.ps1
check-monday-meetings.ps1
check-nps.ps1
check-nps-listening.ps1
check-nps-logs.ps1
check-nps-service.ps1
check-rules-graph.ps1
check-sysadmin.ps1
claude.bat
CLAUDE.md
claude_code_quickstart.md
claude-settings/
cleanup-lehman.ps1
cloudflare-whm/
connect-acg-tenant.ps1
cookies.txt
create-app.ps1
dataforth-vpn.ovpn
dataforth-vpn-linux.ovpn
debug-nps.ps1
exo-investigate.ps1
exo-shelly.ps1
find-users.ps1
fix-nps.ps1
fix-nps-logging.ps1
fix-radius-client.ps1
full-investigate.ps1
get-nps-config.ps1
get-nps-policies.ps1
get-nps-simple.ps1
grabb-website-move/
grant-access.ps1
grant-access-scan.ps1
graph-admin-investigate.ps1
graph-rest-investigate.ps1
guru-connect/
gururmm.temp/
install_claudecode.sh*
investigate-interactive.ps1
investigate-mike.ps1
investigate-mike-full.ps1
investigate-shelly.ps1
launch-investigation.ps1
lehman-dup-contacts.csv
lehman-dup-events.csv
list-users.ps1
monitor-radius.ps1
msp-toolkit/
msp-toolkit-rust/
nul
ralphstransfer-security-audit-2025-12-12.md
reference/
run-scan.ps1
scan-duplicates.ps1
scan-lehman.ps1
scan-my-duplicates.ps1
seafile-graph-email/
send-migration-notice.sh*
server-migration-email.txt
session-logs/
setup-claude-mac.sh*
setup-claude-workstation.ps1
shared-data/
shelly-exo-results.txt
shelly-investigation-results.txt
test-radius.ps1
trace-radius.ps1
verify-and-restart-nps.ps1
verify-lehman.ps1
Website2025/
whm-dns-cleanup/
windows-setup-helper/


Found it - it's `guru-connect/` (lowercase). Let me check its structure to understand what kind of project we'd be importing.


Bash

ls -la /c/Users/MikeSwanson/claude-projects/guru-connect/ && echo "---" && find /c/Users/MikeSwanson/claude-projects/guru-connect -name "package.json" -o -name "Cargo.toml" -o -name "requirements.txt" -o -name "README.md" 2>/dev/null | head -10

Check guru-connect structure


total 145
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 21 19:04 ./
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  8 16:23 ../
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  8 15:03 .git/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096   255 Dec 21 18:58 .gitignore
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 22 05:01 agent/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 82502 Dec 21 18:58 Cargo.lock
-rw-r--r-- 1 AzureAD+MikeSwanson 4096   649 Dec 21 18:58 Cargo.toml
-rw-r--r-- 1 AzureAD+MikeSwanson 4096  3240 Dec 21 18:58 CLAUDE.md
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 21 20:06 dashboard/
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 21 18:58 proto/
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 21 18:58 server/
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Dec 21 19:09 target/
---
/c/Users/MikeSwanson/claude-projects/guru-connect/agent/Cargo.toml
/c/Users/MikeSwanson/claude-projects/guru-connect/Cargo.toml
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/.vite/deps/package.json
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/code-frame/package.json
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/code-frame/README.md
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/compat-data/package.json
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/compat-data/README.md
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/core/package.json
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/core/README.md
/c/Users/MikeSwanson/claude-projects/guru-connect/dashboard/node_modules/@babel/generator/package.json


Now I have a good understanding of the GuruConnect project:
- Rust workspace (Cargo.toml at root)
- `agent/` - Rust agent
- `dashboard/` - Node.js frontend (React likely)
- `server/` - Rust server
- `proto/` - Protocol buffers
- Has a CLAUDE.md file already

This is a great test case for the import feature. Let me check if there's a dashboard package.json:


     1→# GuruConnect
     2→
     3→Remote desktop solution similar to ScreenConnect, integrated with GuruRMM.
     4→
     5→## Project Overview
     6→
     7→GuruConnect provides remote screen control and backstage tools for Windows systems.
     8→It's designed to be fast, secure, and enterprise-ready.
     9→
    10→## Architecture
    11→
    12→```
    13→┌─────────────────┐         ┌─────────────────┐         ┌─────────────────┐
    14→│   Dashboard     │◄───────►│  GuruConnect    │◄───────►│  GuruConnect    │
    15→│   (React)       │  WSS    │  Server (Rust)  │  WSS    │  Agent (Rust)   │
    16→└─────────────────┘         └─────────────────┘         └─────────────────┘
    17→```
    18→
    19→## Directory Structure
    20→
    21→- `agent/` - Windows remote desktop agent (Rust)
    22→- `server/` - Relay server (Rust + Axum)
    23→- `dashboard/` - Web viewer (React, to be integrated with GuruRMM)
    24→- `proto/` - Protobuf protocol definitions
    25→
    26→## Building
    27→
    28→### Prerequisites
    29→
    30→- Rust 1.75+ (install via rustup)
    31→- Windows SDK (for agent)
    32→- protoc (Protocol Buffers compiler)
    33→
    34→### Build Commands
    35→
    36→```bash
    37→# Build all (from workspace root)
    38→cargo build --release
    39→
    40→# Build agent only
    41→cargo build -p guruconnect-agent --release
    42→
    43→# Build server only
    44→cargo build -p guruconnect-server --release
    45→```
    46→
    47→### Cross-compilation (Agent for Windows)
    48→
    49→From Linux build server:
    50→```bash

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

# GuruConnect

Remote desktop solution similar to ScreenConnect, integrated with GuruRMM.

## Project Overview

GuruConnect provides remote screen control and backstage tools for Windows systems.
It's designed to be fast, secure, and enterprise-ready.

## Architecture

```
┌─────────────────┐         ┌─────────────────┐         ┌─────────────────┐
│   Dashboard     │◄───────►│  GuruConnect    │◄───────►│  GuruConnect    │
│   (React)       │  WSS    │  Server (Rust)  │  WSS    │  Agent (Rust)   │
└─────────────────┘         └─────────────────┘         └─────────────────┘
```

## Directory Structure

- `agent/` - Windows remote desktop agent (Rust)
- `server/` - Relay server (Rust + Axum)
- `dashboard/` - Web viewer (React, to be integrated with GuruRMM)
- `proto/` - Protobuf protocol definitions

## Building

### Prerequisites

- Rust 1.75+ (install via rustup)
- Windows SDK (for agent)
- protoc (Protocol Buffers compiler)

### Build Commands

```bash
# Build all (from workspace root)
cargo build --release

# Build agent only
cargo build -p guruconnect-agent --release

# Build server only
cargo build -p guruconnect-server --release
```

### Cross-compilation (Agent for Windows)

From Linux build server:
```bash


This is great - GuruConnect already has a CLAUDE.md file with project documentation. This is valuable context that the import feature could use. The project has:- React dashboard
- Rust server (Axum)
- Rust agent- Protocol buffers- Good documentationThis confirms the import feature should:
1. Detect CLAUDE.md and include its content in the analysis2. Detect Cargo.toml and package.json
3. Analyze the directory structureNow I have enough context. Let me ask the user a clarifying question about one design decision, then finalize the plan.


GuruConnect has a CLAUDE.md file with good documentation - the import feature should definitely leverage that!

I have one clarifying question before finalizing the plan:


AskUserQuestion

Question: When importing an existing project like GuruConnect, should the spec interview focus more on documenting what EXISTS or planning what SHOULD BE BUILT next?

Choices:
Claude analyzes and documents what the codebase already does, creating a spec that reflects current functionality
Claude uses existing code as context but focuses on what features should be added or improved
Document existing functionality AND identify gaps/next steps for development


User has answered your questions: "When importing an existing project like GuruConnect, should the spec interview focus more on documenting what EXISTS or planning what SHOULD BE BUILT next?"="Both - hybrid approach". You can now continue with the user's answers in mind.

Question: When importing an existing project like GuruConnect, should the spec interview focus more on documenting what EXISTS or planning what SHOULD BE BUILT next?

Choices:
Claude analyzes and documents what the codebase already does, creating a spec that reflects current functionality
Claude uses existing code as context but focuses on what features should be added or improved
Document existing functionality AND identify gaps/next steps for development


The user wants a hybrid approach - document existing functionality AND identify gaps/next steps. This is the most useful approach. Let me update the plan to reflect this and then exit plan mode to get approval.


Good choice - the hybrid approach makes the most sense. Let me update the plan to reflect this:


Edit

### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- Phases adjusted for existing codebase:
  - Phase 1: Review what's already there (from analysis)
  - Phase 2: Confirm/correct detected tech stack
  - Phase 3: Ask about features the codebase SHOULD have
  - Phase 4: Derive feature list from existing code + discussion
  - Phase 5-7: Same as create-spec

### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec


The file C:\Users\MikeSwanson\.claude\plans\floating-yawning-cray.md has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
    50→- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
    51→- Modify `start()` to prepend context to system prompt when importing
    52→- Create import-specific preamble for Claude
    53→
    54→#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
    55→- Similar to `create-spec.md` but with import context
    56→- **Hybrid approach**: Document existing + plan future
    57→- Phases adjusted for existing codebase:
    58→  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
    59→  - Phase 2: User confirms/corrects what project does today
    60→  - Phase 3: Document EXISTING features (what's already built)
    61→  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
    62→  - Phase 5: Plan NEXT features (what should be added)
    63→  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
    64→  - Phase 7: Review & generate spec
    65→
    66→### Frontend Changes
    67→
    68→#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option

### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec

# Import Existing Project Feature - Implementation Plan

## Overview

Add the ability to import an existing project folder into autocoder+, analyze its contents, and run the spec creation interview with context about what's already there.

## User Flow

```
Current "New Project" Flow:
  Name → Folder (NEW) → Method → Claude Interview → Start Agent

New "Import" Flow:
  [Import Existing] → Folder (SELECT EXISTING) → Name (default to folder name)
    → Analyze Codebase → Claude Interview (WITH CONTEXT) → Start Agent
```

## Files to Modify/Create

### Backend Changes

#### 1. `backend/app/routers/projects.py` - Add import endpoint
- Add `POST /api/projects/import` endpoint
- Accepts: `{ name: str, path: str, analyze: bool = true }`
- Validates path exists and is a directory
- Calls codebase analyzer
- Creates project in database
- Returns project + analysis results

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type
- Read README if present
- Identify frameworks (React, Express, FastAPI, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".py": 12}
    detected_stack: dict  # {frontend: "React", backend: "FastAPI", db: "SQLite"}
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Python main.py, etc.
```

#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
- Modify `start()` to prepend context to system prompt when importing
- Create import-specific preamble for Claude

#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- Phases adjusted for existing codebase:
  - Phase 1: Review what's already there (from analysis)
  - Phase 2: Confirm/correct detected tech stack
  - Phase 3: Ask about features the codebase SHOULD have
  - Phase 4: Derive feature list from existing code + discussion
  - Phase 5-7: Same as create-spec

### Frontend Changes

#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option
- Add initial step to choose: "Create New" vs "Import Existing"
- New state: `isImportMode: boolean`
- When import mode:
  - FolderBrowser selects existing folder (not append name)
  - Project name defaults to folder name
  - Pass `isImport: true` to API

#### 6. `ui/src/components/FolderBrowser.tsx` - Support import mode
- Add prop: `mode: 'create' | 'import'`
- In import mode:
  - Allow selection of non-empty folders
  - Show file count in folder
  - "Select This Project Folder" button text

#### 7. `ui/src/hooks/useProjects.ts` - Add import mutation
```typescript
export function useImportProject() {
  return useMutation({
    mutationFn: ({ name, path }) =>
      api.importProject(name, path),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projects'] })
    },
  })
}
```

#### 8. `ui/src/lib/api.ts` - Add import API call
```typescript
async importProject(name: string, path: string): Promise<ProjectWithAnalysis> {
  const response = await fetch(`${this.baseUrl}/api/projects/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, path }),
  })
  return response.json()
}
```

#### 9. `ui/src/components/SpecCreationChat.tsx` - Show analysis context
- Accept optional `codebaseAnalysis` prop
- Display analysis summary at start of chat
- Pass to backend via WebSocket start message

## Implementation Order

1. **Backend analyzer** - Create `codebase_analyzer.py` service
2. **Backend endpoint** - Add import endpoint to `projects.py`
3. **Import skill** - Create `import-spec.md` Claude skill
4. **Session modifications** - Update `spec_chat_session.py` for import context
5. **Frontend API** - Add `importProject` to `api.ts` and `useProjects.ts`
6. **FolderBrowser** - Add import mode support
7. **NewProjectModal** - Add Create/Import choice and import flow
8. **SpecCreationChat** - Display analysis context

## Key Design Decisions

### 1. Separate Import Skill vs. Modified Create Skill
**Decision**: Create separate `import-spec.md` skill
**Reason**: Cleaner separation, different conversation flow, easier to maintain

### 2. Analysis Depth
**Decision**: Lightweight analysis (file types, package files, README)
**Reason**: Don't want to read all source code (too slow, context limits). Let Claude ask about specifics.

### 3. Project Name Handling
**Decision**: Default to folder name, allow user to change
**Reason**: Existing folders have meaningful names, but user should be able to override

### 4. Import vs Create Backend
**Decision**: Separate `/api/projects/import` endpoint
**Reason**: Different validation (folder must exist), includes analysis step

## Testing Plan

1. **Unit test** `codebase_analyzer.py` with sample project structures
2. **Integration test** import endpoint with real folder
3. **E2E test**: Import the GuruConnect folder, verify:
   - Analysis detects tech stack correctly
   - Claude interview receives context
   - Spec file is generated with existing code awareness

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (package.json with react dependency)
- Rust backend (Cargo.toml)
- SQLite database
- File counts by type

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. I can see it's a React + Rust application with approximately X files. Let me ask some questions to understand what features this application should have..."

+- **Hybrid approach**: Document existing + plan future

-  - Phase 1: Review what's already there (from analysis)

-  - Phase 2: Confirm/correct detected tech stack

-  - Phase 3: Ask about features the codebase SHOULD have

-  - Phase 4: Derive feature list from existing code + discussion

+  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)

+  - Phase 2: User confirms/corrects what project does today

+  - Phase 3: Document EXISTING features (what's already built)

+  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)

+  - Phase 5: Plan NEXT features (what should be added)

+  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")


Now let me also update the example at the bottom of the plan to reflect the hybrid approach, and add that the analyzer should read CLAUDE.md if present.


## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (package.json with react dependency)
- Rust backend (Cargo.toml)
- SQLite database
- File counts by type

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. I can see it's a React + Rust application with approximately X files. Let me ask some questions to understand what features this application should have..."

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (dashboard/package.json)
- Rust server + agent (Cargo.toml workspace)
- Protocol buffers (proto/ directory)
- CLAUDE.md with project documentation
- File counts: ~X .rs files, ~Y .tsx files

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
> - React dashboard
> - Rust relay server (Axum)
> - Rust Windows agent
> - Protocol buffer messaging
>
> Let's document what's already working, identify any gaps, and plan what should be built next..."

The resulting spec would have:
- **Existing features** marked as implemented (for reference)
- **Gaps/incomplete features** marked as pending (high priority)
- **New features** marked as pending (to be built)


The file C:\Users\MikeSwanson\.claude\plans\floating-yawning-cray.md has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
   147→   - Analysis detects tech stack correctly
   148→   - Claude interview receives context
   149→   - Spec file is generated with existing code awareness
   150→
   151→## Example: GuruConnect Import
   152→
   153→When importing GuruConnect, the analyzer should detect:
   154→- React frontend (dashboard/package.json)
   155→- Rust server + agent (Cargo.toml workspace)
   156→- Protocol buffers (proto/ directory)
   157→- CLAUDE.md with project documentation
   158→- File counts: ~X .rs files, ~Y .tsx files
   159→
   160→Claude's interview would start with:
   161→> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
   162→> - React dashboard
   163→> - Rust relay server (Axum)
   164→> - Rust Windows agent
   165→> - Protocol buffer messaging
   166→>
   167→> Let's document what's already working, identify any gaps, and plan what should be built next..."
   168→
   169→The resulting spec would have:
   170→- **Existing features** marked as implemented (for reference)
   171→- **Gaps/incomplete features** marked as pending (high priority)
   172→- **New features** marked as pending (to be built)
   173→

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (dashboard/package.json)
- Rust server + agent (Cargo.toml workspace)
- Protocol buffers (proto/ directory)
- CLAUDE.md with project documentation
- File counts: ~X .rs files, ~Y .tsx files

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
> - React dashboard
> - Rust relay server (Axum)
> - Rust Windows agent
> - Protocol buffer messaging
>
> Let's document what's already working, identify any gaps, and plan what should be built next..."

The resulting spec would have:
- **Existing features** marked as implemented (for reference)
- **Gaps/incomplete features** marked as pending (high priority)
- **New features** marked as pending (to be built)

# Import Existing Project Feature - Implementation Plan

## Overview

Add the ability to import an existing project folder into autocoder+, analyze its contents, and run the spec creation interview with context about what's already there.

## User Flow

```
Current "New Project" Flow:
  Name → Folder (NEW) → Method → Claude Interview → Start Agent

New "Import" Flow:
  [Import Existing] → Folder (SELECT EXISTING) → Name (default to folder name)
    → Analyze Codebase → Claude Interview (WITH CONTEXT) → Start Agent
```

## Files to Modify/Create

### Backend Changes

#### 1. `backend/app/routers/projects.py` - Add import endpoint
- Add `POST /api/projects/import` endpoint
- Accepts: `{ name: str, path: str, analyze: bool = true }`
- Validates path exists and is a directory
- Calls codebase analyzer
- Creates project in database
- Returns project + analysis results

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type
- Read README if present
- Identify frameworks (React, Express, FastAPI, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".py": 12}
    detected_stack: dict  # {frontend: "React", backend: "FastAPI", db: "SQLite"}
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Python main.py, etc.
```

#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
- Modify `start()` to prepend context to system prompt when importing
- Create import-specific preamble for Claude

#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec

### Frontend Changes

#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option
- Add initial step to choose: "Create New" vs "Import Existing"
- New state: `isImportMode: boolean`
- When import mode:
  - FolderBrowser selects existing folder (not append name)
  - Project name defaults to folder name
  - Pass `isImport: true` to API

#### 6. `ui/src/components/FolderBrowser.tsx` - Support import mode
- Add prop: `mode: 'create' | 'import'`
- In import mode:
  - Allow selection of non-empty folders
  - Show file count in folder
  - "Select This Project Folder" button text

#### 7. `ui/src/hooks/useProjects.ts` - Add import mutation
```typescript
export function useImportProject() {
  return useMutation({
    mutationFn: ({ name, path }) =>
      api.importProject(name, path),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projects'] })
    },
  })
}
```

#### 8. `ui/src/lib/api.ts` - Add import API call
```typescript
async importProject(name: string, path: string): Promise<ProjectWithAnalysis> {
  const response = await fetch(`${this.baseUrl}/api/projects/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, path }),
  })
  return response.json()
}
```

#### 9. `ui/src/components/SpecCreationChat.tsx` - Show analysis context
- Accept optional `codebaseAnalysis` prop
- Display analysis summary at start of chat
- Pass to backend via WebSocket start message

## Implementation Order

1. **Backend analyzer** - Create `codebase_analyzer.py` service
2. **Backend endpoint** - Add import endpoint to `projects.py`
3. **Import skill** - Create `import-spec.md` Claude skill
4. **Session modifications** - Update `spec_chat_session.py` for import context
5. **Frontend API** - Add `importProject` to `api.ts` and `useProjects.ts`
6. **FolderBrowser** - Add import mode support
7. **NewProjectModal** - Add Create/Import choice and import flow
8. **SpecCreationChat** - Display analysis context

## Key Design Decisions

### 1. Separate Import Skill vs. Modified Create Skill
**Decision**: Create separate `import-spec.md` skill
**Reason**: Cleaner separation, different conversation flow, easier to maintain

### 2. Analysis Depth
**Decision**: Lightweight analysis (file types, package files, README)
**Reason**: Don't want to read all source code (too slow, context limits). Let Claude ask about specifics.

### 3. Project Name Handling
**Decision**: Default to folder name, allow user to change
**Reason**: Existing folders have meaningful names, but user should be able to override

### 4. Import vs Create Backend
**Decision**: Separate `/api/projects/import` endpoint
**Reason**: Different validation (folder must exist), includes analysis step

## Testing Plan

1. **Unit test** `codebase_analyzer.py` with sample project structures
2. **Integration test** import endpoint with real folder
3. **E2E test**: Import the GuruConnect folder, verify:
   - Analysis detects tech stack correctly
   - Claude interview receives context
   - Spec file is generated with existing code awareness

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (package.json with react dependency)
- Rust backend (Cargo.toml)
- SQLite database
- File counts by type

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. I can see it's a React + Rust application with approximately X files. Let me ask some questions to understand what features this application should have..."

-- React frontend (package.json with react dependency)

+- React frontend (dashboard/package.json)

+- Rust server + agent (Cargo.toml workspace)

+- File counts: ~X .rs files, ~Y .tsx files

-> "I've analyzed your existing GuruConnect project. I can see it's a React + Rust application with approximately X files. Let me ask some questions to understand what features this application should have..."

+> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:

+> Let's document what's already working, identify any gaps, and plan what should be built next..."

+- **Existing features** marked as implemented (for reference)

+- **Gaps/incomplete features** marked as pending (high priority)

+- **New features** marked as pending (to be built)


Now let me also add that the codebase analyzer should read CLAUDE.md if present.


#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type
- Read README if present
- Identify frameworks (React, Express, FastAPI, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".py": 12}
    detected_stack: dict  # {frontend: "React", backend: "FastAPI", db: "SQLite"}
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Python main.py, etc.
```

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type (.rs, .ts, .tsx, .py, etc.)
- Read CLAUDE.md if present (project documentation)
- Read README.md if present
- Identify frameworks (React, Express, FastAPI, Axum, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}
    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}
    has_claude_md: bool
    claude_md_content: str | None  # Full CLAUDE.md content for Claude context
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.
```


The file C:\Users\MikeSwanson\.claude\plans\floating-yawning-cray.md has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
    26→- Calls codebase analyzer
    27→- Creates project in database
    28→- Returns project + analysis results
    29→
    30→#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
    31→- Scan directory for file structure
    32→- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
    33→- Count files by type (.rs, .ts, .tsx, .py, etc.)
    34→- Read CLAUDE.md if present (project documentation)
    35→- Read README.md if present
    36→- Identify frameworks (React, Express, FastAPI, Axum, etc.)
    37→- Return structured analysis
    38→
    39→```python
    40→class CodebaseAnalysis:
    41→    total_files: int
    42→    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}
    43→    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}
    44→    has_claude_md: bool
    45→    claude_md_content: str | None  # Full CLAUDE.md content for Claude context
    46→    has_readme: bool
    47→    readme_summary: str | None
    48→    directories: list[str]  # top-level dirs
    49→    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.
    50→```
    51→
    52→#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
    53→- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
    54→- Modify `start()` to prepend context to system prompt when importing

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type (.rs, .ts, .tsx, .py, etc.)
- Read CLAUDE.md if present (project documentation)
- Read README.md if present
- Identify frameworks (React, Express, FastAPI, Axum, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}
    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}
    has_claude_md: bool
    claude_md_content: str | None  # Full CLAUDE.md content for Claude context
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.
```

# Import Existing Project Feature - Implementation Plan

## Overview

Add the ability to import an existing project folder into autocoder+, analyze its contents, and run the spec creation interview with context about what's already there.

## User Flow

```
Current "New Project" Flow:
  Name → Folder (NEW) → Method → Claude Interview → Start Agent

New "Import" Flow:
  [Import Existing] → Folder (SELECT EXISTING) → Name (default to folder name)
    → Analyze Codebase → Claude Interview (WITH CONTEXT) → Start Agent
```

## Files to Modify/Create

### Backend Changes

#### 1. `backend/app/routers/projects.py` - Add import endpoint
- Add `POST /api/projects/import` endpoint
- Accepts: `{ name: str, path: str, analyze: bool = true }`
- Validates path exists and is a directory
- Calls codebase analyzer
- Creates project in database
- Returns project + analysis results

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type
- Read README if present
- Identify frameworks (React, Express, FastAPI, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".py": 12}
    detected_stack: dict  # {frontend: "React", backend: "FastAPI", db: "SQLite"}
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Python main.py, etc.
```

#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
- Modify `start()` to prepend context to system prompt when importing
- Create import-specific preamble for Claude

#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec

### Frontend Changes

#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option
- Add initial step to choose: "Create New" vs "Import Existing"
- New state: `isImportMode: boolean`
- When import mode:
  - FolderBrowser selects existing folder (not append name)
  - Project name defaults to folder name
  - Pass `isImport: true` to API

#### 6. `ui/src/components/FolderBrowser.tsx` - Support import mode
- Add prop: `mode: 'create' | 'import'`
- In import mode:
  - Allow selection of non-empty folders
  - Show file count in folder
  - "Select This Project Folder" button text

#### 7. `ui/src/hooks/useProjects.ts` - Add import mutation
```typescript
export function useImportProject() {
  return useMutation({
    mutationFn: ({ name, path }) =>
      api.importProject(name, path),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projects'] })
    },
  })
}
```

#### 8. `ui/src/lib/api.ts` - Add import API call
```typescript
async importProject(name: string, path: string): Promise<ProjectWithAnalysis> {
  const response = await fetch(`${this.baseUrl}/api/projects/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, path }),
  })
  return response.json()
}
```

#### 9. `ui/src/components/SpecCreationChat.tsx` - Show analysis context
- Accept optional `codebaseAnalysis` prop
- Display analysis summary at start of chat
- Pass to backend via WebSocket start message

## Implementation Order

1. **Backend analyzer** - Create `codebase_analyzer.py` service
2. **Backend endpoint** - Add import endpoint to `projects.py`
3. **Import skill** - Create `import-spec.md` Claude skill
4. **Session modifications** - Update `spec_chat_session.py` for import context
5. **Frontend API** - Add `importProject` to `api.ts` and `useProjects.ts`
6. **FolderBrowser** - Add import mode support
7. **NewProjectModal** - Add Create/Import choice and import flow
8. **SpecCreationChat** - Display analysis context

## Key Design Decisions

### 1. Separate Import Skill vs. Modified Create Skill
**Decision**: Create separate `import-spec.md` skill
**Reason**: Cleaner separation, different conversation flow, easier to maintain

### 2. Analysis Depth
**Decision**: Lightweight analysis (file types, package files, README)
**Reason**: Don't want to read all source code (too slow, context limits). Let Claude ask about specifics.

### 3. Project Name Handling
**Decision**: Default to folder name, allow user to change
**Reason**: Existing folders have meaningful names, but user should be able to override

### 4. Import vs Create Backend
**Decision**: Separate `/api/projects/import` endpoint
**Reason**: Different validation (folder must exist), includes analysis step

## Testing Plan

1. **Unit test** `codebase_analyzer.py` with sample project structures
2. **Integration test** import endpoint with real folder
3. **E2E test**: Import the GuruConnect folder, verify:
   - Analysis detects tech stack correctly
   - Claude interview receives context
   - Spec file is generated with existing code awareness

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (dashboard/package.json)
- Rust server + agent (Cargo.toml workspace)
- Protocol buffers (proto/ directory)
- CLAUDE.md with project documentation
- File counts: ~X .rs files, ~Y .tsx files

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
> - React dashboard
> - Rust relay server (Axum)
> - Rust Windows agent
> - Protocol buffer messaging
>
> Let's document what's already working, identify any gaps, and plan what should be built next..."

The resulting spec would have:
- **Existing features** marked as implemented (for reference)
- **Gaps/incomplete features** marked as pending (high priority)
- **New features** marked as pending (to be built)

-- Identify frameworks (React, Express, FastAPI, etc.)

+- Count files by type (.rs, .ts, .tsx, .py, etc.)

+- Read CLAUDE.md if present (project documentation)

+- Identify frameworks (React, Express, FastAPI, Axum, etc.)

-    file_types: dict[str, int]  # e.g., {".ts": 45, ".py": 12}

-    detected_stack: dict  # {frontend: "React", backend: "FastAPI", db: "SQLite"}

+    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}

+    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}

+    claude_md_content: str | None  # Full CLAUDE.md content for Claude context

directories: list[str]  # top-level dirs

-    entry_points: list[str]  # package.json main, Python main.py, etc.

+    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.


The plan is now complete. Let me exit plan mode and present it to the user for approval.


The plan is complete. Let me present it for your approval.


ExitPlanMode

# Import Existing Project Feature - Implementation Plan

## Overview

Add the ability to import an existing project folder into autocoder+, analyze its contents, and run the spec creation interview with context about what's already there.

## User Flow

```
Current "New Project" Flow:
  Name → Folder (NEW) → Method → Claude Interview → Start Agent

New "Import" Flow:
  [Import Existing] → Folder (SELECT EXISTING) → Name (default to folder name)
    → Analyze Codebase → Claude Interview (WITH CONTEXT) → Start Agent
```

## Files to Modify/Create

### Backend Changes

#### 1. `backend/app/routers/projects.py` - Add import endpoint
- Add `POST /api/projects/import` endpoint
- Accepts: `{ name: str, path: str, analyze: bool = true }`
- Validates path exists and is a directory
- Calls codebase analyzer
- Creates project in database
- Returns project + analysis results

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type (.rs, .ts, .tsx, .py, etc.)
- Read CLAUDE.md if present (project documentation)
- Read README.md if present
- Identify frameworks (React, Express, FastAPI, Axum, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}
    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}
    has_claude_md: bool
    claude_md_content: str | None  # Full CLAUDE.md content for Claude context
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.
```

#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
- Modify `start()` to prepend context to system prompt when importing
- Create import-specific preamble for Claude

#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec

### Frontend Changes

#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option
- Add initial step to choose: "Create New" vs "Import Existing"
- New state: `isImportMode: boolean`
- When import mode:
  - FolderBrowser selects existing folder (not append name)
  - Project name defaults to folder name
  - Pass `isImport: true` to API

#### 6. `ui/src/components/FolderBrowser.tsx` - Support import mode
- Add prop: `mode: 'create' | 'import'`
- In import mode:
  - Allow selection of non-empty folders
  - Show file count in folder
  - "Select This Project Folder" button text

#### 7. `ui/src/hooks/useProjects.ts` - Add import mutation
```typescript
export function useImportProject() {
  return useMutation({
    mutationFn: ({ name, path }) =>
      api.importProject(name, path),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projects'] })
    },
  })
}
```

#### 8. `ui/src/lib/api.ts` - Add import API call
```typescript
async importProject(name: string, path: string): Promise<ProjectWithAnalysis> {
  const response = await fetch(`${this.baseUrl}/api/projects/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, path }),
  })
  return response.json()
}
```

#### 9. `ui/src/components/SpecCreationChat.tsx` - Show analysis context
- Accept optional `codebaseAnalysis` prop
- Display analysis summary at start of chat
- Pass to backend via WebSocket start message

## Implementation Order

1. **Backend analyzer** - Create `codebase_analyzer.py` service
2. **Backend endpoint** - Add import endpoint to `projects.py`
3. **Import skill** - Create `import-spec.md` Claude skill
4. **Session modifications** - Update `spec_chat_session.py` for import context
5. **Frontend API** - Add `importProject` to `api.ts` and `useProjects.ts`
6. **FolderBrowser** - Add import mode support
7. **NewProjectModal** - Add Create/Import choice and import flow
8. **SpecCreationChat** - Display analysis context

## Key Design Decisions

### 1. Separate Import Skill vs. Modified Create Skill
**Decision**: Create separate `import-spec.md` skill
**Reason**: Cleaner separation, different conversation flow, easier to maintain

### 2. Analysis Depth
**Decision**: Lightweight analysis (file types, package files, README)
**Reason**: Don't want to read all source code (too slow, context limits). Let Claude ask about specifics.

### 3. Project Name Handling
**Decision**: Default to folder name, allow user to change
**Reason**: Existing folders have meaningful names, but user should be able to override

### 4. Import vs Create Backend
**Decision**: Separate `/api/projects/import` endpoint
**Reason**: Different validation (folder must exist), includes analysis step

## Testing Plan

1. **Unit test** `codebase_analyzer.py` with sample project structures
2. **Integration test** import endpoint with real folder
3. **E2E test**: Import the GuruConnect folder, verify:
   - Analysis detects tech stack correctly
   - Claude interview receives context
   - Spec file is generated with existing code awareness

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (dashboard/package.json)
- Rust server + agent (Cargo.toml workspace)
- Protocol buffers (proto/ directory)
- CLAUDE.md with project documentation
- File counts: ~X .rs files, ~Y .tsx files

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
> - React dashboard
> - Rust relay server (Axum)
> - Rust Windows agent
> - Protocol buffer messaging
>
> Let's document what's already working, identify any gaps, and plan what should be built next..."

The resulting spec would have:
- **Existing features** marked as implemented (for reference)
- **Gaps/incomplete features** marked as pending (high priority)
- **New features** marked as pending (to be built)


User has approved your plan. You can now start coding. Start with updating your todo list if applicable

Your plan has been saved to: C:\Users\MikeSwanson\.claude\plans\floating-yawning-cray.md
You can refer back to it if needed during implementation.

## Approved Plan:
# Import Existing Project Feature - Implementation Plan

## Overview

Add the ability to import an existing project folder into autocoder+, analyze its contents, and run the spec creation interview with context about what's already there.

## User Flow

```
Current "New Project" Flow:
  Name → Folder (NEW) → Method → Claude Interview → Start Agent

New "Import" Flow:
  [Import Existing] → Folder (SELECT EXISTING) → Name (default to folder name)
    → Analyze Codebase → Claude Interview (WITH CONTEXT) → Start Agent
```

## Files to Modify/Create

### Backend Changes

#### 1. `backend/app/routers/projects.py` - Add import endpoint
- Add `POST /api/projects/import` endpoint
- Accepts: `{ name: str, path: str, analyze: bool = true }`
- Validates path exists and is a directory
- Calls codebase analyzer
- Creates project in database
- Returns project + analysis results

#### 2. NEW: `backend/app/services/codebase_analyzer.py` - Analyze existing code
- Scan directory for file structure
- Detect tech stack (package.json, requirements.txt, Cargo.toml, etc.)
- Count files by type (.rs, .ts, .tsx, .py, etc.)
- Read CLAUDE.md if present (project documentation)
- Read README.md if present
- Identify frameworks (React, Express, FastAPI, Axum, etc.)
- Return structured analysis

```python
class CodebaseAnalysis:
    total_files: int
    file_types: dict[str, int]  # e.g., {".ts": 45, ".rs": 30}
    detected_stack: dict  # {frontend: "React", backend: "Rust/Axum", db: "SQLite"}
    has_claude_md: bool
    claude_md_content: str | None  # Full CLAUDE.md content for Claude context
    has_readme: bool
    readme_summary: str | None
    directories: list[str]  # top-level dirs
    entry_points: list[str]  # package.json main, Cargo.toml bins, etc.
```

#### 3. `autocoder-master/server/services/spec_chat_session.py` - Accept import context
- Modify `create_session()` to accept optional `codebase_context: CodebaseAnalysis`
- Modify `start()` to prepend context to system prompt when importing
- Create import-specific preamble for Claude

#### 4. NEW: `autocoder-master/.claude/commands/import-spec.md` - Import-specific skill
- Similar to `create-spec.md` but with import context
- **Hybrid approach**: Document existing + plan future
- Phases adjusted for existing codebase:
  - Phase 1: Present analysis (detected stack, file structure, CLAUDE.md summary)
  - Phase 2: User confirms/corrects what project does today
  - Phase 3: Document EXISTING features (what's already built)
  - Phase 4: Identify GAPS (what's missing, incomplete, or broken)
  - Phase 5: Plan NEXT features (what should be added)
  - Phase 6: Derive feature list (existing as "complete", gaps/new as "pending")
  - Phase 7: Review & generate spec

### Frontend Changes

#### 5. `ui/src/components/NewProjectModal.tsx` - Add import option
- Add initial step to choose: "Create New" vs "Import Existing"
- New state: `isImportMode: boolean`
- When import mode:
  - FolderBrowser selects existing folder (not append name)
  - Project name defaults to folder name
  - Pass `isImport: true` to API

#### 6. `ui/src/components/FolderBrowser.tsx` - Support import mode
- Add prop: `mode: 'create' | 'import'`
- In import mode:
  - Allow selection of non-empty folders
  - Show file count in folder
  - "Select This Project Folder" button text

#### 7. `ui/src/hooks/useProjects.ts` - Add import mutation
```typescript
export function useImportProject() {
  return useMutation({
    mutationFn: ({ name, path }) =>
      api.importProject(name, path),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projects'] })
    },
  })
}
```

#### 8. `ui/src/lib/api.ts` - Add import API call
```typescript
async importProject(name: string, path: string): Promise<ProjectWithAnalysis> {
  const response = await fetch(`${this.baseUrl}/api/projects/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name, path }),
  })
  return response.json()
}
```

#### 9. `ui/src/components/SpecCreationChat.tsx` - Show analysis context
- Accept optional `codebaseAnalysis` prop
- Display analysis summary at start of chat
- Pass to backend via WebSocket start message

## Implementation Order

1. **Backend analyzer** - Create `codebase_analyzer.py` service
2. **Backend endpoint** - Add import endpoint to `projects.py`
3. **Import skill** - Create `import-spec.md` Claude skill
4. **Session modifications** - Update `spec_chat_session.py` for import context
5. **Frontend API** - Add `importProject` to `api.ts` and `useProjects.ts`
6. **FolderBrowser** - Add import mode support
7. **NewProjectModal** - Add Create/Import choice and import flow
8. **SpecCreationChat** - Display analysis context

## Key Design Decisions

### 1. Separate Import Skill vs. Modified Create Skill
**Decision**: Create separate `import-spec.md` skill
**Reason**: Cleaner separation, different conversation flow, easier to maintain

### 2. Analysis Depth
**Decision**: Lightweight analysis (file types, package files, README)
**Reason**: Don't want to read all source code (too slow, context limits). Let Claude ask about specifics.

### 3. Project Name Handling
**Decision**: Default to folder name, allow user to change
**Reason**: Existing folders have meaningful names, but user should be able to override

### 4. Import vs Create Backend
**Decision**: Separate `/api/projects/import` endpoint
**Reason**: Different validation (folder must exist), includes analysis step

## Testing Plan

1. **Unit test** `codebase_analyzer.py` with sample project structures
2. **Integration test** import endpoint with real folder
3. **E2E test**: Import the GuruConnect folder, verify:
   - Analysis detects tech stack correctly
   - Claude interview receives context
   - Spec file is generated with existing code awareness

## Example: GuruConnect Import

When importing GuruConnect, the analyzer should detect:
- React frontend (dashboard/package.json)
- Rust server + agent (Cargo.toml workspace)
- Protocol buffers (proto/ directory)
- CLAUDE.md with project documentation
- File counts: ~X .rs files, ~Y .tsx files

Claude's interview would start with:
> "I've analyzed your existing GuruConnect project. Based on CLAUDE.md and the codebase structure, this is a remote desktop solution with:
> - React dashboard
> - Rust relay server (Axum)
> - Rust Windows agent
> - Protocol buffer messaging
>
> Let's document what's already working, identify any gaps, and plan what should be built next..."

The resulting spec would have:
- **Existing features** marked as implemented (for reference)
- **Gaps/incomplete features** marked as pending (high priority)
- **New features** marked as pending (to be built)


The plan is approved. Now let me start implementing it. I'll create a todo list to track progress and start with the backend changes first.


Let me set up the implementation tasks and start building this feature.


TodoWrite

Create codebase_analyzer.py service

Add import endpoint to projects.py

Create import-spec.md Claude skill

Update spec_chat_session.py for import context

Add importProject to api.ts

Add useImportProject hook

Add import mode to FolderBrowser

Add Create/Import choice to NewProjectModal

Test with GuruConnect folder


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 codebase_analyzer.py service

Add import endpoint to projects.py

Create import-spec.md Claude skill

Update spec_chat_session.py for import context

Add importProject to api.ts

Add useImportProject hook

Add import mode to FolderBrowser

Add Create/Import choice to NewProjectModal

Test with GuruConnect folder


Now let me start by creating the codebase_analyzer.py service. This will scan a directory and analyze its contents.


Write

"""
Codebase Analyzer Service
=========================

Analyzes an existing project directory to extract metadata for import.
"""

import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

@dataclass
class CodebaseAnalysis:
    """Analysis results for an existing codebase."""

    total_files: int = 0
    file_types: dict[str, int] = field(default_factory=dict)
    detected_stack: dict[str, str] = field(default_factory=dict)
    has_claude_md: bool = False
    claude_md_content: Optional[str] = None
    has_readme: bool = False
    readme_content: Optional[str] = None
    directories: list[str] = field(default_factory=list)
    entry_points: list[str] = field(default_factory=list)
    project_name: Optional[str] = None

    def to_dict(self) -> dict:
        """Convert to dictionary for JSON serialization."""
        return {
            "total_files": self.total_files,
            "file_types": self.file_types,
            "detected_stack": self.detected_stack,
            "has_claude_md": self.has_claude_md,
            "claude_md_content": self.claude_md_content,
            "has_readme": self.has_readme,
            "readme_content": self.readme_content,
            "directories": self.directories,
            "entry_points": self.entry_points,
            "project_name": self.project_name,
        }

# Directories to skip during analysis
SKIP_DIRS = {
    "node_modules",
    ".git",
    "__pycache__",
    ".venv",
    "venv",
    "target",
    "dist",
    "build",
    ".next",
    ".nuxt",
    "coverage",
    ".pytest_cache",
    ".mypy_cache",
    ".tox",
    "eggs",
    "*.egg-info",
}

# File extensions to count
CODE_EXTENSIONS = {
    ".py", ".pyi",
    ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs",
    ".rs",
    ".go",
    ".java", ".kt", ".scala",
    ".c", ".cpp", ".cc", ".h", ".hpp",
    ".cs",
    ".rb",
    ".php",
    ".swift",
    ".vue", ".svelte",
    ".html", ".css", ".scss", ".sass", ".less",
    ".json", ".yaml", ".yml", ".toml",
    ".md", ".mdx",
    ".sql",
    ".sh", ".bash", ".zsh", ".fish",
    ".ps1", ".bat", ".cmd",
}

def analyze_codebase(project_path: str | Path) -> CodebaseAnalysis:
    """
    Analyze an existing project directory.

    Args:
        project_path: Path to the project root directory

    Returns:
        CodebaseAnalysis with detected metadata
    """
    path = Path(project_path)
    if not path.exists():
        raise ValueError(f"Project path does not exist: {project_path}")
    if not path.is_dir():
        raise ValueError(f"Project path is not a directory: {project_path}")

    analysis = CodebaseAnalysis()
    analysis.project_name = path.name

    # Get top-level directories
    analysis.directories = [
        d.name for d in path.iterdir()
        if d.is_dir() and not d.name.startswith(".") and d.name not in SKIP_DIRS
    ]

    # Read CLAUDE.md if present
    claude_md = path / "CLAUDE.md"
    if claude_md.exists():
        analysis.has_claude_md = True
        try:
            analysis.claude_md_content = claude_md.read_text(encoding="utf-8")
        except Exception:
            analysis.claude_md_content = None

    # Read README.md if present
    for readme_name in ["README.md", "README", "readme.md", "Readme.md"]:
        readme = path / readme_name
        if readme.exists():
            analysis.has_readme = True
            try:
                content = readme.read_text(encoding="utf-8")
                # Truncate to first 2000 chars for summary
                analysis.readme_content = content[:2000] if len(content) > 2000 else content
            except Exception:
                analysis.readme_content = None
            break

    # Count files by type
    file_counts: dict[str, int] = {}
    total_files = 0

    for root, dirs, files in os.walk(path):
        # Skip certain directories
        dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]

        for filename in files:
            ext = Path(filename).suffix.lower()
            if ext in CODE_EXTENSIONS:
                file_counts[ext] = file_counts.get(ext, 0) + 1
                total_files += 1

    analysis.file_types = dict(sorted(file_counts.items(), key=lambda x: -x[1]))
    analysis.total_files = total_files

    # Detect tech stack
    analysis.detected_stack = _detect_tech_stack(path)

    # Find entry points
    analysis.entry_points = _find_entry_points(path)

    return analysis

def _detect_tech_stack(path: Path) -> dict[str, str]:
    """Detect the technology stack from config files."""
    stack: dict[str, str] = {}

    # Check for Cargo.toml (Rust)
    cargo_toml = path / "Cargo.toml"
    if cargo_toml.exists():
        try:
            content = cargo_toml.read_text(encoding="utf-8")
            if "[workspace]" in content:
                stack["backend"] = "Rust (workspace)"
            else:
                stack["backend"] = "Rust"

            # Check for common Rust web frameworks
            if "axum" in content.lower():
                stack["backend"] = "Rust/Axum"
            elif "actix" in content.lower():
                stack["backend"] = "Rust/Actix"
            elif "rocket" in content.lower():
                stack["backend"] = "Rust/Rocket"
        except Exception:
            stack["backend"] = "Rust"

    # Check for package.json (Node.js/JavaScript)
    package_json = path / "package.json"
    if not package_json.exists():
        # Check common frontend subdirectories
        for subdir in ["frontend", "client", "web", "app", "dashboard", "ui"]:
            sub_package = path / subdir / "package.json"
            if sub_package.exists():
                package_json = sub_package
                break

    if package_json.exists():
        try:
            data = json.loads(package_json.read_text(encoding="utf-8"))
            deps = {**data.get("dependencies", {}), **data.get("devDependencies", {})}

            # Detect frontend framework
            if "react" in deps:
                if "next" in deps:
                    stack["frontend"] = "Next.js"
                elif "vite" in deps:
                    stack["frontend"] = "React/Vite"
                else:
                    stack["frontend"] = "React"
            elif "vue" in deps:
                if "nuxt" in deps:
                    stack["frontend"] = "Nuxt.js"
                else:
                    stack["frontend"] = "Vue"
            elif "svelte" in deps:
                stack["frontend"] = "Svelte"
            elif "@angular/core" in deps:
                stack["frontend"] = "Angular"

            # Detect styling
            if "tailwindcss" in deps:
                stack["styling"] = "Tailwind CSS"
            elif "styled-components" in deps:
                stack["styling"] = "Styled Components"
            elif "@emotion/react" in deps:
                stack["styling"] = "Emotion"
            elif "sass" in deps or "node-sass" in deps:
                stack["styling"] = "Sass/SCSS"

            # Detect Node.js backend (if not already detected)
            if "backend" not in stack:
                if "express" in deps:
                    stack["backend"] = "Express.js"
                elif "fastify" in deps:
                    stack["backend"] = "Fastify"
                elif "koa" in deps:
                    stack["backend"] = "Koa"
                elif "nestjs" in deps or "@nestjs/core" in deps:
                    stack["backend"] = "NestJS"
        except Exception:
            pass

    # Check for requirements.txt or pyproject.toml (Python)
    requirements = path / "requirements.txt"
    pyproject = path / "pyproject.toml"

    if requirements.exists():
        try:
            content = requirements.read_text(encoding="utf-8").lower()
            if "fastapi" in content:
                stack["backend"] = "FastAPI"
            elif "django" in content:
                stack["backend"] = "Django"
            elif "flask" in content:
                stack["backend"] = "Flask"
        except Exception:
            pass

    if pyproject.exists():
        try:
            content = pyproject.read_text(encoding="utf-8").lower()
            if "fastapi" in content:
                stack["backend"] = "FastAPI"
            elif "django" in content:
                stack["backend"] = "Django"
            elif "flask" in content:
                stack["backend"] = "Flask"
        except Exception:
            pass

    # Check for Go
    go_mod = path / "go.mod"
    if go_mod.exists():
        stack["backend"] = "Go"
        try:
            content = go_mod.read_text(encoding="utf-8").lower()
            if "gin-gonic" in content:
                stack["backend"] = "Go/Gin"
            elif "fiber" in content:
                stack["backend"] = "Go/Fiber"
            elif "echo" in content:
                stack["backend"] = "Go/Echo"
        except Exception:
            pass

    # Check for database
    for db_file in ["prisma/schema.prisma", "drizzle.config.ts", "knexfile.js"]:
        if (path / db_file).exists():
            if "prisma" in db_file:
                stack["orm"] = "Prisma"
            elif "drizzle" in db_file:
                stack["orm"] = "Drizzle"
            elif "knex" in db_file:
                stack["orm"] = "Knex"
            break

    # Check for SQLite
    for db_file in path.glob("*.db"):
        stack["database"] = "SQLite"
        break
    for db_file in path.glob("*.sqlite"):
        stack["database"] = "SQLite"
        break

    # Check for Docker
    if (path / "Dockerfile").exists() or (path / "docker-compose.yml").exists():
        stack["deployment"] = "Docker"

    # Check for proto files
    if (path / "proto").exists() or list(path.glob("**/*.proto")):
        stack["messaging"] = "Protocol Buffers"

    return stack

def _find_entry_points(path: Path) -> list[str]:
    """Find likely entry point files."""
    entry_points = []

    # Check package.json for main/scripts
    package_json = path / "package.json"
    if package_json.exists():
        try:
            data = json.loads(package_json.read_text(encoding="utf-8"))
            if "main" in data:
                entry_points.append(f"package.json main: {data['main']}")
            if "scripts" in data:
                if "start" in data["scripts"]:
                    entry_points.append(f"npm start: {data['scripts']['start'][:50]}")
                if "dev" in data["scripts"]:
                    entry_points.append(f"npm dev: {data['scripts']['dev'][:50]}")
        except Exception:
            pass

    # Check Cargo.toml for bins
    cargo_toml = path / "Cargo.toml"
    if cargo_toml.exists():
        entry_points.append("cargo run (Rust)")

    # Check for common Python entry points
    for py_main in ["main.py", "app.py", "run.py", "server.py", "manage.py"]:
        if (path / py_main).exists():
            entry_points.append(f"python {py_main}")
            break

    # Check for start scripts
    for script in ["start.sh", "start.bat", "run.sh", "run.bat"]:
        if (path / script).exists():
            entry_points.append(script)

    return entry_points

def format_analysis_for_claude(analysis: CodebaseAnalysis) -> str:
    """
    Format analysis results as context for Claude's system prompt.

    Returns a markdown-formatted summary suitable for prepending to the import skill.
    """
    lines = [
        "# EXISTING PROJECT ANALYSIS",
        "",
        f"**Project Directory:** {analysis.project_name}",
        "",
    ]

    if analysis.detected_stack:
        lines.append("## Detected Technology Stack")
        for category, tech in analysis.detected_stack.items():
            lines.append(f"- **{category.title()}:** {tech}")
        lines.append("")

    if analysis.directories:
        lines.append("## Directory Structure")
        lines.append("Top-level directories:")
        for dir_name in analysis.directories[:10]:  # Limit to 10
            lines.append(f"- `{dir_name}/`")
        if len(analysis.directories) > 10:
            lines.append(f"- ... and {len(analysis.directories) - 10} more")
        lines.append("")

    if analysis.file_types:
        lines.append("## File Statistics")
        lines.append(f"Total code files: {analysis.total_files}")
        lines.append("")
        lines.append("Files by type:")
        for ext, count in list(analysis.file_types.items())[:8]:
            lines.append(f"- `{ext}`: {count} files")
        lines.append("")

    if analysis.entry_points:
        lines.append("## Entry Points")
        for ep in analysis.entry_points[:5]:
            lines.append(f"- {ep}")
        lines.append("")

    if analysis.claude_md_content:
        lines.append("## Project Documentation (from CLAUDE.md)")
        lines.append("")
        # Include full CLAUDE.md content for context
        lines.append(analysis.claude_md_content)
        lines.append("")
    elif analysis.readme_content:
        lines.append("## Project Documentation (from README.md)")
        lines.append("")
        lines.append(analysis.readme_content)
        lines.append("")

    lines.append("---")
    lines.append("")

    return "\n".join(lines)


File created successfully at: C:\Users\MikeSwanson\claude-projects\Autocode-remix\Autocode-fork\backend\app\services\codebase_analyzer.py

"""
Codebase Analyzer Service
=========================

Analyzes an existing project directory to extract metadata for import.
"""

import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

@dataclass
class CodebaseAnalysis:
    """Analysis results for an existing codebase."""

    total_files: int = 0
    file_types: dict[str, int] = field(default_factory=dict)
    detected_stack: dict[str, str] = field(default_factory=dict)
    has_claude_md: bool = False
    claude_md_content: Optional[str] = None
    has_readme: bool = False
    readme_content: Optional[str] = None
    directories: list[str] = field(default_factory=list)
    entry_points: list[str] = field(default_factory=list)
    project_name: Optional[str] = None

    def to_dict(self) -> dict:
        """Convert to dictionary for JSON serialization."""
        return {
            "total_files": self.total_files,
            "file_types": self.file_types,
            "detected_stack": self.detected_stack,
            "has_claude_md": self.has_claude_md,
            "claude_md_content": self.claude_md_content,
            "has_readme": self.has_readme,
            "readme_content": self.readme_content,
            "directories": self.directories,
            "entry_points": self.entry_points,
            "project_name": self.project_name,
        }

# Directories to skip during analysis
SKIP_DIRS = {
    "node_modules",
    ".git",
    "__pycache__",
    ".venv",
    "venv",
    "target",
    "dist",
    "build",
    ".next",
    ".nuxt",
    "coverage",
    ".pytest_cache",
    ".mypy_cache",
    ".tox",
    "eggs",
    "*.egg-info",
}

# File extensions to count
CODE_EXTENSIONS = {
    ".py", ".pyi",
    ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs",
    ".rs",
    ".go",
    ".java", ".kt", ".scala",
    ".c", ".cpp", ".cc", ".h", ".hpp",
    ".cs",
    ".rb",
    ".php",
    ".swift",
    ".vue", ".svelte",
    ".html", ".css", ".scss", ".sass", ".less",
    ".json", ".yaml", ".yml", ".toml",
    ".md", ".mdx",
    ".sql",
    ".sh", ".bash", ".zsh", ".fish",
    ".ps1", ".bat", ".cmd",
}

def analyze_codebase(project_path: str | Path) -> CodebaseAnalysis:
    """
    Analyze an existing project directory.

    Args:
        project_path: Path to the project root directory

    Returns:
        CodebaseAnalysis with detected metadata
    """
    path = Path(project_path)
    if not path.exists():
        raise ValueError(f"Project path does not exist: {project_path}")
    if not path.is_dir():
        raise ValueError(f"Project path is not a directory: {project_path}")

    analysis = CodebaseAnalysis()
    analysis.project_name = path.name

    # Get top-level directories
    analysis.directories = [
        d.name for d in path.iterdir()
        if d.is_dir() and not d.name.startswith(".") and d.name not in SKIP_DIRS
    ]

    # Read CLAUDE.md if present
    claude_md = path / "CLAUDE.md"
    if claude_md.exists():
        analysis.has_claude_md = True
        try:
            analysis.claude_md_content = claude_md.read_text(encoding="utf-8")
        except Exception:
            analysis.claude_md_content = None

    # Read README.md if present
    for readme_name in ["README.md", "README", "readme.md", "Readme.md"]:
        readme = path / readme_name
        if readme.exists():
            analysis.has_readme = True
            try:
                content = readme.read_text(encoding="utf-8")
                # Truncate to first 2000 chars for summary
                analysis.readme_content = content[:2000] if len(content) > 2000 else content
            except Exception:
                analysis.readme_content = None
            break

    # Count files by type
    file_counts: dict[str, int] = {}
    total_files = 0

    for root, dirs, files in os.walk(path):
        # Skip certain directories
        dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]

        for filename in files:
            ext = Path(filename).suffix.lower()
            if ext in CODE_EXTENSIONS:
                file_counts[ext] = file_counts.get(ext, 0) + 1
                total_files += 1

    analysis.file_types = dict(sorted(file_counts.items(), key=lambda x: -x[1]))
    analysis.total_files = total_files

    # Detect tech stack
    analysis.detected_stack = _detect_tech_stack(path)

    # Find entry points
    analysis.entry_points = _find_entry_points(path)

    return analysis

def _detect_tech_stack(path: Path) -> dict[str, str]:
    """Detect the technology stack from config files."""
    stack: dict[str, str] = {}

    # Check for Cargo.toml (Rust)
    cargo_toml = path / "Cargo.toml"
    if cargo_toml.exists():
        try:
            content = cargo_toml.read_text(encoding="utf-8")
            if "[workspace]" in content:
                stack["backend"] = "Rust (workspace)"
            else:
                stack["backend"] = "Rust"

            # Check for common Rust web frameworks
            if "axum" in content.lower():
                stack["backend"] = "Rust/Axum"
            elif "actix" in content.lower():
                stack["backend"] = "Rust/Actix"
            elif "rocket" in content.lower():
                stack["backend"] = "Rust/Rocket"
        except Exception:
            stack["backend"] = "Rust"

    # Check for package.json (Node.js/JavaScript)
    package_json = path / "package.json"
    if not package_json.exists():
        # Check common frontend subdirectories
        for subdir in ["frontend", "client", "web", "app", "dashboard", "ui"]:
            sub_package = path / subdir / "package.json"
            if sub_package.exists():
                package_json = sub_package
                break

    if package_json.exists():
        try:
            data = json.loads(package_json.read_text(encoding="utf-8"))
            deps = {**data.get("dependencies", {}), **data.get("devDependencies", {})}

            # Detect frontend framework
            if "react" in deps:
                if "next" in deps:
                    stack["frontend"] = "Next.js"
                elif "vite" in deps:
                    stack["frontend"] = "React/Vite"
                else:
                    stack["frontend"] = "React"
            elif "vue" in deps:
                if "nuxt" in deps:
                    stack["frontend"] = "Nuxt.js"
                else:
                    stack["frontend"] = "Vue"
            elif "svelte" in deps:
                stack["frontend"] = "Svelte"
            elif "@angular/core" in deps:
                stack["frontend"] = "Angular"

            # Detect styling
            if "tailwindcss" in deps:
                stack["styling"] = "Tailwind CSS"
            elif "styled-components" in deps:
                stack["styling"] = "Styled Components"
            elif "@emotion/react" in deps:
                stack["styling"] = "Emotion"
            elif "sass" in deps or "node-sass" in deps:
                stack["styling"] = "Sass/SCSS"

            # Detect Node.js backend (if not already detected)
            if "backend" not in stack:
                if "express" in deps:
                    stack["backend"] = "Express.js"
                elif "fastify" in deps:
                    stack["backend"] = "Fastify"
                elif "koa" in deps:
                    stack["backend"] = "Koa"
                elif "nestjs" in deps or "@nestjs/core" in deps:
                    stack["backend"] = "NestJS"
        except Exception:
            pass

    # Check for requirements.txt or pyproject.toml (Python)
    requirements = path / "requirements.txt"
    pyproject = path / "pyproject.toml"

    if requirements.exists():
        try:
            content = requirements.read_text(encoding="utf-8").lower()
            if "fastapi" in content:
                stack["backend"] = "FastAPI"
            elif "django" in content:
                stack["backend"] = "Django"
            elif "flask" in content:
                stack["backend"] = "Flask"
        except Exception:
            pass

    if pyproject.exists():
        try:
            content = pyproject.read_text(encoding="utf-8").lower()
            if "fastapi" in content:
                stack["backend"] = "FastAPI"
            elif "django" in content:
                stack["backend"] = "Django"
            elif "flask" in content:
                stack["backend"] = "Flask"
        except Exception:
            pass

    # Check for Go
    go_mod = path / "go.mod"
    if go_mod.exists():
        stack["backend"] = "Go"
        try:
            content = go_mod.read_text(encoding="utf-8").lower()
            if "gin-gonic" in content:
                stack["backend"] = "Go/Gin"
            elif "fiber" in content:
                stack["backend"] = "Go/Fiber"
            elif "echo" in content:
                stack["backend"] = "Go/Echo"
        except Exception:
            pass

    # Check for database
    for db_file in ["prisma/schema.prisma", "drizzle.config.ts", "knexfile.js"]:
        if (path / db_file).exists():
            if "prisma" in db_file:
                stack["orm"] = "Prisma"
            elif "drizzle" in db_file:
                stack["orm"] = "Drizzle"
            elif "knex" in db_file:
                stack["orm"] = "Knex"
            break

    # Check for SQLite
    for db_file in path.glob("*.db"):
        stack["database"] = "SQLite"
        break
    for db_file in path.glob("*.sqlite"):
        stack["database"] = "SQLite"
        break

    # Check for Docker
    if (path / "Dockerfile").exists() or (path / "docker-compose.yml").exists():
        stack["deployment"] = "Docker"

    # Check for proto files
    if (path / "proto").exists() or list(path.glob("**/*.proto")):
        stack["messaging"] = "Protocol Buffers"

    return stack

def _find_entry_points(path: Path) -> list[str]:
    """Find likely entry point files."""
    entry_points = []

    # Check package.json for main/scripts
    package_json = path / "package.json"
    if package_json.exists():
        try:
            data = json.loads(package_json.read_text(encoding="utf-8"))
            if "main" in data:
                entry_points.append(f"package.json main: {data['main']}")
            if "scripts" in data:
                if "start" in data["scripts"]:
                    entry_points.append(f"npm start: {data['scripts']['start'][:50]}")
                if "dev" in data["scripts"]:
                    entry_points.append(f"npm dev: {data['scripts']['dev'][:50]}")
        except Exception:
            pass

    # Check Cargo.toml for bins
    cargo_toml = path / "Cargo.toml"
    if cargo_toml.exists():
        entry_points.append("cargo run (Rust)")

    # Check for common Python entry points
    for py_main in ["main.py", "app.py", "run.py", "server.py", "manage.py"]:
        if (path / py_main).exists():
            entry_points.append(f"python {py_main}")
            break

    # Check for start scripts
    for script in ["start.sh", "start.bat", "run.sh", "run.bat"]:
        if (path / script).exists():
            entry_points.append(script)

    return entry_points

def format_analysis_for_claude(analysis: CodebaseAnalysis) -> str:
    """
    Format analysis results as context for Claude's system prompt.

    Returns a markdown-formatted summary suitable for prepending to the import skill.
    """
    lines = [
        "# EXISTING PROJECT ANALYSIS",
        "",
        f"**Project Directory:** {analysis.project_name}",
        "",
    ]

    if analysis.detected_stack:
        lines.append("## Detected Technology Stack")
        for category, tech in analysis.detected_stack.items():
            lines.append(f"- **{category.title()}:** {tech}")
        lines.append("")

    if analysis.directories:
        lines.append("## Directory Structure")
        lines.append("Top-level directories:")
        for dir_name in analysis.directories[:10]:  # Limit to 10
            lines.append(f"- `{dir_name}/`")
        if len(analysis.directories) > 10:
            lines.append(f"- ... and {len(analysis.directories) - 10} more")
        lines.append("")

    if analysis.file_types:
        lines.append("## File Statistics")
        lines.append(f"Total code files: {analysis.total_files}")
        lines.append("")
        lines.append("Files by type:")
        for ext, count in list(analysis.file_types.items())[:8]:
            lines.append(f"- `{ext}`: {count} files")
        lines.append("")

    if analysis.entry_points:
        lines.append("## Entry Points")
        for ep in analysis.entry_points[:5]:
            lines.append(f"- {ep}")
        lines.append("")

    if analysis.claude_md_content:
        lines.append("## Project Documentation (from CLAUDE.md)")
        lines.append("")
        # Include full CLAUDE.md content for context
        lines.append(analysis.claude_md_content)
        lines.append("")
    elif analysis.readme_content:
        lines.append("## Project Documentation (from README.md)")
        lines.append("")
        lines.append(analysis.readme_content)
        lines.append("")

    lines.append("---")
    lines.append("")

    return "\n".join(lines)


Now I need to create the __init__.py for the services directory if it doesn't exist, then move on to creating the import endpoint.


Bash

ls -la /c/Users/MikeSwanson/claude-projects/Autocode-remix/Autocode-fork/backend/app/services/ 2>/dev/null || echo "directory does not exist"

Check if services directory exists


total 20
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  9 10:24 ./
drwxr-xr-x 1 AzureAD+MikeSwanson 4096     0 Jan  9 10:24 ../
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 13274 Jan  9 10:24 codebase_analyzer.py


Need to create an __init__.py in the services directory.


Write

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

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

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


File created successfully at: C:\Users\MikeSwanson\claude-projects\Autocode-remix\Autocode-fork\backend\app\services\__init__.py

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

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

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


Now let me update the todo list and add the import endpoint to projects.py.


TodoWrite

Create codebase_analyzer.py service

Add import endpoint to projects.py

Create import-spec.md Claude skill

Update spec_chat_session.py for import context

Add importProject to api.ts

Add useImportProject hook

Add import mode to FolderBrowser

Add Create/Import choice to NewProjectModal

Test with GuruConnect folder


Create codebase_analyzer.py service

Add import endpoint to projects.py

Create import-spec.md Claude skill

Add importProject to api.ts

Add useImportProject hook

Add import mode to FolderBrowser

Test with GuruConnect folder

Create codebase_analyzer.py service

Add import endpoint to projects.py

Create import-spec.md Claude skill

Add importProject to api.ts

Add useImportProject hook

Add import mode to FolderBrowser

Test with GuruConnect folder


Now I need to read the current projects.py and add the import endpoint.