Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# StackForge v1 Architecture

StackForge turns a plain-English product idea into a structured full-stack project blueprint. A fixed sequence of LLM-backed stages produces it, and the stages stream their progress to the browser over Server-Sent Events (SSE).

## Monorepo layout

Bun workspaces and Turborepo. `turbo run build|test|typecheck` builds upstream packages first (`dependsOn: ["^build"]`).

| Path | Role |
|------|------|
| `apps/api` | Express server. Validates requests, creates jobs, runs the pipeline, streams SSE, and serves ZIP download, GitHub push, and add-feature endpoints. |
| `apps/web` | Vite + React dashboard (deployed to Vercel). In dev it proxies `/api` to `localhost:3001`. Has a client-side demo mode that works with no API. |
| `packages/agents` | The pipeline: workflow definitions, `WorkflowEngine`, the `AgentStepExecutor` boundary, LLM providers (OpenRouter, NVIDIA, mock), the cache, and skills. |
| `packages/shared` | Zod schemas and TypeScript types shared by every package: requests, jobs, SSE events, and the blueprint. |
| `packages/ui` | Small React UI primitives used by `apps/web`. |

Dependency direction: `apps/*` → `packages/agents` → `packages/shared`. `packages/shared` depends on nothing internal.

## Request flow

```
POST /api/generate
→ GenerateRequestSchema (zod)
→ job.store.createJob() status: queued
→ runOrchestrator() status: running
selectWorkflow(prompt) fullstack-scaffold | feature-add
WorkflowEngine.run()
for each step: AgentStepExecutor.execute()
currentStage = step.agent
assembleBlueprintFromWorkflow() normalize + defaults
BlueprintSchema.safeParse() reject invalid output
→ job.store.updateJob() status: completed | failed
GET /api/stream/:jobId SSE replay + live events
```

## Pipeline stages

`packages/agents/src/workflow/router.ts` defines two workflows.

| Workflow | Selected when | Stages |
|----------|---------------|--------|
| `fullstack-scaffold` | default | `planner` → `schema` → `api` → `frontend` → `devops` → `reviewer` → `codegen` |
| `feature-add` | prompt contains add/feature/update/modify | `planner` → `schema` → `api` → `frontend` → `devops` |

Setting `execution.enableCodeGeneration: false` removes `codegen`. Stages run strictly in order. Each stage gets the user goal plus a compressed summary of every earlier stage's output (`WorkflowState`), and its full structured output is kept for blueprint assembly.

## The `AgentStepExecutor` boundary

```ts
interface AgentStepExecutor {
execute(request: StepExecutionRequest): Promise<StepExecutionResult>;
}
// request: { jobId, goal, workflow, step, state, emit }
// result: { rawOutput, compressedOutput, tokensUsed }
```

The boundary splits responsibilities between two components:

- **`WorkflowEngine`** (`workflow/engine.ts`) owns ordering and state. It walks the steps, calls the executor, stores `compressedOutput` in state and `rawOutput` for assembly, and sums tokens. It has no knowledge of providers, prompts, or caching.
- **`ProviderStepExecutor`** (`workflow/provider-step-executor.ts`) is the default executor. For one stage it builds the prompt from the skill file, checks the cache, calls the `LLMProvider` with token streaming, validates the output shape, makes one repair call when validation fails, compresses the output for the next stages, and emits the stage's SSE events (`agent_started`, `agent_token`, `agent_complete`, `agent_completed`, `agent_failed`).

You can pass `runOrchestrator({ ..., executor })` to replace step execution, for example to use a deterministic mock in tests or to replay recorded outputs. If you omit `executor`, the default provider-backed path runs.

Failures: when an executor throws, `WorkflowEngine` rethrows the error as `StepExecutionError`, which carries `stage`, `stepId`, and the original message. `apps/api` stores this as `job.failure` and sends it in the `job_failed` SSE payload. A failure outside any stage, such as a token-budget check or blueprint validation, sets `error` but leaves `failure` unset.

## Validation points

| Where | Schema | Effect |
|-------|--------|--------|
| `POST /api/generate` | `GenerateRequestSchema` | 422 when the trimmed prompt is outside 10 to 2000 characters, or the budget is invalid. |
| Each stage | `validateStepOutput` (shape check) | One repair call, then the stage fails. |
| After assembly | `BlueprintSchema` | The job fails with the first schema issues. |
| `POST /api/pipeline/add-feature` | `BlueprintSchema` on `previousOutput` | Rejects a malformed input blueprint. |

