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

# Workflow Engine

> X402 workflow engine: stages, state, and error handling.

## X402 Workflow Engine

The “X402” workflow is implemented in `lib/x402.ts` and used by the Idea → Intent → Platform → Payment → Execute → Completion flow. It manages:

* **Stages** — `WorkflowStage` and transitions
* **Context** — `WorkflowContext` with all stage outputs
* **Persistence** — `getWorkflowContextDB`, `updateWorkflowContextDB`, `createWorkflowContextDB` (Prisma); in-memory `getWorkflowContext`, `updateWorkflowContext`, `createWorkflowContext` as fallback

***

## Workflow Stages

```
type WorkflowStage =
  | 'idea_input'
  | 'intent_analysis'
  | 'platform_selection'
  | 'payment_processing'
  | 'execution'
  | 'completion';
```

| Stage                   | API / Trigger               | Main data produced                                                   |
| :---------------------- | :-------------------------- | :------------------------------------------------------------------- |
| **idea\_input**         | `POST /api/idea`            | `idea`, `analysis`, `clarifyingQuestions`                            |
| **intent\_analysis**    | `POST /api/intent`          | `answers`, `refinedRequirements`                                     |
| **platform\_selection** | `POST /api/platform`        | `platformOptions`, `selectedPlatform` (later), `supabaseIntegration` |
| **payment\_processing** | `POST /api/payment` or Dodo | `paymentDetails` (wallet/signature or `dodoPaymentId`)               |
| **execution**           | `POST /api/execute`         | `executionResult`                                                    |
| **completion**          | —                           | UI only; uses `executionResult`                                      |

***

## State Management

### WorkflowContext

`WorkflowContext` in `lib/x402.ts`:

* `sessionId`, `currentStage`, `createdAt`, `updatedAt`
* `idea`, `analysis`, `clarifyingQuestions`, `answers`, `refinedRequirements`
* `platformOptions`, `selectedPlatform`, `supabaseIntegration`
* `paymentDetails` (e.g. `walletAddress`, `amountScript`, `transactionSignature`, `paymentMethod`, `dodoPaymentId`)
* `executionResult` (agents, deliverables, `review_passed`, etc.)

***

### Persistence

* **DB (preferred):** `getWorkflowContextDB`, `createWorkflowContextDB`, `updateWorkflowContextDB` map to the `Workflow` model in `prisma/schema.prisma`. Some fields (e.g. `platformOptions`, `executionResult`) are not fully stored in DB; the code merges with in-memory when needed.
* **In-memory:** `workflowStore = new Map<string, WorkflowContext>()`. Used when DB calls fail or for backwards compatibility.

API handlers typically: try DB first, on error fall back to in-memory. `execute` can rebuild a minimal context from `prisma.workflow` if the full context is missing.

***

### Transitions

* `getNextStage(current)` — Returns the next stage in order, or `null` at `completion`.
* `validateStageTransition(from, to)` — Allows same stage or the immediate next stage only.

***

## Error Handling

1. **Missing context** — Idea: create context if new `sessionId`. Intent/Platform/Payment/Execute: return 400 with a message to restart or complete the previous stage; Execute may try to rebuild from DB.
2. **DB vs in-memory** — On Prisma/connection errors, APIs log and fall back to in-memory; some fields (e.g. `platformOptions`) may be missing if only in memory.
3. **Execute-specific:**
   * No `refinedRequirements` → build minimal from `idea` if present, else 400.
   * No `selectedPlatform` → 400.
   * Transaction signature invalid → 400.
   * Any requested agent disabled (`isAgentEnabled`) → 503 with list of disabled agents.
4. **AI (OpenRouter) errors** — Propagated from `processIdea`, `refineIntent`, `selectPlatform`, `executeX402Workflow`; APIs return 500 with the error message.
5. **Platform templates** — On per-file generation failure, `generateFileContentWithAgent` uses `generateFileContent` as a fallback so the run can still complete.
