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

# Find Specs

> Search specs using regex patterns. Perfect for finding specs by keywords, patterns, or complex search criteria.

# GET /find-specs

Search for specifications using powerful regex patterns with optional status and endpoint filtering.

## Overview

* **Cost:** Free (no credits required)
* **Use Cases:** Keyword search, pattern matching, finding related specs
* **Response Time:** Instant
* **Search:** Case-insensitive regex matching against spec input text
* **Returns:** Paginated array of matching specs

## Endpoint

```
GET https://api.pre.dev/find-specs
```

## Headers

```
Authorization: Bearer YOUR_API_KEY
```

## Query Parameters

| Parameter  | Type    | Required | Default | Description                                                         |
| ---------- | ------- | -------- | ------- | ------------------------------------------------------------------- |
| `query`    | string  | ✅        | -       | **REQUIRED** - Regex pattern to search (case-insensitive)           |
| `limit`    | integer | ❌        | 20      | Results per page (1-100)                                            |
| `skip`     | integer | ❌        | 0       | Number of records to skip for pagination                            |
| `endpoint` | string  | ❌        | -       | Filter by endpoint: `fast_spec` or `deep_spec`                      |
| `status`   | string  | ❌        | -       | Filter by status: `pending`, `processing`, `completed`, or `failed` |

### Parameter Details

**query** (REQUIRED)

* Regex pattern matched against spec `input` field
* Case-insensitive by default
* Supports full regex syntax
* Must be URL-encoded in request

**limit**

* Minimum: 1
* Maximum: 100
* Default: 20

**skip**

* Minimum: 0
* Used for pagination

**endpoint**

* `fast_spec` - Only search Fast Spec generations
* `deep_spec` - Only search Deep Spec generations

**status**

* `pending` - Only queued specs
* `processing` - Only specs currently generating
* `completed` - Only successfully finished specs
* `failed` - Only failed generations

## Regex Pattern Examples

| Pattern            | What It Matches                | Example Use Case                   |
| ------------------ | ------------------------------ | ---------------------------------- |
| `payment`          | Contains "payment" (any case)  | Find all payment-related specs     |
| `^Build`           | Starts with "Build"            | Find all "Build X" specs           |
| `platform$`        | Ends with "platform"           | Find platform projects             |
| `(API\|REST)`      | Contains "API" OR "REST"       | Find API-related specs             |
| `auth.*system`     | "auth" followed by "system"    | Find authentication systems        |
| `\d{3,}`           | Contains 3+ consecutive digits | Find specs with quantities/budgets |
| `saas\|sass`       | Contains "saas" OR "sass"      | Catch common misspellings          |
| `e-?commerce`      | "ecommerce" or "e-commerce"    | Match hyphen variations            |
| `task.*management` | "task" then "management"       | Find task/project mgmt tools       |
| `real.?time`       | "realtime" or "real time"      | Match spacing variations           |

## Response

### Success Response

Same structure as `/list-specs`:

```json theme={null}
{
  "specs": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "created": "2024-01-15T14:30:00.000Z",
      "endpoint": "fast_spec",
      "input": "Build a payment processing system with Stripe integration",
      "status": "completed",
      "success": true,
      "humanSpecUrl": "https://api.pre.dev/s/a6hFJRV6",
      "totalHumanHours": 120,
      "codingAgentSpecUrl": "https://api.pre.dev/s/a6hFJRV7",
      "executionTime": 38500
    }
  ],
  "total": 8,
  "hasMore": false
}
```

### Response Fields