## Job state: in-memory by design

`apps/api/src/store/job.store.ts` keeps jobs in a process-local `Map`:

- Statuses: `queued` → `running` → `completed` | `failed`.
- Each job holds `currentStage`, `agentsCompleted`, `error`, `failure`, `blueprint`, and the full SSE event log, which is used to replay events to clients that reconnect.
- Limits: at most 200 jobs, and completed or failed jobs are evicted 1 hour after their last update.

This is intentional for v1. Jobs are short-lived, and users download or push the result to GitHub. Because the store is in memory, jobs are lost on restart, one API instance cannot share jobs with another, and an interrupted run cannot be resumed. Anything that needs durable state should replace this module behind its existing functions (`createJob`, `getJob`, `updateJob`, `appendEvent`, `listJobs`).

## Out of scope for v1: `loop-core`

The `feat/loop-engine` branch contains `packages/loop-core`, a SQLite-backed milestone, gate, and memory engine, and `apps/mcp`, an MCP server that exposes it. That work is a separate product for driving external coding agents. It is not merged into v1 and nothing on `main` depends on it. Phase 2 moves it into its own repository.
135 changes: 62 additions & 73 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,103 +1,85 @@
# StackForge 🏗️

**StackForge** is an AI agent orchestration system designed for full-stack scaffolding.
Users enter a product idea in plain English, and the system coordinates multiple specialized subagents to generate a structured, full-stack project blueprint (and eventually real code).
**StackForge** turns a plain-English product idea into a structured full-stack project blueprint: stack, folder layout, data model, API routes, frontend pages, infra plan, review notes, and optional generated source files. Specialized LLM stages each produce one part, and the web dashboard streams their progress live over Server-Sent Events.

Currently, this repository contains the **Core Backend & Orchestration Layer** (v1), which features a clean provider abstraction, strict Zod validation, and real-time Server-Sent Events (SSE) streaming for agent progress.

The backend runs on **real OpenRouter provider calls** with per-agent token optimization (input compression, output caps, and budget guardrails).
- Web app: https://stackforge-web.vercel.app (it runs in demo mode when no API is configured)
- Architecture: see [ARCHITECTURE.md](./ARCHITECTURE.md)

---

## 🚀 Tech Stack & Tools Needed

Before you begin, ensure you have the following installed on your machine:
## Architecture at a glance

