Skip to content
AiatullaPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Forge

Forge is a locally hosted scaffolding engine with a visual dashboard. You describe an idea, negotiate the architecture with an AI orchestrator in a chat, approve a generated blueprint, and then a DAG of AI worker agents writes a complete Next.js + FastAPI codebase to disk. It runs on the Gemini API, keeps all state on your machine (SQLite + ChromaDB + plain files), and ships AI rules files alongside every generated project so the context survives when you open it in another editor.

Full product spec: forge/docs/PRD.md.


Table of contents

  1. What Forge does
  2. Architecture
  3. Tech stack
  4. Repository layout
  5. Setup
  6. Running Forge
  7. The generation workflow
  8. Agent system
  9. The DAG
  10. RAG component injection
  11. Data model
  12. HTTP API reference
  13. WebSocket API reference
  14. JSON contracts
  15. Frontend
  16. Generated project layout
  17. Template and agent rules files
  18. Helper scripts
  19. Configuration reference
  20. Known issues and rough edges

1. What Forge does

Forge turns a one-paragraph idea into a running full-stack project in four phases.

  • Ideation. You chat with an Orchestrator agent over a WebSocket. It streams responses and pushes you toward concrete features, data models, endpoints, and pages. When you are satisfied, Forge distills the conversation into an Architecture Decision Record (ADR) in Markdown.
  • Blueprint. The ADR is parsed into a strict GenerationBlueprint JSON schema (pages, backend domains, design tokens, auth strategy). Forge then deterministically compiles a task DAG from that blueprint - the LLM does not get to invent the task graph.
  • Generation. A dispatcher walks the DAG, running every unblocked task concurrently through asyncio.gather. Each task is one worker agent producing one file. Progress and per-agent logs stream to the dashboard over a WebSocket.
  • Review and fix. A Reviewer agent reads the whole generated tree and emits a JSON conflict report; a Synthesizer agent rewrites the offending files. Afterwards you can browse the file tree, regenerate individual pages with feedback, fix individual files with feedback, extend the project with new features, or export a ZIP.

Everything is local. The only network dependency is the Gemini API.


2. Architecture

┌──────────────────────────────────────────────────────────┐
│                   FORGE DASHBOARD                        │
│                Next.js - localhost:3000                  │
│  Ideation chat | Blueprint | Generation DAG              │
│  UI Pass       | Files + Fix mode | Settings             │
└───────────────────────┬──────────────────────────────────┘
                        │ REST + WebSocket
┌───────────────────────▼──────────────────────────────────┐
│                    FORGE ENGINE                          │
│                FastAPI - localhost:8000                  │
│  DAGEngine | Dispatcher | ConnectionManager              │
│  13 worker agents | File writer                          │
└──────┬─────────────────────┬─────────────────┬───────────┘
       │                     │                 │
┌──────▼──────┐   ┌──────────▼───────┐  ┌──────▼──────────┐
│  SQLITE     │   │   CHROMADB       │  │  FILESYSTEM     │
│  projects   │   │  ui_components   │  │  forge-data/    │
│  tasks      │   │  embeddings      │  │  generated/     │
└─────────────┘   └──────────────────┘  └─────────────────┘
       │
┌──────▼───────────────────────────────────────────────────┐
│                     GEMINI API                           │
│   gemini-2.5-pro (orchestration) / 2.5-flash (workers)   │
│           text-embedding-004 (RAG embeddings)            │
└──────────────────────────────────────────────────────────┘

Request path for a generation run:

  1. POST /api/projects/{id}/generation/start reads architecture.md from disk.
  2. OrchestratorAgent.generate_blueprint calls Gemini with a JSON schema and returns a GenerationBlueprint.
  3. Forge appends a deterministic list of DAGTask objects to the blueprint and writes blueprint.json.
  4. A Dispatcher is constructed and launched with asyncio.create_task, so the HTTP call returns immediately.
  5. DAGEngine.get_ready_tasks() yields every pending task whose dependencies are all resolved. The dispatcher marks them running, broadcasts state, and awaits them together.
  6. Each worker calls Gemini, strips Markdown fences from the response, and writes a file under forge-data/generated/{project_id}/.
  7. Every state change and worker log is broadcast to all WebSocket clients subscribed to that project.