Identical to the [list-specs endpoint](/architect-agent/api/list-specs#response-fields). See that documentation for complete field descriptions.

## Code Examples

### cURL Examples

**Simple keyword search:**

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=payment"
```

**Search with URL encoding:**

```bash theme={null}
# Search for specs starting with "Build"
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=%5EBuild"
```

**Search completed specs only:**

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=dashboard&status=completed"
```

**Search with OR condition:**

```bash theme={null}
# Find specs containing "API" OR "REST"
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=(API%7CREST)"
```

**Complex pattern with pagination:**

```bash theme={null}
# Find e-commerce specs (handles hyphen variations)
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.pre.dev/find-specs?query=e-?commerce&limit=50&skip=0"
```

### JavaScript/Node.js

```javascript theme={null}
async function findSpecs(query, options = {}) {
  const {
    limit = 20,
    skip = 0,
    endpoint = null,
    status = null
  } = options;

  const params = new URLSearchParams({
    query,
    limit: limit.toString(),
    skip: skip.toString()
  });

  if (endpoint) params.append('endpoint', endpoint);
  if (status) params.append('status', status);

  const response = await fetch(
    `https://api.pre.dev/find-specs?${params}`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}

// Usage examples

// Simple keyword search
const paymentSpecs = await findSpecs('payment');
console.log(`Found ${paymentSpecs.total} payment specs`);

// Search for specs starting with "Build"
const buildSpecs = await findSpecs('^Build');

// Search with filters
const dashboards = await findSpecs('dashboard', {
  status: 'completed',
  limit: 50
});

// Complex regex: find API or REST specs
const apiSpecs = await findSpecs('(API|REST)');

// Search with pagination
async function searchAllMatches(query) {
  let allMatches = [];
  let skip = 0;
  const limit = 50;

  while (true) {
    const response = await findSpecs(query, { skip, limit });
    allMatches.push(...response.specs);
    
    if (!response.hasMore) break;
    skip += limit;
  }

  return allMatches;
}

// Search for e-commerce (with hyphen variation)
const ecommerce = await findSpecs('e-?commerce');

// Find authentication systems
const authSystems = await findSpecs('auth.*system');
```

### TypeScript

```typescript theme={null}
interface FindSpecsOptions {
  limit?: number;
  skip?: number;
  endpoint?: 'fast_spec' | 'deep_spec';
  status?: 'pending' | 'processing' | 'completed' | 'failed';
}

interface SearchResult {
  specs: SpecObject[];
  total: number;
  hasMore: boolean;
  query: string;
}

class SpecSearchClient {
  constructor(private apiKey: string) {}

  async findSpecs(
    query: string,
    options: FindSpecsOptions = {}
  ): Promise<SearchResult> {
    const {
      limit = 20,
      skip = 0,
      endpoint,
      status
    } = options;

    const params = new URLSearchParams({
      query,
      limit: limit.toString(),
      skip: skip.toString()
    });

    if (endpoint) params.append('endpoint', endpoint);
    if (status) params.append('status', status);

    const response = await fetch(
      `https://api.pre.dev/find-specs?${params}`,
      {
        headers: { 'Authorization': `Bearer ${this.apiKey}` }
      }
    );

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    const data = await response.json();
    return { ...data, query };
  }

  async *searchPaginated(
    query: string,
    options: FindSpecsOptions = {}
  ): AsyncGenerator<SpecObject[], void, unknown> {
    let skip = 0;
    const limit = options.limit || 50;

    while (true) {
      const response = await this.findSpecs(query, { ...options, skip, limit });
      
      if (response.specs.length === 0) break;
      
      yield response.specs;
      
      if (!response.hasMore) break;
      skip += limit;
    }
  }

  async searchWithHighlight(
    query: string,
    options: FindSpecsOptions = {}
  ): Promise<Array<SpecObject & { highlight: string }>> {
    const result = await this.findSpecs(query, options);
    
    // Add highlighting to matched text
    const regex = new RegExp(`(${query})`, 'gi');
    
    return result.specs.map(spec => ({
      ...spec,
      highlight: spec.input.replace(regex, '<mark>$1</mark>')
    }));
  }
}

// Usage
const searchClient = new SpecSearchClient('YOUR_API_KEY');

// Simple search
const results = await searchClient.findSpecs('payment', { 
  status: 'completed' 
});
console.log(`Found ${results.total} completed payment specs`);

// Paginated search
for await (const batch of searchClient.searchPaginated('dashboard')) {
  console.log(`Processing ${batch.length} dashboard specs...`);
  batch.forEach(spec => console.log(`  - ${spec.input}`));
}

// Search with highlighting
const highlighted = await searchClient.searchWithHighlight('payment');
highlighted.forEach(spec => {
  console.log(spec.highlight); // HTML with <mark> tags
});

// Complex searches
const apiOrRest = await searchClient.findSpecs('(API|REST)');
const startsWithBuild = await searchClient.findSpecs('^Build');
const hasRealtime = await searchClient.findSpecs('real.?time');
```

### Python

```python theme={null}
import requests
from typing import Optional, List, Dict, Any, Generator
import urllib.parse

class SpecSearchClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://api.pre.dev'
    
    def find_specs(
        self,
        query: str,
        limit: int = 20,
        skip: int = 0,
        endpoint: Optional[str] = None,
        status: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Search specs using regex pattern.
        
        Args:
            query: Regex pattern to search (case-insensitive)
            limit: Number of results per page (1-100)
            skip: Number of records to skip
            endpoint: Filter by 'fast_spec' or 'deep_spec'
            status: Filter by 'pending', 'processing', 'completed', or 'failed'
        
        Returns:
            Dictionary with 'specs' array, 'total' count, and 'hasMore' flag
        """
        params = {
            'query': query,
            'limit': limit,
            'skip': skip
        }
        
        if endpoint:
            params['endpoint'] = endpoint
        if status:
            params['status'] = status
        
        response = requests.get(
            f'{self.base_url}/find-specs',
            params=params,
            headers={'Authorization': f'Bearer {self.api_key}'}
        )
        response.raise_for_status()
        return response.json()
    
    def search_all(
        self,
        query: str,
        endpoint: Optional[str] = None,
        status: Optional[str] = None,
        batch_size: int = 50
    ) -> List[Dict[str, Any]]:
        """Fetch all specs matching the search query."""
        all_results = []
        skip = 0
        
        while True:
            response = self.find_specs(
                query=query,
                limit=batch_size,
                skip=skip,
                endpoint=endpoint,
                status=status
            )
            all_results.extend(response['specs'])
            
            if not response['hasMore']:
                break
            
            skip += batch_size
        
        return all_results
    
    def search_paginated(
        self,
        query: str,
        endpoint: Optional[str] = None,
        status: Optional[str] = None,
        batch_size: int = 50
    ) -> Generator[List[Dict[str, Any]], None, None]:
        """Generator that yields batches of search results."""
        skip = 0
        
        while True:
            response = self.find_specs(
                query=query,
                limit=batch_size,
                skip=skip,
                endpoint=endpoint,
                status=status
            )
            
            if not response['specs']:
                break
            
            yield response['specs']
            
            if not response['hasMore']:
                break
            
            skip += batch_size

# Usage examples
client = SpecSearchClient('YOUR_API_KEY')

# Simple keyword search
payment_specs = client.find_specs('payment')
print(f"Found {payment_specs['total']} payment specs")

# Search with filters
dashboards = client.find_specs(
    'dashboard',
    status='completed',
    limit=50
)

# Complex regex patterns
api_specs = client.find_specs('(API|REST)')  # OR condition
build_specs = client.find_specs('^Build')    # Starts with
auth_systems = client.find_specs('auth.*system')  # Pattern with wildcard

# Search for e-commerce (handles hyphen variations)
ecommerce = client.find_specs('e-?commerce')

# Get all matches
all_payment_specs = client.search_all('payment', status='completed')
print(f"Total payment specs: {len(all_payment_specs)}")

# Process in batches
for batch in client.search_paginated('dashboard', batch_size=25):
    print(f"Processing {len(batch)} dashboard specs")
    for spec in batch:
        print(f"  - {spec['input'][:60]}...")

# Common search patterns
def search_patterns():
    """Examples of useful search patterns."""
    
    # Find all SaaS projects
    saas_specs = client.find_specs('saas', status='completed')
    
    # Find real-time features (handles spacing)
    realtime = client.find_specs('real.?time')
    
    # Find specs with numbers (budgets, quantities)
    with_numbers = client.find_specs(r'\d{3,}')
    
    # Find authentication/authorization
    auth = client.find_specs('auth(entication|orization)?')
    
    # Find e-commerce variations
    ecommerce = client.find_specs('e-?commerce')
    
    return {
        'saas': saas_specs['total'],
        'realtime': realtime['total'],
        'with_numbers': with_numbers['total'],
        'auth': auth['total'],
        'ecommerce': ecommerce['total']
    }
```

## Common Use Cases

### 1. Search Bar Implementation

```javascript theme={null}
async function handleSearch(searchTerm, filters = {}) {
  try {
    // Escape special regex characters for literal search
    const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    
    const results = await findSpecs(escapedTerm, {
      status: filters.status,
      endpoint: filters.endpoint,
      limit: 20
    });
    
    return {
      results: results.specs,
      total: results.total,
      hasMore: results.hasMore
    };
  } catch (error) {
    console.error('Search failed:', error);
    return { results: [], total: 0, hasMore: false };
  }
}
```

### 2. Find Related Specs

```python theme={null}
def find_related_specs(base_spec_input: str, client: SpecSearchClient):
    """Find specs related to a given spec."""
    # Extract key terms (simplified example)
    keywords = base_spec_input.lower().split()[:3]
    pattern = '|'.join(keywords)
    
    related = client.find_specs(pattern, limit=10)
    return related['specs']
```

### 3. Category-Based Search

```typescript theme={null}
const CATEGORY_PATTERNS: Record<string, string> = {
  ecommerce: 'e-?commerce|shop|store|cart',
  authentication: 'auth(entication|orization)?|login|signup',
  realtime: 'real.?time|websocket|live|streaming',
  payment: 'payment|billing|stripe|checkout',
  dashboard: 'dashboard|analytics|metrics|reporting',
  api: '(API|REST|GraphQL)',
  social: 'social|chat|messaging|comment',
  ai: '(AI|ML|machine.?learning|artificial.?intelligence)'
};

async function searchByCategory(category: string) {
  const pattern = CATEGORY_PATTERNS[category];
  if (!pattern) {
    throw new Error(`Unknown category: ${category}`);
  }
  
  return await searchClient.findSpecs(pattern, {
    status: 'completed',
    limit: 50
  });
}
```

### 4. Advanced Search with Multiple Criteria

```javascript theme={null}
async function advancedSearch({
  mustInclude = [],      // All of these terms
  shouldInclude = [],    // Any of these terms
  mustExclude = [],      // None of these terms
  status = null,
  endpoint = null
}) {
  // Build regex pattern
  let pattern = '';
  
  if (mustInclude.length > 0) {
    // Positive lookahead for each required term
    pattern = mustInclude.map(term => `(?=.*${term})`).join('');
    pattern += '.*';
  }
  
  if (shouldInclude.length > 0) {
    pattern += `(${shouldInclude.join('|')})`;
  }
  
  // Note: mustExclude requires client-side filtering as regex negative lookahead
  // can be complex. Better to filter results after fetching.
  
  const results = await findSpecs(pattern || '.*', { status, endpoint });
  
  // Client-side filtering for exclusions
  if (mustExclude.length > 0) {
    const excludeRegex = new RegExp(mustExclude.join('|'), 'i');
    results.specs = results.specs.filter(
      spec => !excludeRegex.test(spec.input)
    );
    results.total = results.specs.length;
  }
  
  return results;
}

// Usage
const results = await advancedSearch({
  mustInclude: ['task', 'management'],
  shouldInclude: ['team', 'collaboration'],
  mustExclude: ['deprecated'],
  status: 'completed'
});
```

## Regex Tips & Tricks

### Common Patterns

```javascript theme={null}
// Case variations
'saas|SaaS|SAAS'  // Match any capitalization

// Word boundaries
'\\bapi\\b'       // Match "api" as whole word only

// Optional characters
'e-?commerce'     // Match "ecommerce" or "e-commerce"
'real.?time'      // Match "realtime" or "real time"

// Character classes
'[Pp]ayment'      // Match "Payment" or "payment"
'task[- ]management'  // Match "task management" or "task-management"

// Quantifiers
'\\d{3,}'         // 3 or more digits
'feature.*flag'   // "feature" then "flag" with anything between

// Alternation
'(dashboard|admin|panel)'  // Match any of these

// Start/End anchors
'^Build'          // Must start with "Build"
'platform$'       // Must end with "platform"
```

### URL Encoding

When using cURL or constructing URLs directly, encode special characters:

| Character | Encoded      | Example Pattern   | Encoded URL              |
| --------- | ------------ | ----------------- | ------------------------ |
| `^`       | `%5E`        | `^Build`          | `query=%5EBuild`         |
| `$`       | `%24`        | `platform$`       | `query=platform%24`      |
| `\|`      | `%7C`        | `API\|REST`       | `query=API%7CREST`       |
| `(`       | `%28`        | `(API\|REST)`     | `query=%28API%7CREST%29` |
| `)`       | `%29`        | `(API\|REST)`     | `query=%28API%7CREST%29` |
| Space     | `%20` or `+` | `task management` | `query=task+management`  |

Most HTTP clients handle this automatically.

## Best Practices

### Search Patterns

* Start with simple keywords, add complexity if needed
* Use case-insensitive patterns (already default)
* Handle common variations (hyphens, spaces, plural forms)
* Test patterns before using in production

### Performance

* Use specific patterns to reduce result sets
* Combine with `status` and `endpoint` filters
* Implement pagination for large result sets
* Cache frequent searches

### User Experience

* Show loading states during search
* Display result counts
* Highlight matched terms in results
* Provide search suggestions or examples
* Handle empty results gracefully

### Error Handling

* Validate regex patterns client-side when possible
* Catch and display API errors clearly
* Provide fallback for invalid regex
* Show helpful messages for no results

## Limitations

* Search only matches against the `input` field
* Maximum 100 results per request (use pagination for more)
* Regex is case-insensitive by default
* Very complex regex patterns may impact performance

<Card title="Back: List Specs" icon="arrow-left" href="/api-reference/list-specs">
  List all specs with pagination and filtering.
</Card>


## OpenAPI

````yaml GET /find-specs
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:
  /find-specs:
    get:
      tags:
        - Spec Management
      summary: Find Specs (Search)
      description: >-
        Search for specifications using regex patterns. Perfect for finding
        specs by keywords, patterns, or complex search criteria.
        Case-insensitive search. This endpoint is free and does not consume
        credits.
      operationId: findSpecs
      parameters:
        - name: query
          in: query
          required: true
          description: REQUIRED - Regex pattern to search (case-insensitive)
          schema:
            type: string
            example: payment
        - name: limit
          in: query
          required: false
          description: Number of results per page (1-100)
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
            example: 20
        - name: skip
          in: query
          required: false
          description: Number of records to skip for pagination
          schema:
            type: integer
            minimum: 0
            default: 0
            example: 0
        - name: endpoint
          in: query
          required: false
          description: Filter by endpoint type
          schema:
            type: string
            enum:
              - fast_spec
              - deep_spec
            example: fast_spec
        - name: status
          in: query
          required: false
          description: Filter by processing status
          schema:
            type: string
            enum:
              - pending
              - processing
              - completed
              - failed
            example: completed
      responses:
        '200':
          description: Search results retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListSpecsResponse'
              examples:
                keywordSearch:
                  summary: Search for 'payment'
                  value:
                    specs:
                      - _id: 507f1f77bcf86cd799439011
                        created: '2024-01-15T14:30:00.000Z'
                        endpoint: fast_spec
                        input: >-
                          Build a payment processing system with Stripe
                          integration
                        status: completed
                        success: true
                        humanSpecUrl: https://api.pre.dev/s/a6hFJRV6
                        codingAgentSpecUrl: https://api.pre.dev/s/a6hFJRV7
                    total: 8
                    hasMore: false
                patternSearch:
                  summary: Search for specs starting with 'Build'
                  value:
                    specs:
                      - _id: 507f1f77bcf86cd799439012
                        created: '2024-01-15T12:00:00.000Z'
                        endpoint: fast_spec
                        input: Build a real-time collaborative whiteboard
                        status: completed
                        success: true
                        humanSpecUrl: https://api.pre.dev/s/a6hFJRV6
                        codingAgentSpecUrl: https://api.pre.dev/s/a6hFJRV7
                    total: 23
                    hasMore: true
        '400':
          description: Bad Request - Missing required query parameter
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: Bad Request
                message: Query parameter is required
        '401':
          description: Unauthorized - Invalid or missing API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - apiKeyAuth: []
components:
  schemas:
    ListSpecsResponse:
      type: object
      required:
        - specs
        - total
        - hasMore
      properties:
        specs:
          type: array
          description: Array of spec objects matching the filters
          items:
            $ref: '#/components/schemas/StatusResponse'
        total:
          type: integer
          description: Total number of specs matching the filters
          example: 42
        hasMore:
          type: boolean
          description: Whether more pages are available
          example: true
    Error:
      type: object
      required:
        - error
        - message
      properties:
        error:
          type: string
          description: Error type or code
        message:
          type: string
          description: Human-readable error message
    StatusResponse:
      type: object
      properties:
        _id:
          type: string
          description: MongoDB ObjectId of the spec request
        created:
          type: string
          format: date-time
          description: ISO timestamp when the request was created
        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:
            - pending
            - processing
            - completed
            - failed
          description: Current status
        success:
          type: boolean
          description: Whether the request succeeded
        uploadedFileShortUrl:
          type: string
          description: Short URL for uploaded file (if file was uploaded)
        uploadedFileName:
          type: string
          description: Name of uploaded file (if file was uploaded)
        humanSpecUrl:
          type: string
          format: uri
          description: URL where the human-readable spec is hosted (only when completed)
        totalHumanHours:
          type: number
          description: >-
            Estimated total hours for a human to implement the spec (only when
            completed)
        architectureInfographicUrl:
          type: string
          format: uri
          description: >-
            URL to a visual architecture infographic/diagram for the
            specification (only when completed)
        codingAgentSpecUrl:
          type: string
          format: uri
          description: >-
            URL where the coding agent spec format is hosted (only when
            completed)
        codingAgentSpecJson:
          $ref: '#/components/schemas/CodingAgentSpecJson'
          description: >-
            Structured JSON spec optimized for AI coding assistants (only when
            completed)
        codingAgentSpecMarkdown:
          type: string
          description: >-
            Markdown spec optimized for AI coding assistants (only when
            completed)
        humanSpecJson:
          $ref: '#/components/schemas/HumanSpecJson'
          description: >-
            Full structured JSON spec with hours, personas, and roles (only when
            completed)
        humanSpecMarkdown:
          type: string
          description: >-
            Full markdown spec with all details for human review (only when
            completed)
        executionTime:
          type: integer
          description: Processing time in milliseconds (only when completed or failed)
        predevUrl:
          type: string
          format: uri
          description: pre.dev project URL (only when completed)
        zippedDocsUrls:
          type: array
          description: >-
            Array of scraped documentation archives (only when completed). Empty
            array if no docURLs provided or scraping fails
          items:
            $ref: '#/components/schemas/ZippedDocsUrl'
        errorMessage:
          type: string
          description: Error description (only when failed)
        progress:
          type: string
          description: Human-readable progress description
        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)
    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

````