> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate Fast Spec

> Complete documentation for the Fast Spec endpoint. Generate comprehensive project specifications in 30-40 seconds.

# POST /fast-spec

Generate a quick, comprehensive project specification.

## Overview

* **Cost:** Variable (typically \~5-10 credits based on complexity)
* **Use Cases:** MVPs, prototypes, rapid iteration
* **Processing Time:** \~30-40 seconds (sync) or instant return (async)
* **Output:** Complete feature breakdown, architecture, milestones

## Endpoint

```
POST https://api.pre.dev/fast-spec
```

## Headers

**For JSON requests:**

```
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
```

**For file upload requests:**

```
Content-Type: multipart/form-data
Authorization: Bearer YOUR_API_KEY
```

## Request Body

### Parameters

**For JSON requests:**

| Parameter        | Type      | Required | Description                                                                                                                                                                              |
| ---------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input`          | string    | ✅        | Description of what you want to build                                                                                                                                                    |
| `currentContext` | string    | ❌        | **CRITICAL:** Existing project/codebase context. When provided, generates feature addition spec. When omitted, generates full new project spec with setup, deployment, docs, maintenance |
| `docURLs`        | string\[] | ❌        | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs           |
| `async`          | boolean   | ❌        | `false` (default) - wait for completion, or `true` - return immediately with requestId for status polling                                                                                |

**For file upload requests (multipart/form-data):**

| Parameter | Type      | Required | Description                                                                                                                                                                    |
| --------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `file`    | File      | ❌        | **Optional:** File to be parsed as input (e.g., existing code, documentation, requirements). Can be used alone or combined with `input` text                                   |
| `input`   | string    | ❌        | **Optional:** Additional text description when using file upload. Can be empty string if using only file                                                                       |
| `docURLs` | string\[] | ❌        | **Optional:** Array of documentation URLs that Architect will reference when generating specifications. Useful for API documentation, design systems, or existing project docs |
| `async`   | boolean   | ❌        | `false` (default) - wait for completion, or `true` - return immediately with requestId for status polling                                                                      |

### Understanding `currentContext`

**Omit `currentContext` (New Project):**

```json theme={null}
{
  "input": "Build a task management SaaS"
}
```

**Generates:** Complete new project including:

* Initial setup and scaffolding
* Deployment configuration
* Documentation structure
* Support and maintenance guidelines
* Infrastructure setup
* CI/CD pipelines
* Monitoring and logging

**Provide `currentContext` (Feature Addition):**

```json theme={null}
{
  "input": "Add real-time notifications and activity feed",
  "currentContext": "Existing Next.js task management app with Supabase, has auth, task CRUD, team features"
}
```

**Generates:** Incremental feature spec including:

* New features only (respects existing architecture)
* Integration points with current codebase
* Migration considerations
* No redundant setup/deployment (already exists)

### Example: New Project

```json theme={null}
{
  "input": "Build a SaaS project management tool with team collaboration, real-time updates, task tracking, and time logging. Include user authentication and role-based permissions.",
}
```

### Example: Feature Addition

```json theme={null}
{
  "input": "Add a calendar view and Gantt chart visualization to the existing project management tool",
  "currentContext": "We have a task management system with list and board views, user auth, and basic team features",
}
```

### Example: Async Request

```json theme={null}
{
  "input": "Build a comprehensive e-commerce platform with inventory management",
  "async": true
}
```

### Example: With Documentation URLs

```json theme={null}
{
  "input": "Build a customer support ticketing system with priority levels and file attachments",
  "docURLs": [
    "https://docs.pre.dev",
    "https://docs.stripe.com"
  ]
}
```

### Example: With File Upload

```javascript theme={null}
// Prepare file upload
const formData = new FormData();
formData.append('file', fileInput.files[0]); // fileInput is your HTML file input
formData.append('input', '');
formData.append('docURLs', JSON.stringify(["https://docs.pre.dev"]));