3. Tech stack

Forge itself

Layer Choice
Dashboard Next.js 16 (App Router), React 19, TypeScript 5
Styling Tailwind CSS 4, shadcn/ui (base-nova style), tw-animate-css
Client state TanStack Query 5 (server state), Zustand 4 (UI state)
UI extras framer-motion, lucide-react, react-markdown + remark-gfm, next-themes
Engine FastAPI 0.111, Python 3.11+, Uvicorn
ORM SQLAlchemy 2.0 async + aiosqlite
Validation Pydantic v2, pydantic-settings
Vector store ChromaDB (PersistentClient, no Docker)
LLM SDK google-genai 0.3.0
Realtime Native FastAPI WebSockets

Default stack Forge generates

Next.js 14 App Router + TypeScript + Tailwind + shadcn/ui on the frontend; FastAPI + SQLAlchemy 2.0 + Pydantic v2 on the backend; SQLite by default; NextAuth.js for auth. These defaults are editable in the Settings page.


4. Repository layout

forge-ai/
├── README.md                     ← this file
├── test_curl.py                  ← manual smoke test: POST generation/start
├── test_fastapi.py               ← manual smoke test: same call via ASGITransport
├── test_gemini.py                ← manual smoke test: Gemini key + generate_text
├── test_schema.py                ← reproduces the google-genai nested-schema bug
│
└── forge/
    ├── CLAUDE.md                 ← master rules for Claude Code (template)
    ├── GEMINI.md                 ← master rules for Gemini CLI (template)
    ├── DESIGN.md                 ← design token placeholder (fill per project)
    ├── DOCS.md                   ← project description placeholder (fill per project)
    ├── plan.md                   ← the setup prompt that generated this template
    ├── docs/PRD.md               ← full product requirements document
    │
    ├── agents/                   ← Markdown agent definitions for editor-based agents
    │   ├── ORCHESTRATOR.md
    │   ├── AGENT_PLANNER.md
    │   ├── AGENT_FRONTEND.md
    │   ├── AGENT_BACKEND.md
    │   ├── AGENT_DATABASE.md
    │   └── AGENT_REVIEWER.md
    │
    ├── scripts/
    │   ├── scan-context.sh       ← inventory of existing components and modules
    │   ├── task.sh               ← run a task with context auto-injected
    │   ├── review.sh             ← run the reviewer agent on a file or diff
    │   ├── new-task.md           ← task template
    │   └── index_components.py   ← index rag-library/ into ChromaDB
    │
    ├── rag-library/              ← source components indexed for RAG
    │   └── shadcn-blocks/FancyHero.tsx
    │
    ├── forge-data/               ← runtime state (gitignored in practice)
    │   ├── chroma/               ← ChromaDB persistent store
    │   ├── projects/{id}/_config ← architecture.md, blueprint.json
    │   ├── generated/{id}/       ← generated project files
    │   ├── exports/              ← ZIP exports
    │   └── settings.json
    │
    ├── backend/
    │   ├── requirements.txt
    │   ├── test_ws.py            ← manual smoke test for the chat WebSocket
    │   └── app/
    │       ├── main.py           ← FastAPI app, CORS, router mounting
    │       ├── core/
    │       │   ├── config.py     ← pydantic-settings + .env loading
    │       │   └── database.py   ← async engine, session factory, Base
    │       ├── models/           ← SQLAlchemy ORM models
    │       ├── schemas/          ← Pydantic request/response schemas
    │       ├── api/              ← routers: projects, generation, ws, fix, settings
    │       ├── orchestrator/     ← schemas.py, dag.py, dispatcher.py
    │       ├── agents/           ← LLM client + 13 worker agents
    │       └── rag/              ← ChromaDB client and query helpers
    │
    └── frontend/
        ├── app/                  ← Next.js App Router pages
        ├── components/ui/        ← shadcn/ui primitives
        ├── components/layouts/   ← ForgeShell (sidebar + nav)
        ├── queries/              ← TanStack Query hooks + fetch client
        ├── stores/ui.ts          ← Zustand UI store
        └── lib/                  ← utils and fake-data types

