# 🏭 Dark Factory

**Self-Building Code Generator** — AI that writes its own code, tests it, and deploys it.

Part of the [GhostFoundry-Syndicate](https://github.com/srmbsrg/ghostfoundry-syndicate) project.

---

## 🎯 What is Dark Factory?

Dark Factory is a recursive, self-referential code generation system. You describe what you want in natural language, and it:

1. **Parses your intent** using LLMs (GPT-4.1)
2. **Generates schemas** (Prisma models, TypeScript types, API specs)
3. **Writes production code** (API routes, database migrations, tests)
4. **Validates everything** (type checking, linting, test execution)
5. **Deploys to the codebase** (optional, with human gates)

> *"Build the factory first, then let the factory build the product."*

---

## 🧠 Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        DARK FACTORY                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────┐        │
│  │Intent Parser │ → │Schema Gen    │ → │Code Gen      │        │
│  │(NL → Spec)   │   │(Spec → Types)│   │(Types → Code)│        │
│  └──────────────┘   └──────────────┘   └──────────────┘        │
│         │                  │                  │                 │
│         ▼                  ▼                  ▼                 │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────┐        │
│  │Validation    │ ← │Test Gen      │ ← │Deployment    │        │
│  │(Type + Lint) │   │(Auto Tests)  │   │(Human Gates) │        │
│  └──────────────┘   └──────────────┘   └──────────────┘        │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

---

## 📁 Structure

```
dark-factory/
├── core/
│   ├── intent/
│   │   └── parser.ts         # NL → Structured Spec (LLM-powered)
│   ├── schema/
│   │   └── generator.ts      # Spec → Prisma + TypeScript types
│   └── orchestrator/
│       └── pipeline.ts       # 5-stage generation pipeline
├── generators/
│   ├── api/
│   │   └── route-generator.ts   # Next.js API route generation
│   ├── database/
│   │   └── prisma-generator.ts  # Prisma schema generation
│   └── tests/
│       └── test-generator.ts    # Auto test generation
├── validators/                  # Code validation (future)
├── deployers/                   # Deployment logic (future)
├── templates/                   # Reusable code patterns
├── api/                         # Next.js API endpoints
│   ├── generate/               # POST - Submit generation request
│   ├── status/[taskId]/        # GET - Check task status
│   ├── tasks/                  # GET - List all tasks
│   ├── artifacts/[id]/         # GET - Get generated code
│   ├── deploy/                 # POST - Deploy to codebase
│   └── events/                 # GET - Factory event log
├── components/                  # React UI components
│   ├── dashboard.tsx           # Main factory dashboard
│   ├── generation-form.tsx     # NL input form
│   ├── task-list.tsx           # Task browser
│   └── artifact-viewer.tsx     # Code viewer + deploy
├── types/
│   └── dark-factory.ts         # TypeScript definitions
└── index.ts                    # Main exports
```

---

## 🚀 Usage

### Via API

```bash
# Submit a generation request
curl -X POST http://localhost:3000/api/dark-factory/generate \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Create a customer feedback system with ratings, comments, and sentiment analysis"
  }'

# Check status
curl http://localhost:3000/api/dark-factory/status/{taskId}

# Get generated artifact
curl http://localhost:3000/api/dark-factory/artifacts/{artifactId}

# Deploy to codebase
curl -X POST http://localhost:3000/api/dark-factory/deploy \
  -H "Content-Type: application/json" \
  -d '{"artifactId": "...", "targetPath": "app/api/feedback"}'
```

### Via Dashboard

Navigate to `/dark-factory` in the GhostFoundry app to access the visual interface.

---

## 🔧 Pipeline Stages

| Stage | Description | Output |
|-------|-------------|--------|
| 1. **Parse Intent** | LLM extracts entities, relationships, operations from natural language | Structured spec JSON |
| 2. **Generate Schema** | Creates Prisma models + TypeScript types | `.prisma` + `.ts` files |
| 3. **Generate Code** | Writes API routes, validations, error handling | Next.js route handlers |
| 4. **Validate** | Type-checks, lints, runs generated tests | Pass/fail + errors |
| 5. **Deploy** | Writes to codebase (optional human gate) | Live code |

---

## 🎨 Example Prompts

```
"Build an invoice management system with line items, tax calculations, and PDF export"

"Create a task queue with priorities, retries, and dead letter handling"

"Design a subscription billing system with Stripe integration and usage tracking"

"Build a knowledge base with categories, search, and version history"
```

---

## 🔗 Integration

Dark Factory is designed to work with the GhostFoundry-Syndicate ecosystem:

- **Event Bus** — Emits events for each generation stage
- **Human Gates** — Requires approval before deploying critical code
- **Memory** — Stores successful patterns for future reference
- **Sentinel** — Monitors generated code for security issues

---

## 📜 License

MIT — Part of GhostFoundry-Syndicate

---

## 🌐 Links

- **Live Demo**: [SpookySoftwareSyndicate.com/dark-factory](https://spookysoftwaresyndicate.com/dark-factory)
- **Parent Project**: [GhostFoundry-Syndicate](https://github.com/srmbsrg/ghostfoundry-syndicate)
- **Author**: Scott Murphy ([@srmbsrg](https://github.com/srmbsrg))