const response = await fetch('http://localhost:3001/fast-spec', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: formData
});
```

### Example: File Upload with Additional Context

```javascript theme={null}
// Upload a requirements document and add context
const formData = new FormData();
formData.append('file', requirementsFile); // PDF or text file with requirements
formData.append('input', 'Please focus on the authentication and user management features from the uploaded requirements document');
formData.append('docURLs', JSON.stringify(["https://docs.pre.dev/auth"]));
```

## Response

### Success Response (Sync Mode)

```json theme={null}
{
  "endpoint": "fast_spec",
  "input": "Build a SaaS project management tool with team collaboration...",
  "status": "completed",
  "success": true,
  "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6",
  "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7",
  "codingAgentSpecJson": {
    "executiveSummary": "A modern task management platform...",
    "coreFunctionalities": [
      { "name": "Task CRUD", "description": "Create, read, update, delete tasks", "priority": "High" }
    ],
    "techStack": [
      { "name": "React", "category": "Frontend" },
      { "name": "Node.js", "category": "Backend" }
    ],
    "techStackGrouped": { "Frontend": ["React", "TailwindCSS"], "Backend": ["Node.js", "Express"] },
    "milestones": [
      {
        "milestoneNumber": 1,
        "description": "Core Task Management",
        "stories": [
          {
            "id": "US-001",
            "title": "User can create a task",
            "acceptanceCriteria": ["Task form validates input", "Task saved to database"],
            "complexity": "M",
            "subTasks": [{ "id": "ST-001", "description": "Design task form UI", "complexity": "S" }]
          }
        ]
      }
    ]
  },
  "codingAgentSpecMarkdown": "# Task Management App\\n\\n## Executive Summary\\n...",
  "humanSpecJson": {
    "executiveSummary": "A modern task management platform...",
    "personas": [{ "title": "Team Lead", "description": "Manages work allocation" }],
    "techStack": [{ "name": "PostgreSQL", "category": "Database" }],
    "techStackGrouped": { "Database": ["PostgreSQL"] },
    "roles": [{ "name": "Full Stack Developer", "shortHand": "FSD" }],
    "totalHours": 120,
    "milestones": [
      {
        "milestoneNumber": 1,
        "description": "Core Task Management",
        "hours": 40,
        "stories": [
          {
            "id": "US-001",
            "title": "User can create a task",
            "hours": 8,
            "subTasks": [{ "description": "Implement task creation API", "hours": 3, "complexity": "M" }]
          }
        ]
      }
    ]
  },
  "humanSpecMarkdown": "# Task Management App\\n\\n## Executive Summary\\n...",
  "architectureInfographicUrl": "https://res.cloudinary.com/dfvg7gm6w/image/upload/v1765403270/infographics/arch_infographic_cfac141b_1765403269989_0.jpg",
  "executionTime": 38500,
  "predevUrl": "https://pre.dev/projects/abc123",
  "creditsUsed": 7,
  "zippedDocsUrls": [
    {
      "platform": "stripe.com",
      "masterZipShortUrl": "https://api.pre.dev/s/xyz789"
    },
    {
      "platform": "docs.github.com",
      "masterZipShortUrl": "https://api.pre.dev/s/abc456"
    }
  ]
}
```

| Field                        | Type    | Description                                                                                                                                                                                                                                                                                  |
| ---------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `endpoint`                   | string  | Endpoint used: `"fast_spec"` or `"deep_spec"`                                                                                                                                                                                                                                                |
| `input`                      | string  | Original input text provided                                                                                                                                                                                                                                                                 |
| `status`                     | string  | Completion status: `"completed"` when successful                                                                                                                                                                                                                                             |
| `success`                    | boolean | Whether the request succeeded                                                                                                                                                                                                                                                                |
| `humanSpecUrl`               | string  | URL where the human-readable spec is hosted (downloadable markdown)                                                                                                                                                                                                                          |
| `humanSpecMarkdown`          | string  | Full markdown SOW content (human review)                                                                                                                                                                                                                                                     |
| `humanSpecJson`              | object  | Full structured SOW JSON with hours, personas, roles                                                                                                                                                                                                                                         |
| `totalHumanHours`            | number  | Estimated total hours for a human to implement the spec                                                                                                                                                                                                                                      |
| `architectureInfographicUrl` | string  | URL to a visual architecture infographic/diagram for the specification                                                                                                                                                                                                                       |
| `codingAgentSpecUrl`         | string  | URL where the coding agent spec format is hosted (downloadable markdown)                                                                                                                                                                                                                     |
| `codingAgentSpecMarkdown`    | string  | Simplified markdown SOW for AI coding tools                                                                                                                                                                                                                                                  |
| `codingAgentSpecJson`        | object  | Simplified structured SOW JSON for AI coding tools                                                                                                                                                                                                                                           |
| `executionTime`              | number  | Processing time in milliseconds                                                                                                                                                                                                                                                              |
| `predevUrl`                  | string  | pre.dev project URL where you can view and edit the spec                                                                                                                                                                                                                                     |
| `creditsUsed`                | number  | Total credits consumed by this spec generation. Available in real-time during processing and persisted on completion. Typical values: Fast spec \~5-10, Deep spec \~10-50                                                                                                                    |
| `zippedDocsUrls`             | array   | **New:** Array of scraped documentation archives. Each object contains `platform` (hostname from the doc URL), `masterZipShortUrl` (download link to the ZIP archive), and optional `masterMarkdownShortUrl` (consolidated markdown). Empty array if no `docURLs` provided or scraping fails |

### Success Response (Async Mode)

**Immediate response when `async: true`:**

```json theme={null}
{
  "specId": "507f1f77bcf86cd799439011",
  "status": "pending"
}
```

| Field    | Type   | Description                                                        |
| -------- | ------ | ------------------------------------------------------------------ |
| `specId` | string | Unique ID to poll for status (use with `/api/spec-status/:specId`) |
| `status` | string | Initial status: `"pending"`                                        |

**Poll `/api/spec-status/:specId` to check progress.**

### Async Status Flow

1. **Pending** → Initial queue state
2. **Processing** → Actively generating spec
3. **Completed** → Success, output available
4. **Failed** → Error occurred

**Typical processing times:**

* Fast Spec: 30-40 seconds
* Deep Spec: 2-3 minutes

Poll every 10-15 seconds for best UX.

## Output Structure: Milestones → Stories

Fast Spec follows a **two-level hierarchy** optimized for rapid development:

```markdown theme={null}
### - [ ] **Milestone 1**: User authentication and profile management

- [ ] **User Registration** - (M): As a: new user, I want to: register an account with email and password, So that: I can access the platform
  - **Acceptance Criteria:**
    - [ ] User can register with valid email and password
    - [ ] Email verification sent upon registration
    - [ ] Duplicate emails handled gracefully
    - [ ] Password strength requirements enforced

- [ ] **User Login** - (S): As a: registered user, I want to: log in securely, So that: I can access my account
  - **Acceptance Criteria:**
    - [ ] User can log in with correct credentials
    - [ ] Invalid credentials rejected with clear message
    - [ ] Session persists across browser tabs
    - [ ] Password reset option available