5. Setup

Prerequisites

Backend

cd forge-ai
python -m venv .venv
source .venv/bin/activate
pip install -r forge/backend/requirements.txt

Create forge/env/.env (this exact path is what core/config.py loads, and it is gitignored):

GEMINI_API_KEY=your_key_here

You can also paste the key into the dashboard Settings page, which writes it to forge-data/settings.json and sets os.environ["GEMINI_API_KEY"] for the running process.

Verify the key works:

python test_gemini.py     # should print: Gemini Response: WORKING

Frontend

cd forge/frontend
npm install

RAG index (optional but recommended)

Drop .tsx component files into forge/rag-library/<source-name>/, then:

python forge/scripts/index_components.py

This embeds each file with text-embedding-004 and upserts it into the ui_components ChromaDB collection in batches of 5. Read known issues first: the indexer and the query path currently resolve different forge-data directories.


6. Running Forge

From the repository root:

make install    # pip deps into .venv (if present) plus npm install
make up         # engine on :8000 and dashboard on :3000, Ctrl-C stops both

make up is the whole story. It picks .venv/bin/python when that venv exists and falls back to python3, sets FORGE_DATA_DIR=forge/forge-data so runtime state lands inside the repo, and exports NEXT_PUBLIC_API_URL / NEXT_PUBLIC_WS_URL pointing at 127.0.0.1:$(BACKEND_PORT) so the dashboard talks to the engine you just started.

Overridable variables:

BACKEND_PORT=8010 make up          # if something else owns :8000
PYTHON=python3.12 make install     # different interpreter
FORGE_DATA_DIR=/tmp/forge make up  # different state directory

make backend and make frontend run either half alone.

The equivalent manual commands, run from the repository root so that forge.backend.app is importable:

FORGE_DATA_DIR=forge/forge-data .venv/bin/python -m uvicorn forge.backend.app.main:app --reload --port 8000
cd forge/frontend && npm run dev

FORGE_DATA_DIR defaults to ../forge-data, which is relative to the working directory and will not point at forge/forge-data when you launch from the repository root. Set it explicitly, or launch from forge/backend with PYTHONPATH set to the repository root.

Use 127.0.0.1, not localhost, when curling the engine. localhost resolves to ::1 first, and Uvicorn binds IPv4 only, so anything else holding *:8000 (a Docker container, for example) answers instead.

On startup the app runs Base.metadata.create_all, so the SQLite schema is created automatically. There are no migrations to run for v1, despite Alembic being in requirements.txt.

Dashboard:

cd forge/frontend
npm run dev

Open http://localhost:3000. CORS on the engine allows localhost:3000 and localhost:3001 only.

The frontend reads NEXT_PUBLIC_API_URL and falls back to http://localhost:8000/api.


7. The generation workflow

Phase 1 - Ideation

Open a project and go to Ideation. The page opens a WebSocket to /api/ws/projects/{id}/chat. On connect, the server seeds the history with the project name and description, then replays it as a history frame. Every user message is appended to an in-memory history and streamed back through OrchestratorAgent.chat_stream as chunk frames, terminated by a done frame.

Chat history lives in a module-level dict (active_chats) and is lost when the engine restarts. If that happens, blueprint generation silently falls back to just the project name and description.

Clicking Finalize calls POST /api/projects/{id}/blueprint/generate, which asks Gemini for a Markdown ADR covering stack, architecture, endpoints, auth, and folder structure, writes it to forge-data/projects/{id}/_config/architecture.md, and moves the project to blueprint status.

Phase 2 - Blueprint

