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

# Data Flow

> Data flow, request/response patterns, state transitions, and persistence.

## Data Flow Overview

```
User (Idea) ──→ /api/idea ──→ processIdea ──→ WorkflowContext (idea, analysis, clarifyingQuestions)
                    │
                    └── create/update Workflow (DB or in-memory)

User (Answers) ──→ /api/intent ──→ refineIntent ──→ WorkflowContext (answers, refinedRequirements)
                    │
                    └── update Workflow

User (Platform) ──→ /api/platform ──→ selectPlatform ──→ WorkflowContext (platformOptions, supabaseIntegration)
                    │
                    └── update Workflow

User (Wallet/Checkout) ──→ /api/payment or /api/dodo/create-checkout ──→ validatePayment or Dodo
                    │
                    └── update Workflow (paymentDetails: wallet/signature or dodoPaymentId)

User (Tx / Dodo success) ──→ /api/execute ──→ executeX402Workflow ──→ generatePlatformDeliverables
                    │                              │
                    │                              └── Review, dedupe, ZIP, etc.
                    │
                    └── update Workflow (executionResult), AgentStat, Transaction, User.totalSpent

Dodo ──→ /api/dodo/webhook ──→ update Workflow (paymentMethod, dodoPaymentId, selectedPlatform, etc.)
```

***

## Request/Response Flow

### Idea

* **Request:** `POST /api/idea` — `{ idea, sessionId? }`
* **Flow:** Create/get context → `processIdea(idea, sessionId)` → persist `analysis`, `clarifyingQuestions`
* **Response:** `{ status, sessionId, stage: 'idea_input', analysis, clarifying_questions, next_stage: 'intent_analysis' }`

***

### Intent

* **Request:** `POST /api/intent` — `{ sessionId, answers, idea? }`
* **Flow:** Load context (DB then memory); if missing and `idea` provided, recreate → `refineIntent(idea, answers, sessionId)` → persist `answers`, `refinedRequirements`
* **Response:** `{ status, stage: 'intent_analysis', refined_requirements, next_stage: 'platform_selection' }`

***

### Platform

* **Request:** `POST /api/platform` — `{ sessionId, refinedRequirements?, supabaseIntegration? }`
* **Flow:** Load context; recover `refinedRequirements` from body if needed → `selectPlatform(refinedRequirements, sessionId)` → normalize `cost_script` to `UNIFIED_PRICE_SCRIPT` → persist `platformOptions`, `supabaseIntegration`
* **Response:** `{ status, stage: 'platform_selection', platform_options, recommended, next_stage: 'payment_processing' }`

***

### Payment (Solana)

* **Request:** `POST /api/payment` — `{ sessionId, selectedPlatform, userWalletPubKey }`
* **Flow:** Load context → find platform cost → `validatePayment(userWalletPubKey, cost_script)` → persist `paymentDetails` (wallet, amount, `paymentMethod: 'solana'`)
* **Response:** `{ status, stage: 'payment_processing', payment_details?, payment_issues?, next_stage?: 'execution' }`

***

### Payment (Dodo)

* **Create checkout:** `POST /api/dodo/create-checkout` — `{ sessionId, platform }` → Dodo API → `{ checkout_url }`
* **Webhook:** `POST /api/dodo/webhook` — `payment.succeeded` etc. → update `Workflow` (`dodoPaymentId`, `paymentMethod: 'dodo'`, `selectedPlatform` from metadata)
* **Confirm (optional):** `POST /api/dodo/confirm-payment` for client-side confirmation flow

***

### Execute

* **Request:** `POST /api/execute` — `{ sessionId, transactionSignature?, platform? }`
* **Flow:** Load/rebuild context → verify `transactionSignature` if present → check `isAgentEnabled` for each agent → `executeX402Workflow(...)` which calls `generatePlatformDeliverables` → persist `executionResult` → update `AgentStat`, `Transaction`, `User.totalSpent`
* **Response:** `{ status, stage: 'execution', execution_result: { agents_executed, deliverables, total_cost_script, execution_time_minutes, review_passed?, review_issues? }, next_stage: 'completion' }`

***

## State Transitions

Stages advance in order:\
`idea_input` → `intent_analysis` → `platform_selection` → `payment_processing` → `execution` → `completion`.

* **idea\_input:** Set by `/api/idea`; `next_stage` = `intent_analysis`.
* **intent\_analysis:** Set by `/api/intent`; `next_stage` = `platform_selection`.
* **platform\_selection:** Set by `/api/platform`; `next_stage` = `payment_processing`.
* **payment\_processing:** Set by `/api/payment` or Dodo webhook; user then proceeds to Execute.
* **execution:** Set by `/api/execute`; `next_stage` = `completion`.
* **completion:** No API; UI shows results. `getNextStage('completion')` is `null`.

`validateStageTransition(from, to)` allows only `to === from` or `to === getNextStage(from)`.

***

## Data Persistence

### Workflow (Prisma)

* **Model:** `Workflow` in `prisma/schema.prisma`
* **Stored:** `sessionId`, `currentStage`, `idea`, `analysisSummary`, `analysisFeatures`, `complexity`, `estimatedAgents`, `clarifyingQuestions`, `answers`, `refinedTitle`, `refinedDesc`, `refinedFeatures`, `targetAudience`, `techReqs`, `selectedPlatform`, `supabaseIntegration`, `walletAddress`, `amountScript`, `transactionSig`, `dodoPaymentId`, `paymentMethod`, `zipFile`, `zipFileName`, `zipFileSize`, timestamps
* **Not stored (or only in memory):** `platformOptions` (array), `executionResult` (object). APIs merge from in-memory when available.

***

### Other Models

* **User** — `walletAddress`, `totalSpent`, etc.; updated on Execute for Solana payments.
* **Transaction** — `userWallet`, `planType`, `amount`, `status`, `transactionHash`, `agentTriggered`; written on Execute.
* **AgentStat** — Per-agent `executions`, `successes`, `errors`, `totalExecutionTime`; updated on Execute.
* **AgentControl** — Per-agent `enabled`; used by `isAgentEnabled` in Execute.
* **ZipFile** — `sessionId`, `fileName`, `fileData`, `fileSize`, `projectName`, `userWallet`; populated when projects are zipped for download.
* **ExecutionLog**, **Ticket**, **PromptSale** — Used by other features (logs, support, marketplace).

***

### In-Memory

* **x402:** `workflowStore: Map<sessionId, WorkflowContext>` when DB is not used or for `platformOptions`/`executionResult`.
* **a2a:** `A2AMessageBus` — `Map<sessionId, A2AMessage[]>` and subscriber sets.