- **[Bun](https://bun.sh/)** (v1.3+): JavaScript runtime, package manager, and test runner.
- **[Turborepo](https://turbo.build/)**: High-performance build system for TypeScript monorepos.
- **Node.js** (v22+): For broad compatibility, though Bun executes the backend.
- **Git**: For version control.
```text
apps/web ──/api──▶ apps/api ──▶ packages/agents ──▶ LLMProvider (OpenRouter | NVIDIA | mock)
(Vite/React) (Express, runOrchestrator
job store, └ WorkflowEngine (ordering, state)
SSE) └ AgentStepExecutor (one stage)
packages/shared: zod schemas + types used everywhere
```

**Monorepo Details:**
- **Language**: TypeScript (Strict Mode)
- **Backend Framework**: Express
- **Realtime**: Server-Sent Events (SSE)
- **Validation & Modeling**: Zod
- **Pipeline:** `planner` → `schema` → `api` → `frontend` → `devops` → `reviewer` → `codegen`. Feature-add prompts run the first five stages, and setting `enableCodeGeneration: false` drops `codegen`.
- **`AgentStepExecutor`:** the interface for running one stage. The default `ProviderStepExecutor` calls the LLM. Tests can pass their own executor to `runOrchestrator`.
- **Job store:** jobs live in memory with a TTL (200 jobs max, evicted 1 hour after finishing). Each job records `currentStage` and, when a stage fails, a structured `failure` (`stage`, `stepId`, `message`). Jobs do not survive a restart.

---

## 🛠️ Installation & Setup

1. **Clone the repository:**
```bash
git clone https://github.com/7vignesh/stackforge.git
cd stackforge
```

2. **Install dependencies:**
Bun handles all workspace linking seamlessly:
```bash
bun install
```
*(This will also set up Husky pre-commit hooks automatically).*

3. **Start the API Server (Development Mode):**
```bash
cd apps/api
bun run dev
```
*The server will start on http://localhost:3001.*

4. **Run the Interactive Demo:**
To see the AI orchestration pipeline stream its results in real-time, open a **second terminal** and run:
```bash
bun run scripts/demo.ts
```
*You can also pass a custom prompt:*
```bash
bun run scripts/demo.ts --prompt "Build a CRM for real estate agents with PostgreSQL"
```
## Requirements

---
- [Bun](https://bun.sh/) 1.3+ (runtime, package manager, test runner)
- Git

## 🧪 Testing
The stack is TypeScript (strict mode), Express, React + Vite, Zod, and Turborepo.

The repository uses Bun's incredibly fast, built-in native test runner (`bun:test`).
---

## Setup

**Run the API Integration Tests:**
```bash
cd apps/api
bun test
git clone https://github.com/7vignesh/stackforge.git
cd stackforge
bun install
cp apps/api/.env.example apps/api/.env # optional: add OpenRouter keys
```

**Run Tests Across the Entire Monorepo:**
With no API keys set, the API uses the deterministic mock provider (`STACKFORGE_PROVIDER=auto`).

## Run locally

```bash
bun run test
bun run api:dev # API on http://localhost:3001
cd apps/web && bun run dev # web on http://localhost:5173 (proxies /api to :3001)
bun run dev # or start every package's dev task through Turbo
```
*Turborepo will execute the `"test"` script in every package and cache the results.*

### Pre-commit Hooks (Husky)
To ensure the repository remains stable, a git pre-commit hook is fully configured.
Whenever you run `git commit`, the system automatically runs:
- `turbo run typecheck`: Type-checks all packages without emitting files (`tsc --noEmit`).
- `turbo run test`: Runs the test suites.
To stream a run in the terminal, start the API and then run:

If any of these fail, the commit is aborted.
```bash
bun run scripts/demo.ts
bun run scripts/demo.ts --prompt "Build a CRM for real estate agents with PostgreSQL"
```

## Test, typecheck, build

```bash
bun run typecheck # tsc --noEmit in every package
bun run test # bun test in apps/api and packages/agents
bun run build # tsc for packages and api, vite build for web
```

### Monorepo Structure & Ownership
CI (`.github/workflows/ci.yml`) runs these three commands on every push to `main` and on every pull request. No API keys are needed for any of them.

## Repository layout

```text
apps/
api/ # Primary Backend (Express + Orchestrator bridge)
web/ # Frontend Web App (React/Next.js stub)

api/ Express API: generate, jobs, SSE stream, download, GitHub push, add-feature
web/ Vite + React dashboard (deployed to Vercel)
packages/
agents/ # Core Orchestration, 6 Subagents, OpenRouter provider, token optimizer
shared/ # Zod Schemas, Constant Enums, and TS Contract Types
ui/ # Reusable UI primitives stub
config/ # ESLint/TSConfig stubs
agents/ Pipeline, WorkflowEngine, AgentStepExecutor, providers, cache, skills
shared/ Zod schemas and types (requests, jobs, SSE events, blueprint)
ui/ Shared React UI primitives
scripts/
demo.ts Terminal SSE demo client
```

---
Expand All @@ -108,7 +90,7 @@ Set these variables in `apps/api/.env`:

```bash
STACKFORGE_PROVIDER=openrouter
OPENROUTER_API_KEY=your_key_here
OPENROUTER_API_KEY=your_key_here # or OPENROUTER_API_KEY_1/_2/_3 for key rotation
OPENROUTER_ENDPOINT=https://openrouter.ai/api/v1/chat/completions
OPENROUTER_APP_NAME=stackforge-api
OPENROUTER_APP_URL=http://localhost:3001
Expand Down Expand Up @@ -141,4 +123,11 @@ Per-agent tuning lives in `packages/agents/src/config/agent.configs.ts`.
3. Lower `maxInputTokens` or raise `compressionLevel` for agents with high `inputTokens`.
4. Lower `maxOutputTokens` for agents with consistently low `outputTokens`.
5. Raise `minOutputTokens` only if quality drops from over-compression.
6. Adjust `tokenBudget` to set overall cost/quality tradeoff for the entire orchestration.
6. Adjust `tokenBudget` to set overall cost/quality tradeoff for the entire orchestration.

---

## Roadmap

- **v1 (this release):** a 7-stage blueprint pipeline, the `AgentStepExecutor` boundary, step-level failure reporting, and an in-memory job store.
- **Phase 2:** the loop engine (`packages/loop-core` and `apps/mcp` on the `feat/loop-engine` branch) is intentionally kept out of v1. It will be extracted into its own repository. `main` has no dependency on it.
Loading