The Blueprint page renders architecture.md with react-markdown and shows a predicted file tree derived from blueprint.json. Clicking Start generation calls POST /api/projects/{id}/generation/start, which:

  1. Reads the ADR.
  2. Calls generate_blueprint to extract pages, backend domains, design tokens, and auth strategy into a GenerationBlueprint.
  3. Compiles the DAG deterministically in Python.
  4. Writes blueprint.json.
  5. Sets project status to generating and fires the dispatcher as a background task.

Phase 3 - Generation

The Generation page opens a WebSocket to /api/ws/projects/{id}/generation and renders the live DAG plus a rolling agent log. The dispatcher broadcasts dag_state frames (per-node status, duration, overall progress) and worker_log frames (timestamped per-agent messages).

Each task retries up to 3 times with exponential backoff (1s, 2s). After the third failure the node is marked failed. Failed dependencies do not block downstream tasks - get_ready_tasks treats failed the same as done, so the pipeline always drains rather than deadlocking on one bad node.

Phase 4 - Review and iterate

  • UI Pass shows a page picker built from the blueprint, polls the generated page.tsx every 5 seconds, and lets you send freeform feedback that dispatches a single-page regeneration.
  • Files shows the full generated tree, opens any file, and offers Fix mode: describe what is wrong and the file is rewritten in place, returning a before/after pair for diffing.
  • Extend (POST /api/projects/{id}/generation/extend) generates a delta-only blueprint. Existing files are passed to the model as read-only context and only new pages and domains produce tasks.
  • Export (POST /api/projects/{id}/export) zips the generated tree into forge-data/exports/.

8. Agent system

All agents subclass Agent from app/agents/base.py and receive an LLMClient. LLMClient is an abstract interface with three methods (generate_text, generate_structured, stream_chat), and GeminiClient is the only implementation.

GeminiClient maps a friendly model name to a Gemini model: "pro" becomes gemini-2.5-pro, everything else becomes gemini-2.5-flash. Structured generation injects the JSON schema into the prompt text and requests application/json rather than using the SDK's response_schema parameter, because that parameter chokes on the $ref/$defs produced by nested Pydantic models. test_schema.py reproduces the original failure.

Orchestrator tier

Agent Role
OrchestratorAgent Streams the ideation chat, converts the ADR into a GenerationBlueprint, compiles the DAG, and builds delta blueprints for extend mode.

Worker tier

Agent Input Output
ComponentMapAgent blueprint pages semantic component requirements per page (frontend/_config/component_map.json)
DesignTokenAgent blueprint color, typography, spacing, radius tokens (frontend/_config/design.json)
DBSchemaAgent one backend domain backend/models/{domain}.py (SQLAlchemy model)
APIWriterAgent one backend domain backend/api/{domain}.py (FastAPI router)
ServiceAgent one backend domain backend/services/{domain}_service.py
UIPageAgent one page + design tokens + RAG hits frontend/app/{route}/page.tsx
OpenAPIAgent generated backend backend/openapi.json and frontend/types/api.d.ts
IntegrationAgent generated frontend and backend frontend/queries/api.ts and frontend/stores/app-store.ts
ReviewerAgent every generated .py, .ts, .tsx _config/review_report.json conflict list
SynthesizerAgent review report + offending files rewritten files in place
TestingAgent generated backend backend/tests/test_api.py
DocsAgent generated tree PROJECT_CONTEXT.md
RulesAgent PROJECT_CONTEXT.md + tree .cursorrules, .windsurfrules, .github/copilot-instructions.md, CLAUDE.md, GEMINI.md

OpenAPIAgent is the only worker that does not call the LLM. It writes a throwaway extraction script into the generated backend, runs it in a subprocess with a 10 second timeout to dump app.openapi(), then shells out to npx openapi-typescript with a 15 second timeout. Both failures are swallowed and logged, because a generated backend with a syntax error must not take down the pipeline.

Most workers post-process the LLM response by stripping leading ```tsx, ```python, ```json, or bare ``` fences and a trailing fence before writing the file.


9. The DAG

OrchestratorAgent.generate_blueprint builds the task graph in Python, not in the model. The layers:

