# Ghost Mechanic Specification
## Embedded Debugging Assistant for Dark Factory

*Version 1.0 - March 8, 2026*

---

## Overview

**Ghost Mechanic** is a lightweight, scoped AI assistant embedded in the Dark Factory dashboard. Unlike a general-purpose AI (like Tes), Ghost Mechanic is purpose-built for one job: **diagnosing and fixing issues with generated artifacts.**

It's not sentient. It's not creative. It's a very smart debugger with natural language interface.

---

## Core Principles

1. **Scoped Access** - Can ONLY see the customer's own artifacts and generation history
2. **Context-Aware** - Knows the original intent/spec for every generated component
3. **Action-Limited** - Can propose fixes, not arbitrarily modify systems
4. **Transparent** - Every action logged, every reasoning step visible
5. **Escalation-Ready** - Knows when to say "I can't fix this, here's why"

---

## Capabilities

### 1. Error Diagnosis

```typescript
interface DiagnosisRequest {
  artifactId: string;
  errorType: 'runtime' | 'build' | 'behavior' | 'integration';
  errorMessage?: string;
  userDescription?: string;  // "The submit button doesn't work"
  actionLog?: ActionLog[];   // From Weft Sandbox
  stackTrace?: string;
  browserConsole?: string[];
}

interface DiagnosisResult {
  confidence: number;  // 0-100
  rootCause: string;
  explanation: string;  // Human-readable
  affectedCode: {
    file: string;
    lines: [number, number];
    snippet: string;
  }[];
  proposedFix?: ProposedFix;
  needsMoreInfo?: string[];  // Questions for user
}
```

### 2. Fix Proposal

```typescript
interface ProposedFix {
  id: string;
  description: string;
  changes: CodeChange[];
  testPlan: string;  // How to verify the fix worked
  rollbackPlan: string;  // How to undo if it breaks more
  confidence: number;
  risks: string[];
}

interface CodeChange {
  file: string;
  type: 'modify' | 'add' | 'delete';
  before?: string;
  after?: string;
  explanation: string;
}
```

### 3. Repair Log

Every diagnosis and fix is logged for pattern learning:

```typescript
interface RepairLog {
  id: string;
  timestamp: Date;
  artifactId: string;
  errorType: string;
  diagnosis: DiagnosisResult;
  fixApplied?: ProposedFix;
  outcome: 'success' | 'partial' | 'failed' | 'pending';
  userFeedback?: string;
}
```

---

## User Interface

### Report Issue Flow

```
┌───────────────────────────────────────────────────────────┐
│  🔧 GHOST MECHANIC                                        │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  What's the issue with "Order Entry Form"?                │
│                                                           │
│  ┌───────────────────────────────────────────────────┐  │
│  │ When I click Submit, nothing happens. The button     │  │
│  │ just stays there. No error, no loading, nothing.     │  │
│  └───────────────────────────────────────────────────┘  │
│                                                           │
│  [📎 Attach Screenshot] [📝 Include Action Log]          │
│                                                           │
│                               [Diagnose →]                │
└───────────────────────────────────────────────────────────┘
```

### Diagnosis Result

```
┌───────────────────────────────────────────────────────────┐
│  🔍 DIAGNOSIS                           Confidence: 94%  │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  ROOT CAUSE:                                              │
│  The onClick handler is calling an async function but     │
│  not awaiting it. The form submission starts but the UI   │
│  doesn't reflect the loading state.                       │
│                                                           │
│  AFFECTED CODE:                                           │
│  ┌─────────────────────────────────────────────────┐  │
│  │ OrderForm.tsx, line 45:                           │  │
│  │                                                   │  │
│  │ - onClick={() => submitOrder(formData)}          │  │
│  │ + onClick={async () => {                         │  │
│  │ +   setLoading(true);                            │  │
│  │ +   await submitOrder(formData);                 │  │
│  │ +   setLoading(false);                           │  │
│  │ + }}                                             │  │
│  └─────────────────────────────────────────────────┘  │
│                                                           │
│  [Apply Fix]  [Show Full Diff]  [Explain More]            │
└───────────────────────────────────────────────────────────┘
```

---

## Context Sources

Ghost Mechanic has access to:

| Source | Purpose |
|--------|----------|
| **Original Spec** | What the user asked for |
| **Generation Log** | How Dark Factory interpreted the request |
| **Weft Config** | Expected API endpoints and behavior |
| **Action Log** | What the user actually did in sandbox |
| **Component Code** | The generated source files |
| **Repair History** | Past issues with this artifact |
| **Pattern Database** | Common issues across all artifacts |

---

## Escalation Paths

When Ghost Mechanic can't fix something:

```typescript
interface Escalation {
  reason: 
    | 'outside_scope'      // Requires system access Mechanic doesn't have
    | 'ambiguous_intent'   // Original spec unclear
    | 'integration_issue'  // Problem is in customer's external system
    | 'low_confidence'     // Multiple possible causes, none certain
    | 'complex_refactor';  // Fix requires architectural changes
  
  explanation: string;
  suggestions: string[];  // What the human should try
  supportTicketDraft?: string;  // Pre-filled for human escalation
}
```

---

## Personality & Tone

Ghost Mechanic should be:

- **Direct** - No fluff, just diagnosis
- **Technical** - Assumes user understands code
- **Humble** - States confidence levels, admits uncertainty
- **Helpful** - Always offers next steps

**Example responses:**

✅ "Found it. Line 45, missing await. Here's the fix."
✅ "I'm 78% confident this is a race condition. Can you tell me if the issue happens every time or intermittently?"
✅ "This looks like an issue in your backend, not the generated component. The form is sending the right payload, but your /api/orders endpoint returns 500."

❌ "I'd be happy to help you with your issue today!"
❌ "Let me think about this philosophically..."
❌ "As an AI, I have limitations..."

---

## Implementation Notes

### Model Selection

- Use a code-specialized model (Claude with code context, or fine-tuned variant)
- Context window must fit: spec + code + logs + repair history
- Streaming responses for long diagnoses

### Safety Rails

1. **No arbitrary code execution** - Proposes changes, doesn't apply them directly to production
2. **Sandboxed testing** - Fixes can be tested in Weft before applying
3. **Rollback ready** - Every fix includes undo instructions
4. **Rate limited** - Prevent abuse/runaway diagnosis loops

### Metrics to Track

- Fix success rate (did applying the fix resolve the issue?)
- Time to diagnosis
- Escalation rate
- User satisfaction (thumbs up/down)
- Recurring issues (same problem, same artifact)

---

## Summary

Ghost Mechanic is the "customer-facing" AI for Dark Factory - scoped, focused, and practical. It handles the debugging loop so customers can iterate independently without needing a "Tes" of their own.

The key insight: **Most debugging is pattern matching + context.** Ghost Mechanic has both, optimized for a narrow domain.

---

*"I fix things. That's what I do."*
— Ghost Mechanic