- [ ] **User Profile** - (M): As a: registered user, I want to: manage my profile, So that: I can update my information
  - **Acceptance Criteria:**
    - [ ] User can view and edit profile details
    - [ ] Shipping addresses can be saved
    - [ ] Password can be changed with re-authentication
    - [ ] Account can be deactivated
```

**Key Characteristics:**

* ✅ High-level milestones group related features
* ✅ User stories with acceptance criteria
* ✅ Complexity estimates (XS, S, M, L, XL)
* ❌ No granular implementation subtasks

## Direct SOW Formats

Fast Spec returns the Scope of Work directly in both JSON and Markdown, and also provides URL endpoints. The JSON is typed and split for coding agents vs. human reviewers:

**Coding Agent JSON (concise, no hours/personas/roles):**

```typescript theme={null}
interface CodingAgentSpecJson {
  title?: string;
  executiveSummary: string;
  coreFunctionalities: SpecCoreFunctionality[];
  techStack: SpecTechStackItem[];
  techStackGrouped: Record<string, string[]>;
  milestones: CodingAgentMilestone[];
}

interface CodingAgentMilestone {
  milestoneNumber: number;
  description: string;
  stories: CodingAgentStory[];
}

interface CodingAgentStory {
  id?: string;
  title: string;
  description?: string;
  acceptanceCriteria?: string[];
  complexity?: string;
  subTasks: CodingAgentSubTask[];
}

interface CodingAgentSubTask {
  id?: string;
  description: string;
  complexity: string; // "S" | "M" | "L" | "XL"
}
```

**Human JSON (full detail with hours/personas/roles):**

```typescript theme={null}
interface HumanSpecJson {
  title?: string;
  executiveSummary: string;
  coreFunctionalities: SpecCoreFunctionality[];
  personas: SpecPersona[];
  techStack: SpecTechStackItem[];
  techStackGrouped: Record<string, string[]>;
  milestones: HumanSpecMilestone[];
  totalHours: number;
  roles: SpecRole[];
}

interface HumanSpecMilestone {
  milestoneNumber: number;
  description: string;
  hours: number;
  stories: HumanSpecStory[];
}

interface HumanSpecStory {
  id?: string;
  title: string;
  description?: string;
  acceptanceCriteria?: string[];
  hours: number;
  complexity?: string;
  subTasks: HumanSpecSubTask[];
}

interface HumanSpecSubTask {
  id?: string;
  description: string;
  hours: number;
  complexity: string;
  roles?: SpecRole[];
}

interface SpecPersona {
  title: string;
  description: string;
  primaryGoals?: string[];
  painPoints?: string[];
  keyTasks?: string[];
}

interface SpecRole {
  name: string;
  shortHand: string;
}

interface SpecCoreFunctionality {
  name: string;
  description: string;
  priority?: string; // "High" | "Medium" | "Low"
}

interface SpecTechStackItem {
  name: string;
  category: string;
}
```

**Recommended usage**

* Feed AI tools: `codingAgentSpecJson` or `codingAgentSpecMarkdown`
* Human-readable UI/PDF: `humanSpecMarkdown`
* Planning dashboards: `humanSpecJson.totalHours`, `humanSpecJson.roles`
* Download links: `codingAgentSpecUrl` and `humanSpecUrl`

## Code Examples

### cURL - Complete Flow

**Synchronous Request:**

```bash theme={null}
curl -X POST https://api.pre.dev/fast-spec \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "input": "Build a real-time collaborative whiteboard with drawing tools, shapes, text, and team presence indicators"
  }'
```

**Asynchronous Request with Polling:**

```bash theme={null}
# Step 1: Start async processing
RESPONSE=$(curl -X POST https://api.pre.dev/fast-spec \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "input": "Build a CRM with contact management, deal pipeline, and email integration",
    "async": true
  }')

SPEC_ID=$(echo $RESPONSE | jq -r '.specId')

# Step 2: Poll for status
while true; do
  STATUS=$(curl https://api.pre.dev/spec-status/$SPEC_ID \
    -H "Authorization: Bearer YOUR_API_KEY")

  STATE=$(echo $STATUS | jq -r '.status')

  if [ "$STATE" = "completed" ]; then
    echo "Spec ready!"
    echo $STATUS | jq -r '.codingAgentSpecUrl'
    break
  elif [ "$STATE" = "failed" ]; then
    echo "Processing failed"
    echo $STATUS | jq -r '.errorMessage'
    break
  fi

  echo "Status: $STATE - $(echo $STATUS | jq -r '.progress')"
  sleep 10
done
```

### Python - Complete Implementation

```python theme={null}
import requests
import time
from typing import Dict, Any

class ArchitectAPI:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.pre.dev"

    def generate_spec(
        self,
        input_text: str,
        current_context: str = None,
        async_mode: bool = False
    ) -> Dict[str, Any]:
        """Generate a fast spec."""
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        payload = {
            "input": input_text,
            "async": async_mode
        }

        if current_context:
            payload["currentContext"] = current_context

        response = requests.post(
            f"{self.base_url}/fast-spec",
            headers=headers,
            json=payload
        )

        response.raise_for_status()
        return response.json()

    def check_status(self, spec_id: str) -> Dict[str, Any]:
        """Check async processing status."""
        headers = {"Authorization": f"Bearer {self.api_key}"}

        response = requests.get(
            f"{self.base_url}/spec-status/{spec_id}",
            headers=headers
        )

        response.raise_for_status()
        return response.json()

    def wait_for_completion(self, spec_id: str, poll_interval: int = 10) -> Dict[str, Any]:
        """Wait for async processing to complete."""
        while True:
            status = self.check_status(spec_id)

            if status["status"] == "completed":
                return status
            elif status["status"] == "failed":
                raise Exception(f"Processing failed: {status.get('errorMessage')}")

            print(f"Status: {status['status']} - {status.get('progress', 'Processing...')}")
            time.sleep(poll_interval)