Layer 1  task_comp_map (ComponentMapAgent)     no deps
         task_design   (DesignTokenAgent)      no deps
         task_db_{domain}   (DBSchemaAgent)    no deps, one per backend domain

Layer 2  task_api_{domain}  (APIWriterAgent)   deps: task_db_{domain}
         task_svc_{domain}  (ServiceAgent)     deps: task_db_{domain}
         task_ui_{page}     (UIPageAgent)      deps: task_comp_map, task_design

Layer 2.5 task_openapi      (OpenAPIAgent)     deps: all api + service tasks

Layer 3  task_integration   (IntegrationAgent) deps: task_openapi + all UI tasks

Layer 4  task_reviewer      (ReviewerAgent)    deps: task_integration

Layer 5  task_synthesizer   (SynthesizerAgent) deps: task_reviewer

Layer 6  task_testing       (TestingAgent)     deps: task_synthesizer
         task_docs          (DocsAgent)        deps: task_synthesizer
         task_rules         (RulesAgent)       deps: task_synthesizer

DAGEngine (app/orchestrator/dag.py) holds status, per-task durations, and start times. Statuses are pending, running, done, failed, blocked. get_state() returns the shape the dashboard expects: {progress, nodes: {id: {status, duration}}, is_complete}.

The delta DAG used by extend mode is flatter: one UIPageAgent task per new page, one APIWriterAgent task per new domain, then integration, reviewer, and synthesizer chained behind all of them.


10. RAG component injection

The point of RAG here is output quality. An LLM asked to write a data table from memory produces a tutorial-grade table; an LLM handed a real production component and told to adapt it produces something closer to shippable.

Flow:

  1. index_components.py walks rag-library/**/*.tsx, wraps each file as Component Name: X\nSource Library: Y\nCode:\n{code}, embeds it with text-embedding-004, and upserts it into the ui_components collection with component_name, source, and filepath metadata.
  2. ComponentMapAgent decides, per page, which 1 to 4 semantic UI patterns that page needs ("interactive data table with column filters", "bento grid dashboard layout").
  3. UIPageAgent passes those phrases to query_components(), which queries ChromaDB and rejects any hit whose cosine distance exceeds 0.75. A bad match is worse than no match.
  4. Surviving hits are inlined into the generation prompt under --- REFERENCE COMPONENTS (ADAPT THESE) --- with an explicit instruction to reuse the structure but never copy the reference data verbatim.

query_components failures (collection missing, Chroma error) are caught and return an empty list, so page generation degrades to plain generation rather than failing.


11. Data model

Two SQLAlchemy tables in SQLite. Everything else lives on the filesystem.

projects

Column Type Notes
id String PK proj_ + 12 hex chars
name String indexed
description String nullable
status String ideation, blueprint, generating, complete, error
techStack JSON list of strings
pagesCount Integer
endpointsCount Integer
authStrategy String defaults to TBD
created_at / updated_at DateTime updated_at auto-updates

generation_tasks

Column Type Notes
id String PK e.g. task_ui_dashboard
project_id String FK cascade delete
status String pending, running, done, failed, blocked
agent_type String
model String defaults to Flash
output / error Text nullable
duration_ms / tokens_used String nullable
started_at / completed_at DateTime nullable

generation_tasks is defined and created but the live dispatcher keeps DAG state in memory and broadcasts it, rather than persisting rows. Restarting the engine mid-run loses run state.

Filesystem state

forge-data/
├── settings.json
├── chroma/
├── projects/{project_id}/_config/
│   ├── architecture.md            ← the ADR
│   ├── blueprint.json             ← GenerationBlueprint including dag_tasks
│   └── delta_blueprint.json       ← extend mode only
├── generated/{project_id}/        ← the actual generated project
│   └── _config/review_report.json
└── exports/{name}_export.zip

12. HTTP API reference

Base path: /api. Interactive docs at /api/docs.

Health

Method Path Description
GET /api/health {status, project}

Projects

Method Path Description
GET /api/projects List all projects, newest updated first
POST /api/projects Create a project. Returns 201
GET /api/projects/{id} Fetch one project
PATCH /api/projects/{id} Partial update
DELETE /api/projects/{id} Delete. Returns 204
GET /api/projects/{id}/code?route= Raw page.tsx for one route, or a placeholder comment if not generated yet
GET /api/projects/{id}/files Flat file list with path, size, extension
GET /api/projects/{id}/file-content?path= Raw file content. Path traversal is blocked with a realpath prefix check
POST /api/projects/{id}/export ZIP the generated tree into forge-data/exports/

Generation

Method Path Description
POST /api/projects/{id}/blueprint/generate Turn the ideation chat into architecture.md
GET /api/projects/{id}/blueprint Return the ADR Markdown
GET /api/projects/{id}/blueprint/json Return the parsed blueprint.json
POST /api/projects/{id}/generation/start Compile the DAG and launch the dispatcher
POST /api/projects/{id}/generation/regenerate-page Body {route, feedback}. Re-runs UIPageAgent for one route with the feedback injected as USER_FEEDBACK_OVERRIDE
POST /api/projects/{id}/generation/extend Body {description}. Delta-only generation for new features

Fix

Method Path Description
POST /api/projects/{id}/fix Body {path, feedback}. Rewrites one file and returns {status, path, diff_before, diff_after}

The agent persona is picked from the file extension: .tsx/.jsx/.ts/.js/.css gets a frontend prompt, .py gets a backend prompt, anything else gets a general one.

Settings

Method Path Description
GET /api/settings Current settings plus a masked API key (gemini_api_key_masked)
POST /api/settings Persist settings to forge-data/settings.json and update the runtime key

Settings fields: gemini_api_key, default_frontend, default_backend, default_database, default_auth, default_styling, backend_port. The GET response masks the key as first8...last4, but the stored gemini_api_key field is also returned in full, so treat this endpoint as trusted-local only.


13. WebSocket API reference

/api/ws/projects/{project_id}/chat

Client sends {"content": "..."} (a bare string also works). Server frames:

type Payload
history array of {id, role, content, timestamp} sent once on connect
status "typing"
chunk one streamed token span
done empty, marks end of the assistant turn
error error text

/api/ws/projects/{project_id}/generation

Read-only from the client's perspective. Server frames:

type Payload
dag_state {progress, nodes: {taskId: {status, duration}}, is_complete}
worker_log {timestamp, agent, message, type} where type is info, success, or error

ConnectionManager keeps a list of sockets per project id and drops any socket that raises on send.


14. JSON contracts

Defined in app/orchestrator/schemas.py. These are the interfaces between tiers.

GenerationBlueprint - orchestrator to DAG engine.

project_name: str
description: str
auth_strategy: str
database: str
design_tokens: dict
pages: list[PageDependency]           # id, route, title, components_needed, data_dependencies
backend_domains: list[BackendDomain]  # name, model_fields, endpoints
dag_tasks: list[DAGTask]              # id, agent, depends_on, target_page, target_domain

MicroTask - DAG engine to worker.

task_id: str
agent_type: str
file_to_create: str | None
description: str
page_data: dict | None        # the page or domain payload for this task
design_tokens: dict | None
rag_components: list[str] | None
constraints: list[str] | None
output_format: dict | None

WorkerOutput - worker result envelope.

task_id: str
status: str                   # 'success' | 'error'
file_path: str | None
file_content: str | None
error_message: str | None
metadata: WorkerMetadata | None   # imports_used, components_created,
                                  # typescript_interfaces, tokens_used, model, duration_ms

Note that ModelField.field_type and BackendDomain.model_fields are named to avoid Pydantic v2's protected model_ namespace collisions and its reserved type handling.


15. Frontend

App Router pages:

Route File Purpose
/ app/page.tsx Project grid, create, delete
/settings app/settings/page.tsx API key and default stack profile
/projects/[id]/ideation ideation chat over WebSocket, finalize into an ADR
/projects/[id]/blueprint ADR rendering, predicted file tree, start generation
/projects/[id]/generation live DAG visualization and agent log
/projects/[id]/ui-pass per-page code preview with regeneration feedback
/projects/[id]/files full file tree, file viewer, fix mode