# Usage
api = ArchitectAPI(api_key="YOUR_API_KEY")

# Synchronous (wait for result)
result = api.generate_spec(
    input_text="Build a fitness tracking app with workout logging, progress charts, and social features",
)
print(f"Spec URL: {result['codingAgentSpecUrl']}")

# Asynchronous (poll for result)
response = api.generate_spec(
    input_text="Add AI meal planning and nutrition tracking to existing fitness app",
    current_context="Existing app has workout logging, user profiles, and basic social features built with React Native and Firebase",
    async_mode=True
)

result = api.wait_for_completion(response["specId"])
print(f"Spec ready: {result['codingAgentSpecUrl']}")
```

### JavaScript/Node.js - Complete Implementation

```javascript theme={null}
const fetch = require('node-fetch');

class ArchitectAPI {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.pre.dev';
  }

  async generateSpec({
    input,
    currentContext = null,
    async = false
  }) {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${this.apiKey}`
    };

    const payload = {
      input,
      async
    };

    if (currentContext) {
      payload.currentContext = currentContext;
    }

    const response = await fetch(`${this.baseUrl}/fast-spec`, {
      method: 'POST',
      headers,
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'API request failed');
    }

    return response.json();
  }

  async checkStatus(specId) {
    const headers = { 'Authorization': `Bearer ${this.apiKey}` };

    const response = await fetch(
      `${this.baseUrl}/spec-status/${specId}`,
      { headers }
    );

    if (!response.ok) {
      throw new Error('Failed to check status');
    }

    return response.json();
  }

  async waitForCompletion(specId, pollInterval = 10000) {
    while (true) {
      const status = await this.checkStatus(specId);

      if (status.status === 'completed') {
        return status;
      } else if (status.status === 'failed') {
        throw new Error(`Processing failed: ${status.errorMessage}`);
      }

      console.log(`Status: ${status.status} - ${status.progress || 'Processing...'}`);
      await new Promise(resolve => setTimeout(resolve, pollInterval));
    }
  }
}

// Usage Examples

// Synchronous
(async () => {
  const api = new ArchitectAPI('YOUR_API_KEY');

  try {
    const result = await api.generateSpec({
      input: 'Build an e-learning platform with video courses, quizzes, certificates, and student progress tracking'
    });

    console.log('Spec URL:', result.codingAgentSpecUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();

// With Documentation URLs
(async () => {
  const api = new ArchitectAPI('YOUR_API_KEY');

  try {
    const result = await api.generateSpec({
      input: 'Build a customer support ticketing system with priority levels and file attachments',
      docURLs: [
        'https://docs.pre.dev',
        'https://docs.stripe.com'
      ]
    });

    console.log('Spec URL:', result.codingAgentSpecUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();

// With File Upload
(async () => {
  const api = new ArchitectAPI('YOUR_API_KEY');

  try {
    // For file uploads, use multipart/form-data
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('input', 'Analyze the uploaded requirements document');
    formData.append('docURLs', JSON.stringify(['https://docs.pre.dev']));

    const response = await fetch(`${api.baseUrl}/fast-spec`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${api.apiKey}`
        // Note: Don't set Content-Type for FormData - browser sets it automatically
      },
      body: formData
    });

    const result = await response.json();
    console.log('Spec URL:', result.codingAgentSpecUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();

// Asynchronous with polling
(async () => {
  const api = new ArchitectAPI('YOUR_API_KEY');

  try {
    // Start processing
    const response = await api.generateSpec({
      input: 'Add gamification with points, badges, and leaderboards',
      currentContext: 'Existing e-learning platform with courses and progress tracking',
      async: true
    });

    console.log('Spec ID:', response.specId);

    // Wait for completion
    const result = await api.waitForCompletion(response.specId);
    console.log('Spec ready:', result.codingAgentSpecUrl);
  } catch (error) {
    console.error('Error:', error.message);
  }
})();
```

### TypeScript - Type-Safe Implementation

```typescript theme={null}
interface SpecRequest {
  input: string;
  currentContext?: string;
  docURLs?: string[];
  async?: boolean;
}

interface FileUploadRequest {
  file?: File;
  input?: string;
  docURLs?: string[];
  async?: boolean;
}

interface SpecResponse {
  codingAgentSpecUrl?: string;
  markdown?: string;
  fileUrl: string;
}

interface AsyncResponse {
  specId: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
}

interface ZippedDocsUrl {
  platform: string;
  masterZipShortUrl: string;
  masterMarkdownShortUrl?: string;
}

interface StatusResponse {
  _id?: string;
  created?: string;
  endpoint: 'fast_spec' | 'deep_spec';
  input: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  success: boolean;
  uploadedFileShortUrl?: string;
  uploadedFileName?: string;
  humanSpecUrl?: string;
  totalHumanHours?: number;
  architectureInfographicUrl?: string;
  codingAgentSpecUrl?: string;
  executionTime?: number;
  predevUrl?: string;
  zippedDocsUrls?: ZippedDocsUrl[];
  errorMessage?: string;
  creditsUsed?: number;     // Total credits consumed (available during processing and on completion)
  progress?: number;        // Overall progress percentage (0-100)
  progressMessage?: string; // Detailed progress message (e.g., "Generating User Stories...")
}

class ArchitectAPI {
  private apiKey: string;
  private baseUrl: string = 'https://api.pre.dev';

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  async generateSpec(request: SpecRequest): Promise<SpecResponse | AsyncResponse> {
    const response = await fetch(`${this.baseUrl}/fast-spec`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`
      },
      body: JSON.stringify(request)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'API request failed');
    }

    return response.json();
  }

  async checkStatus(specId: string): Promise<StatusResponse> {
    const response = await fetch(`${this.baseUrl}/spec-status/${specId}`, {
      headers: { 'Authorization': `Bearer ${this.apiKey}` }
    });

    if (!response.ok) {
      throw new Error('Failed to check status');
    }

    return response.json();
  }

  async waitForCompletion(specId: string, pollInterval: number = 10000): Promise<StatusResponse> {
    while (true) {
      const status = await this.checkStatus(specId);

      if (status.status === 'completed') {
        return status;
      } else if (status.status === 'failed') {
        throw new Error(`Processing failed: ${status.errorMessage}`);
      }

      console.log(`${status.status}: ${status.progress || 'Processing...'}`);
      await new Promise(resolve => setTimeout(resolve, pollInterval));
    }
  }
}
```

## What You Get

The generated specification includes:

* ✅ **Executive summary**
* ✅ **Feature breakdown** by category
* ✅ **Technical architecture** recommendations
* ✅ **Implementation milestones** with effort estimates
* ✅ **User stories** and acceptance criteria
* ✅ **Task checklist** with progress tracking
  * Task status legend: `[ ]` → `[→]` → `[✓]` → `[⊘]`
  * Update as your agent completes work
  * Keep both you and AI aligned on progress
* ✅ **Risk analysis** and considerations
* ✅ **Markdown formatted** for direct agent use

## Using Task Tracking

As your agent implements features, actively manage progress:

1. **Mark tasks in progress:** Change `[ ]` to `[→]` when starting
2. **Mark complete:** Change `[→]` to `[✓]` when done
3. **Mark skipped:** Change `[ ]` to `[⊘]` if skipping (with reason)

**Pro Tip:** Don't let your agent skip tasks without questioning why. This keeps implementation comprehensive and on-track.

## Documentation Scraping & Archives

### Overview

When you provide `docURLs` in your request, Architect automatically scrapes the documentation in parallel with spec generation and packages it into downloadable ZIP archives. This feature helps AI agents and developers have context about external APIs, design systems, or frameworks referenced in the spec.

### How It Works

1. **Parallel Processing:** Documentation scraping runs simultaneously with spec generation (not sequentially), so it doesn't slow down your request
2. **Graceful Degradation:** If documentation scraping fails, spec generation still completes successfully
3. **Organized Archives:** Each platform gets its own ZIP with hierarchical folder structure based on the documentation site

### Response Field: `zippedDocsUrls`

```typescript theme={null}
interface ZippedDocsUrl {
  platform: string;              // Hostname extracted from doc URL (e.g., "stripe.com", "docs.github.com")
  masterZipShortUrl: string;     // Short URL to download the ZIP archive
  masterMarkdownShortUrl?: string; // Optional: consolidated markdown file
}
```

### Example Request with Documentation URLs

```json theme={null}
{
  "input": "Build a payment processing system with Stripe integration",
  "docURLs": [
    "https://stripe.com/docs/api",
    "https://stripe.com/docs/payments",
    "https://docs.github.com/en/rest"
  ]
}
```

### Example Response with Documentation Archives

```json theme={null}
{
  "endpoint": "fast_spec",
  "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV6",
  "zippedDocsUrls": [
    {
      "platform": "stripe.com",
      "masterZipShortUrl": "https://api.pre.dev/s/xyz789"
    },
    {
      "platform": "docs.github.com",
      "masterZipShortUrl": "https://api.pre.dev/s/abc456"
    }
  ]
}
```

### ZIP Archive Structure

Each ZIP archive contains:

* Individual markdown files (one per scraped page)
* Hierarchical folder structure mirroring the documentation site
* Organized by documentation site structure

### Supported Domain Formats

The system handles various domain formats:

* `.com`, `.io`, `.org`, `.net`
* `.cloud`, `.dev`, `.ai`
* Country-specific TLDs (`.co.uk`, `.com.au`, etc.)
* Newer TLDs (`.tech`, `.app`, etc.)

### Best Practices for Documentation URLs

**Do:**

* ✅ Provide specific documentation pages relevant to your spec
* ✅ Include API documentation for integrations you're building
* ✅ Reference design system docs for UI consistency
* ✅ Use official documentation sources

**Don't:**

* ❌ Include general marketing pages
* ❌ Link to blog posts instead of official documentation
* ❌ Reference deprecated or outdated documentation
* ❌ Link to non-documentation content

### Viewing Documentation Archives

**Enterprise users** can view and download documentation archives from the API Usage Logs browser:

1. Navigate to [https://pre.dev/enterprise/dashboard?page=api](https://pre.dev/enterprise/dashboard?page=api)
2. Click on any API call to open the details modal
3. View the "Documentation Archives" section
4. Click download links to get the ZIP files

### Error Handling

If documentation scraping fails:

* `zippedDocsUrls` will be an empty array `[]`
* Spec generation continues normally
* No error is thrown (graceful degradation)

If `docURLs` is not provided or is an empty array:

* `zippedDocsUrls` will be an empty array `[]`
* Spec generation proceeds normally

## Best Practices

### Writing Effective Input

* Be specific about core features
* Include business context and constraints
* Mention technical preferences if any

### Managing Your Agent

* Actively interrupt to ensure tasks are checked off
* Question every skipped task
* Verify acceptance criteria before marking complete
* Triple check that tests are written

<Card title="Next: Deep Spec Endpoint" icon="arrow-right" href="/api-reference/deep-spec">
  Generate ultra-detailed specifications for complex projects.
</Card>


## OpenAPI

````yaml POST /fast-spec
openapi: 3.1.0
info:
  title: pre.dev Architect API
  description: >-
    Generate comprehensive software specifications for coding agents. The
    Architect API helps you create detailed project specifications that AI
    coding agents can understand and implement.
  version: 1.1.0
  contact:
    name: pre.dev Support
    url: https://pre.dev
    email: support@pre.dev
  license:
    name: Proprietary
    url: https://pre.dev/terms
servers:
  - url: https://api.pre.dev
    description: Production API Server
security:
  - apiKeyAuth: []
tags:
  - name: Spec Generation
    description: Generate comprehensive software specifications for AI coding agents
  - name: Status
    description: Check status of asynchronous specification processing
  - name: Spec Management
    description: List and search existing specifications
  - name: Account
    description: Manage user account and credits
  - name: Batches
    description: Submit and retrieve browser-agent task batches
paths:
  /fast-spec:
    post:
      tags:
        - Spec Generation
      summary: Generate Fast Spec
      description: >-
        Generate a comprehensive project specification quickly. Perfect for MVPs
        and prototypes with balanced depth and speed. Cost: Variable (~5-10
        credits based on complexity). Processing time: ~30-40 seconds.
      operationId: generateFastSpec
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SpecRequest'
            examples:
              newProject:
                summary: New Project
                value:
                  input: >-
                    Build a SaaS project management tool with team
                    collaboration, real-time updates, task tracking, and time
                    logging
              featureAddition:
                summary: Feature Addition
                value:
                  input: Add a calendar view and Gantt chart visualization
                  currentContext: >-
                    Existing task management system with list and board views,
                    user auth, and basic team features
              asyncRequest:
                summary: Async Request
                value:
                  input: >-
                    Build a comprehensive e-commerce platform with inventory
                    management
                  async: true
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/FileUploadRequest'
      responses:
        '200':
          description: Specification generated successfully
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/SpecResponse'
                  - $ref: '#/components/schemas/AsyncResponse'
        '400':
          description: Bad Request - Invalid input parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Unauthorized - Invalid or missing API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: Unauthorized
                message: Invalid or missing Authorization header
        '402':
          description: Payment Required - Insufficient credits
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InsufficientCreditsError'
        '429':
          description: Too Many Requests - Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - apiKeyAuth: []
components:
  schemas:
    SpecRequest:
      type: object
      required:
        - input
      properties:
        input:
          type: string
          description: Description of what you want to build or the feature you want to add
          example: >-
            Build a SaaS project management tool with team collaboration and
            real-time updates
        currentContext:
          type: string
          description: >-
            CRITICAL: Existing project/codebase context. When provided,
            generates feature addition spec. When omitted, generates full new
            project spec with setup, deployment, docs, maintenance
          example: >-
            Existing Next.js app with Supabase, has auth, task CRUD, team
            features
        docURLs:
          type: array
          items:
            type: string
            format: uri
          description: >-
            Optional array of documentation URLs that Architect will reference
            when generating specifications. Each URL is automatically scraped
            and packaged into downloadable ZIP archives organized by platform
          example:
            - https://docs.pre.dev
            - https://docs.stripe.com
        async:
          type: boolean
          default: false
          description: >-
            If true, returns immediately with requestId for status polling. If
            false (default), waits for completion
    FileUploadRequest:
      type: object
      properties:
        file:
          type: string
          format: binary
          description: >-
            Optional file to be parsed as input (e.g., existing code,
            documentation, requirements). Can be used alone or combined with
            input text
        input:
          type: string
          description: >-
            Optional additional text description when using file upload. Can be
            empty string if using only file
        docURLs:
          type: array
          items:
            type: string
          description: JSON stringified array of documentation URLs
        async:
          type: boolean
          default: false
    SpecResponse:
      type: object
      properties:
        endpoint:
          type: string
          enum:
            - fast_spec
            - deep_spec
          description: Which endpoint was used
        input:
          type: string
          description: Original input text provided
        status:
          type: string
          enum:
            - completed
          description: Completion status
        success:
          type: boolean
          description: Whether the request succeeded
        humanSpecUrl:
          type: string
          format: uri
          description: URL where the human-readable spec is hosted (downloadable markdown)
        totalHumanHours:
          type: number
          description: Estimated total hours for a human to implement the spec
        architectureInfographicUrl:
          type: string
          format: uri
          description: >-
            URL to a visual architecture infographic/diagram for the
            specification
        codingAgentSpecUrl:
          type: string
          format: uri
          description: >-
            URL where the coding agent spec format is hosted (downloadable
            markdown)
        codingAgentSpecJson:
          $ref: '#/components/schemas/CodingAgentSpecJson'
          description: >-
            Structured JSON spec optimized for AI coding assistants (excludes
            hours, personas, roles)
        codingAgentSpecMarkdown:
          type: string
          description: Markdown spec optimized for AI coding assistants
        humanSpecJson:
          $ref: '#/components/schemas/HumanSpecJson'
          description: >-
            Full structured JSON spec with hours, personas, and roles for human
            review
        humanSpecMarkdown:
          type: string
          description: Full markdown spec with all details for human review
        executionTime:
          type: integer
          description: Processing time in milliseconds
        predevUrl:
          type: string
          format: uri
          description: pre.dev project URL where you can view and edit the spec
        zippedDocsUrls:
          type: array
          description: >-
            Array of scraped documentation archives. Empty array if no docURLs
            provided or scraping fails. Each object contains platform identifier
            and download links
          items:
            $ref: '#/components/schemas/ZippedDocsUrl'
        creditsUsed:
          type: number
          description: >-
            Total credits consumed by this spec generation. Available in
            real-time during processing and persisted on completion. Typical
            values: Fast spec ~5-10, Deep spec ~10-50.
        userFlowGraph:
          $ref: '#/components/schemas/SpecGraph'
          description: >-
            User flow graph with nodes representing user stories/flows and edges
            showing navigation paths (only when completed)
        architectureGraph:
          $ref: '#/components/schemas/SpecGraph'
          description: >-
            System architecture graph with C1/C2 level nodes and their
            relationships (only when completed)
        enrichedTechStack:
          type: array
          items:
            $ref: '#/components/schemas/SpecEnrichedTechStackItem'
          description: >-
            Enriched tech stack with detailed reasons, descriptions, and
            alternatives for each technology (only when completed)
    AsyncResponse:
      type: object
      required:
        - specId
        - status
      properties:
        specId:
          type: string
          description: Unique ID to poll for status (use with /api/spec-status/:specId)
          example: 507f1f77bcf86cd799439011
        status:
          type: string
          enum:
            - pending
          description: Initial status
    Error:
      type: object
      required:
        - error
        - message
      properties:
        error:
          type: string
          description: Error type or code
        message:
          type: string
          description: Human-readable error message
    InsufficientCreditsError:
      type: object
      required:
        - error
        - message
        - generationsAvailable
      properties:
        error:
          type: string
          example: Insufficient credits
        message:
          type: string
          example: >-
            You have insufficient credits to generate a spec. Please purchase
            more credits or upgrade your plan.
        generationsAvailable:
          type: integer
          description: Number of credits currently available
          example: 0
    CodingAgentSpecJson:
      type: object
      required:
        - executiveSummary
        - coreFunctionalities
        - techStack
        - milestones
      description: >-
        Simplified structured JSON for AI coding tools (excludes hours,
        personas, roles)
      properties:
        title:
          type: string
          description: Title of the specification
        executiveSummary:
          type: string
          description: Executive summary of the project
        coreFunctionalities:
          type: array
          items:
            $ref: '#/components/schemas/SpecCoreFunctionality'
          description: List of core functionalities
        techStack:
          type: array
          items:
            $ref: '#/components/schemas/SpecTechStackItem'
          description: Technology stack items
        techStackGrouped:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
          description: Technology stack grouped by category
        milestones:
          type: array
          items:
            $ref: '#/components/schemas/CodingAgentMilestone'
          description: List of milestones
    HumanSpecJson:
      type: object
      required:
        - executiveSummary
        - coreFunctionalities
        - personas
        - techStack
        - milestones
        - totalHours
        - roles
      description: Full structured JSON with hours, personas, and roles for human review
      properties:
        title:
          type: string
          description: Title of the specification
        executiveSummary:
          type: string
          description: Executive summary of the project
        coreFunctionalities:
          type: array
          items:
            $ref: '#/components/schemas/SpecCoreFunctionality'
          description: List of core functionalities
        personas:
          type: array
          items:
            $ref: '#/components/schemas/SpecPersona'
          description: User personas
        techStack:
          type: array
          items:
            $ref: '#/components/schemas/SpecTechStackItem'
          description: Technology stack items
        techStackGrouped:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
          description: Technology stack grouped by category
        milestones:
          type: array
          items:
            $ref: '#/components/schemas/HumanSpecMilestone'
          description: List of milestones with hours
        totalHours:
          type: number
          description: Total estimated hours for the project
        roles:
          type: array
          items:
            $ref: '#/components/schemas/SpecRole'
          description: Roles required for the project
    ZippedDocsUrl:
      type: object
      required:
        - platform
        - masterZipShortUrl
      properties:
        platform:
          type: string
          description: >-
            Hostname extracted from the documentation URL (e.g., 'stripe.com',
            'docs.github.com')
          example: stripe.com
        masterZipShortUrl:
          type: string
          format: uri
          description: >-
            Short URL to download the zipped documentation archive for this
            platform
        masterMarkdownShortUrl:
          type: string
          format: uri
          description: Optional short URL to consolidated markdown file for this platform
    SpecGraph:
      type: object
      required:
        - nodes
        - edges
      properties:
        nodes:
          type: array
          items:
            $ref: '#/components/schemas/SpecGraphNode'
          description: Array of graph nodes
        edges:
          type: array
          items:
            $ref: '#/components/schemas/SpecGraphEdge'
          description: Array of graph edges
    SpecEnrichedTechStackItem:
      type: object
      required:
        - name
        - useFor
        - reason
        - description
      properties:
        name:
          type: string
          description: Name of the technology (e.g., React, PostgreSQL)
        useFor:
          type: string
          description: Category label (e.g., Frontend, Backend, Database)
        reason:
          type: string
          description: Why this technology was chosen for this specific project
        description:
          type: string
          description: Technical description of what the technology does
        link:
          type: string
          format: uri
          description: Official website or documentation URL
        helpfulLinks:
          type: array
          items:
            type: object
            properties:
              url:
                type: string
                format: uri
                description: URL to helpful resource
              description:
                type: string
                description: Description of the resource
          description: Array of helpful documentation and tutorial links
        alternatives:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
                description: Name of the alternative technology
              link:
                type: string
                format: uri
                description: URL of the alternative technology
              description:
                type: string
                description: Description of the alternative
          description: Array of alternative technologies that could be used instead
    SpecCoreFunctionality:
      type: object
      required:
        - name
        - description
      properties:
        name:
          type: string
          description: Name of the core functionality
        description:
          type: string
          description: Description of the functionality
        priority:
          type: string
          enum:
            - High
            - Medium
            - Low
          description: Priority level of the functionality
    SpecTechStackItem:
      type: object
      required:
        - name
        - category
      properties:
        name:
          type: string
          description: Name of the technology
        category:
          type: string
          description: Category of the technology (e.g., Frontend, Backend, Database)
    CodingAgentMilestone:
      type: object
      required:
        - milestoneNumber
        - description
        - stories
      properties:
        milestoneNumber:
          type: integer
          description: Milestone number
        description:
          type: string
          description: Description of the milestone
        stories:
          type: array
          items:
            $ref: '#/components/schemas/CodingAgentStory'
          description: List of user stories in this milestone
    SpecPersona:
      type: object
      required:
        - title
        - description
      properties:
        title:
          type: string
          description: Title of the persona
        description:
          type: string
          description: Description of the persona
        primaryGoals:
          type: array
          items:
            type: string
          description: Primary goals of the persona
        painPoints:
          type: array
          items:
            type: string
          description: Pain points of the persona
        keyTasks:
          type: array
          items:
            type: string
          description: Key tasks of the persona
    HumanSpecMilestone:
      type: object
      required:
        - milestoneNumber
        - description
        - hours
        - stories
      properties:
        milestoneNumber:
          type: integer
          description: Milestone number
        description:
          type: string
          description: Description of the milestone
        hours:
          type: number
          description: Estimated hours for this milestone
        stories:
          type: array
          items:
            $ref: '#/components/schemas/HumanSpecStory'
          description: List of user stories in this milestone
    SpecRole:
      type: object
      required:
        - name
        - shortHand
      properties:
        name:
          type: string
          description: Full name of the role (e.g., Full Stack Developer)
        shortHand:
          type: string
          description: Short abbreviation for the role (e.g., FSD)
    SpecGraphNode:
      type: object
      required:
        - id
        - label
      properties:
        id:
          type: string
          description: Unique identifier for the node
        label:
          type: string
          description: Display label for the node
        type:
          type: string
          description: >-
            Node type category. For architectureGraph: "frontend",
            "api-services", "databases", or "external-services". For
            userFlowGraph: "flow", "role", etc.
        description:
          type: string
          description: Description of the node
        level:
          type: number
          description: >-
            Graph depth level (1, 2, 3...) for userFlowGraph nodes. Not present
            on architectureGraph nodes.
        hours:
          type: number
          description: Estimated hours for this node
    SpecGraphEdge:
      type: object
      required:
        - source
        - target
      properties:
        source:
          type: string
          description: Source node ID
        target:
          type: string
          description: Target node ID
        description:
          type: string
          description: Description of the relationship
        edgeType:
          type: string
          description: Type of edge relationship
    CodingAgentStory:
      type: object
      required:
        - title
        - subTasks
      properties:
        id:
          type: string
          description: Story identifier (e.g., US-001)
        title:
          type: string
          description: Title of the user story
        description:
          type: string
          description: Description of the user story
        acceptanceCriteria:
          type: array
          items:
            type: string
          description: List of acceptance criteria
        complexity:
          type: string
          description: Complexity estimate for the story
        subTasks:
          type: array
          items:
            $ref: '#/components/schemas/CodingAgentSubTask'
          description: List of subtasks for this story
    HumanSpecStory:
      type: object
      required:
        - title
        - hours
        - subTasks
      properties:
        id:
          type: string
          description: Story identifier (e.g., US-001)
        title:
          type: string
          description: Title of the user story
        description:
          type: string
          description: Description of the user story
        acceptanceCriteria:
          type: array
          items:
            type: string
          description: List of acceptance criteria
        hours:
          type: number
          description: Estimated hours for this story
        complexity:
          type: string
          description: Complexity estimate for the story
        subTasks:
          type: array
          items:
            $ref: '#/components/schemas/HumanSpecSubTask'
          description: List of subtasks for this story
    CodingAgentSubTask:
      type: object
      required:
        - description
        - complexity
      properties:
        id:
          type: string
          description: Subtask identifier
        description:
          type: string
          description: Description of the subtask
        complexity:
          type: string
          enum:
            - S
            - M
            - L
            - XL
          description: Complexity estimate
    HumanSpecSubTask:
      type: object
      required:
        - description
        - hours
        - complexity
      properties:
        id:
          type: string
          description: Subtask identifier
        description:
          type: string
          description: Description of the subtask
        hours:
          type: number
          description: Estimated hours for this subtask
        complexity:
          type: string
          description: Complexity estimate
        roles:
          type: array
          items:
            $ref: '#/components/schemas/SpecRole'
          description: Roles assigned to this subtask
  securitySchemes:
    apiKeyAuth:
      type: http
      scheme: bearer
      bearerFormat: API Key
      description: >-
        API key for authentication. Get your API key from
        https://pre.dev/projects/playground (Solo) or
        https://pre.dev/enterprise/dashboard?page=api (Enterprise). Use format:
        Bearer YOUR_API_KEY
      x-default: YOUR_API_KEY

````