components/layouts/forge-shell.tsx provides the sidebar, project switcher, and the five-item section nav (Ideation, Blueprint, Generation, UI Pass, Files).

queries/client.ts holds the fetcher wrapper (JSON headers, 204 handling, throws on non-ok). queries/projects.ts exposes the hooks: useProjects, useProject, useCreateProject, useUpdateProject, useDeleteProject, useBlueprint, useBlueprintJson, useGenerateBlueprint, useStartGeneration, useProjectCode, useRegeneratePage, useFileTree, useFileContent, useFixFile.

useProjectCode polls every 5 seconds so the UI Pass preview picks up freshly written files without manual refresh.

stores/ui.ts is a small Zustand store for sidebar collapse and active project id. lib/fake-data.ts still supplies TypeScript types (Project, ChatMessage, FileNode, AgentStatus) and status colors that the live pages import, plus leftover seed data from the Stage 0 hardcoded UI.


16. Generated project layout

Everything a worker writes lands under forge-data/generated/{project_id}/:

generated/{project_id}/
├── frontend/
│   ├── app/{route}/page.tsx        ← UIPageAgent
│   ├── queries/api.ts              ← IntegrationAgent
│   ├── stores/app-store.ts         ← IntegrationAgent
│   ├── types/api.d.ts              ← OpenAPIAgent (via openapi-typescript)
│   └── _config/design.json         ← DesignTokenAgent
│       _config/component_map.json  ← ComponentMapAgent
├── backend/
│   ├── models/{domain}.py          ← DBSchemaAgent
│   ├── api/{domain}.py             ← APIWriterAgent
│   ├── services/{domain}_service.py← ServiceAgent
│   ├── tests/test_api.py           ← TestingAgent
│   └── openapi.json                ← OpenAPIAgent
├── _config/review_report.json      ← ReviewerAgent
├── PROJECT_CONTEXT.md              ← DocsAgent
├── CLAUDE.md                       ← RulesAgent
├── GEMINI.md                       ← RulesAgent
├── .cursorrules                    ← RulesAgent
├── .windsurfrules                  ← RulesAgent
└── .github/copilot-instructions.md ← RulesAgent

The rules files are the "context inoculation" step: the generated project carries its own conventions, so opening it in Cursor, Windsurf, Copilot, Claude Code, or Gemini CLI gives the same rules without re-explaining the architecture.


17. Template and agent rules files

forge/ doubles as a reusable agentic template for humans working with editor-based AI agents. That is what plan.md set up and what CLAUDE.md and GEMINI.md enforce.

  • CLAUDE.md / GEMINI.md - master rules. Mandatory pre-flight (read DOCS.md, read DESIGN.md, run scan-context.sh, read the relevant agent file, write acceptance criteria), non-negotiable rules (no duplicate components, no hardcoded colors, no business logic in route handlers, 200 line file cap, typed props, Pydantic schemas everywhere), and a self-check list.
  • DOCS.md and DESIGN.md are deliberate placeholders. Agents are instructed to refuse work while they are empty rather than invent a design system.
  • agents/*.md define the roles: ORCHESTRATOR routes, AGENT_PLANNER decomposes, and AGENT_FRONTEND, AGENT_BACKEND, AGENT_DATABASE, AGENT_REVIEWER execute.

The design premise, spelled out in plan.md, is that AI ignores rules for five reasons: rules are too vague, rules are not in context, there is no component inventory so duplicates get created, design tokens are never injected so colors get invented, and there are no acceptance criteria so quality checking stops early. Every file in the template targets at least one of those.


18. Helper scripts

Target Usage
make install Install Python and npm dependencies
make up Start engine and dashboard together, Ctrl-C stops both
make backend Engine only
make frontend Dashboard only
Script Usage
scripts/scan-context.sh Prints an inventory of shadcn primitives, custom components, routes, and backend modules. Honors FRONTEND_DIR and BACKEND_DIR env vars
scripts/task.sh "task" Runs a task with context auto-injected. Flags: -f/--file, -a/--agent, -m/--model, --claude. Env: AGENT, GEMINI_MODEL, AI_TOOL
scripts/review.sh <file> Runs the reviewer agent. Also --diff (staged changes) and --last (last commit)
scripts/new-task.md Template for writing a task brief
scripts/index_components.py Builds the ChromaDB RAG index from rag-library/

Root-level test_*.py files are manual smoke scripts, not a pytest suite:

  • test_gemini.py - verifies the API key and a round trip.
  • test_gemini_structured.py - verifies structured JSON generation.
  • test_schema.py - reproduces the google-genai nested-schema failure that forced prompt-injected schemas.
  • test_fastapi.py / test_curl.py - hit generation/start in-process and over HTTP. Both hardcode a project id you will need to change.
  • forge/backend/test_ws.py - connects to the chat WebSocket and exchanges two frames.

19. Configuration reference

app/core/config.py loads forge/env/.env and then reads settings.

Setting Default Meaning
PROJECT_NAME Forge Engine API FastAPI title
DATABASE_URL sqlite+aiosqlite:///forge.db Declared but unused. database.py builds its own URL from FORGE_DATA_DIR
GEMINI_API_KEY None Required for every LLM and embedding call
FORGE_DATA_DIR ../forge-data Root for all runtime state. Relative to the working directory

Frontend:

Variable Default
NEXT_PUBLIC_API_URL http://localhost:8000/api

20. Known issues and rough edges

These are real, present in the code, and worth knowing before you extend it.

  1. FORGE_DATA_DIR is working-directory relative. The default ../forge-data only resolves to forge/forge-data if you launch from forge/backend. Launching from the repository root silently creates a sibling forge-data outside the repo. Set it explicitly.
  2. The RAG index and the RAG query resolve different directories. scripts/index_components.py writes to forge/forge-data/chroma, while app/rag/client.py computes forge-ai/forge-data/chroma from __file__. Queries will not find what the indexer wrote until these agree.
  3. ComponentMapAgent.run and DesignTokenAgent.run reference an undefined kwargs. Both build their WorkerOutput with kwargs.get("task_id", ...) but neither signature accepts **kwargs, so a successful LLM call raises NameError. Both also return a WorkerOutput instead of writing to disk, unlike every other worker, so design.json and component_map.json are never persisted. Since these two are Layer 1 dependencies of every UI task, this is the highest-value fix in the repo.
  4. model="gemini-2.5-pro" does not select Pro. _get_model_name only matches the literal string "pro"; anything else falls through to gemini-2.5-flash. The agents that ask for Pro get Flash.
  5. Chat history is in-memory only. active_chats is a module-level dict. An engine restart discards the ideation conversation, and blueprint generation quietly falls back to the project description.
  6. DAG state is not persisted. The generation_tasks table exists but the dispatcher never writes to it. A restart mid-generation loses all run state and the dashboard has nothing to reconnect to.
  7. GET /api/settings returns the unmasked key. It adds gemini_api_key_masked but does not remove gemini_api_key from the payload.
  8. The RAG embedding function reads os.environ["GEMINI_API_KEY"] directly rather than going through settings. A key supplied only via forge/env/.env reaches settings but not os.environ, so RAG queries can fail while everything else works.
  9. The sys.path.insert in main.py points one level too high (it resolves to the parent of the repository, not the repository). Imports work because the working directory is on sys.path, not because of that line.
  10. Reviewer context is truncated. Each file is cut at 2000 characters and the combined prompt at 20000, so large projects get a partial review.
  11. No test suite. The test_*.py files are manual scripts with hardcoded project ids. There is no pytest configuration, and Alembic is a dependency with no migrations.
  12. DESIGN.md and DOCS.md are still empty placeholders in this repository, which by the template's own rules means agents should refuse frontend work until they are filled in.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages