# @dreamtree-org/ai-builder

> Scaffold a complete, working full-stack **multi-tenant SPA** in one command —
> Express API + Vite/React client, pre-wired to
> [`@dreamtree-org/korm-js`](https://www.npmjs.com/package/@dreamtree-org/korm-js)
> (data) and [`@dreamtree-org/twreact-ui`](https://www.npmjs.com/package/@dreamtree-org/twreact-ui)
> (UI), with module-driven RBAC, row-level grants, and CSS-variable theming.

`ai-builder` is an **AI-native CLI** with these jobs:

- **`ai-builder <app-name>`** — scaffold a complete app on disk, then get out of the way.
- **`ai-builder init --ai <provider>`** — install an app-building **skill pack + MCP** into any project.
- **`ai-builder update`** — check for a newer version and re-sync the installed skill pack + MCP to it.
- **`ai-builder mcp`** — run a zero-dependency, read-only MCP server: the build rules, data contract and module catalog, plus **where your project is right now** (`project_state`) and **your installed libraries' real APIs** (`layer_docs`).

It is **not** a runtime framework and does not own your app after generation.
Targets apps that don't need SEO (client-rendered SPA, no SSR).

**Aim:** _vibe coding with minimal tokens, world-class consistent output, proper SDLC_ —
an assistant fetches the contract/catalog/rules live instead of re-reading files.
**Motto:** _One module registry, one data contract, one component library — zero
hand-rolled CRUD, zero duplicated UI._

---

## About the Company

`@dreamtree-org/ai-builder` is built and maintained under **[Dreamtree Global](http://dreamtreeglobal.com/)** — a team crafting thoughtful, developer-first software for the modern web. We believe great products start with a great foundation, and that's exactly what this builder aims to be: a fast, consistent, AI-native way to ship full-stack multi-tenant apps.

🌐 **Website:** [dreamtreeglobal.com](http://dreamtreeglobal.com/)

## Author & Maintainer

**Partha Preetham Krishna M L**
📧 [preetham.krishna.dev@gmail.com](mailto:preetham.krishna.dev@gmail.com)

Have an idea, a bug, or just want to say hi? Reach out anytime — feedback from developers like you is what keeps this project growing.

## 💚 Sponsor & Support

`@dreamtree-org/ai-builder` is **free and open source**, built in the open and powered entirely by passion and late nights. Every app it scaffolds — every wired-up RBAC gate, module registry, KORM data contract, and MCP tool — represents hours of careful craft so that *your* team can ship faster and build consistently.

If this builder has saved you time, sparked an idea, or made your stack a little saner, please consider supporting its continued development. **Your sponsorship keeps the updates coming, the bugs squashed, and the docs sharp — for the whole community.** Even the smallest contribution is a huge encouragement. 🙏

### ☕ Make a one-tap donation via UPI

**📷 Scan the QR with any UPI app** (Google Pay, PhonePe, Paytm, BHIM, …) to pay instantly:

<p>
  <img src="https://cdn.jsdelivr.net/npm/@dreamtree-org/ai-builder/doc/assets/upi-qr.png" alt="Scan to pay Dreamtree Global via UPI" width="220" height="220" />
</p>

> **UPI ID:** `dhrugantha.llp@kotak` &nbsp;•&nbsp; **Payee:** Dreamtree Global
>
> 📱 On mobile, you can also tap the button below — it opens your UPI app directly. On desktop, scan the QR above or copy the UPI ID into your payment app.

[![Pay via UPI](https://img.shields.io/badge/Pay-via%20UPI-22c55e?style=for-the-badge&logo=googlepay&logoColor=white)](upi://pay?pa=dhrugantha.llp@kotak&pn=Dreamtree%20Global&cu=INR&tn=Support%20ai-builder)

### 🤝 Become a Sponsor

Want to back the project long-term or as a company? You can sponsor the package directly:

- 📦 **npm:** [`@dreamtree-org/ai-builder`](https://www.npmjs.com/package/@dreamtree-org/ai-builder) — star, share, and sponsor the package
- ✉️ **Corporate sponsorships & partnerships:** [preetham.krishna.dev@gmail.com](mailto:preetham.krishna.dev@gmail.com)

Every star ⭐, share, and contribution helps more than you know. Thank you for being part of the journey!

---

## Quick start

```bash
npx @dreamtree-org/ai-builder my-app
```

Then follow the printed next steps:

```bash
cd my-app
cp .env.example .env        # fill DB + JWT_SECRET
npm install
npm run db:sync             # create tables from schema/sync.json
npm run seed:rbac           # seed permissions from modules.config.js
npm run dev                 # Express API + Vite client
```

A scaffolded app already carries the app-building skill pack + the `ai-builder`
MCP wiring (`--ai <provider>`, default `claude`; `--ai none` to skip). Add the
two layer skills — the live data contract and component catalog:

```bash
npx @dreamtree-org/korm-js init --ai claude
npx @dreamtree-org/twreact-ui init --ai claude
# or just: npm run setup   (installs, builds, migrates, seeds, and does the above)
```

In a project you did **not** scaffold, install the skill pack yourself:

```bash
npx @dreamtree-org/ai-builder init --ai claude   # cursor | copilot | gemini | openai | all
```

---

## `init` — install the skill pack + MCP

Run inside any project to give your AI assistant the rules and live tools to build
a dreamtree app:

```bash
npx @dreamtree-org/ai-builder init --ai <provider>   # claude | cursor | copilot | gemini | openai | all
```

It writes the app-building skill to the provider's conventional location and merges
the `ai-builder` MCP server into the provider's MCP config:

| provider | skill file | MCP config |
| --- | --- | --- |
| `claude` | `.claude/skills/dreamtree-app-builder/SKILL.md` | `.mcp.json` |
| `cursor` | `.cursor/rules/dreamtree-app-builder.mdc` | `.cursor/mcp.json` |
| `copilot` | `.github/copilot-instructions.md` | `.vscode/mcp.json` |
| `gemini` | `GEMINI.md` | `.gemini/settings.json` |
| `openai` | `AGENTS.md` | (Codex global `~/.codex/config.toml`, printed) |

Flags: `--no-mcp` (skill only), `--no-design-skill`, `--force`, `--dry-run`.

`init` also installs the third-party **`ui-ux-pro-max`** design-intelligence skill
(color palettes, font pairings, layout patterns — reference material for prompting,
never a licence to hand-roll UI outside `twreact-ui`). It runs
`npx -y ui-ux-pro-max-cli init --ai <platform>` in your project — a network install
from a package we don't own — best-effort and time-bounded, so a failure warns and
never aborts the skill/MCP install. Opt out with `--no-design-skill`. Scaffolding a
new app does **not** install it.

**Your own files are never overwritten.** `AGENTS.md`, `GEMINI.md` and
`.github/copilot-instructions.md` are shared conventions you write in too, so only
the span between `<!-- ai-builder:start -->` and `<!-- ai-builder:end -->` belongs
to us — everything else is left exactly as it was, and a file with no markers gets
the block appended rather than replaced. Files that are wholly ours
(`.claude/skills/…`, `.cursor/rules/…`) are preserved unless `--force`.

`init` never creates `tracking/` — installing a skill pack shouldn't add documents
to your repo. Scaffolded apps get it; elsewhere your assistant creates it from the
`plan_template` tool when it first plans.

## `update` — stay on the latest version

The skill pack `init` writes is a snapshot — a newer `ai-builder` may have shipped
since. Run `update` (alias `upgrade`) inside the project to check and re-sync:

```bash
npx @dreamtree-org/ai-builder@latest update          # report version + re-sync skill/MCP to it
npx @dreamtree-org/ai-builder@latest update --check   # report only, write nothing
```

It reports the running-vs-latest version (a zero-dep, cached registry check),
prints the command to upgrade the package itself, and **re-syncs the installed,
version-stamped skill pack + MCP wiring** to the running version for every provider
already set up here (or just `--ai <provider>`). It never runs `npm install` for you.

It also **refreshes the korm-js + twreact-ui layer skills** by running each
package's own `init --ai <provider>` (best-effort — a layer failure warns and
prints the manual command). Skip with `--no-layers`. And it reports **version drift
across the whole `@dreamtree-org` family** — declared vs installed vs latest, per
package, with the exact `npm i <pkg>@latest` to run.

| Flag | Description |
| --- | --- |
| `--check` | Report only — write nothing |
| `--ai <provider>` | Re-sync just this provider (default: every provider already set up here) |
| `--no-layers` | Skip the korm-js / twreact-ui skill refresh |
| `--no-mcp` | Re-sync the skill only, leave MCP config alone |
| `--no-design-skill` | Skip the `ui-ux-pro-max` design-skill refresh |
| `--dry-run` | Print what would change (including the layer commands), write nothing |

`scaffold` and `init` also print a one-line nudge when you're behind. Set
`AI_BUILDER_NO_UPDATE_CHECK=1` to disable all version checks (air-gapped/CI). Your AI
assistant can self-check via the `check_version` MCP tool and offer to run `update`.

## `mcp` — the ai-builder MCP server

A **zero-dependency** stdio MCP server (raw JSON-RPC 2.0 — no SDK). `init` wires it
in automatically; you can also register it manually:

```json
{ "mcpServers": { "ai-builder": { "command": "npx", "args": ["-y", "@dreamtree-org/ai-builder", "mcp"] } } }
```

Eleven tools, all **read-only** — the server never writes to your project. Fetch
facts instead of re-reading files:

| Tool | Returns |
| --- | --- |
| `project_state` | **Call this first.** The app on disk (modules, models, tables), installed layer versions, the state of `tracking/plan.md` incl. its Resume block, git — and a computed `nextAction` |
| `plan_template` | the `plan` / `big-picture` / `backlog` skeleton + the rules that keep a plan resumable |
| `layer_docs` | korm-js / twreact-ui docs read from **your** `node_modules` — a component's real props at the version you installed |
| `build_rules` | the binding hard rules + RBAC model + add-a-feature path |
| `data_contract` | the KORM `processRequest` contract + schema column format |
| `list_modules` / `describe_module` | the starter module catalog; one module in full |
| `get_schema` / `get_registry` | the generated `schema/sync.json` / `modules.config.js` |
| `scaffold_plan` | the exact files a scaffold would emit (dry run) |
| `check_version` | version drift across the whole @dreamtree-org family + the commands to fix it |

### Why an agent stops guessing

Two problems this closes:

**"Where was I?"** A session can end mid-task; everything the agent worked out
dies with it. Scaffolded apps ship a `tracking/` trio — `plan.md` (active work,
with a `Resume here` block rewritten at *every task transition*, not at the end),
`big-picture.md` (architecture, seeded from your real registry and schema) and
`backlog.md`. A fresh session calls `project_state` once and gets the next
concrete action back. No re-reading ten files, no re-deciding what was decided.

**"What props does `<Button>` take?"** korm-js and twreact-ui each ship AI docs
*inside the package* — `ai-skills/*.md`, and twreact-ui's `dist/ai-schema.json`
with the per-component prop contract. `layer_docs` reads them out of your own
`node_modules`, so answers are true for the version you actually installed.
ai-builder deliberately keeps **no snapshot** of another package's API: a snapshot
is stale the moment they publish.

A generated app is **two npm projects** — the API at the root and the SPA under
`client/` — and `twreact-ui` is declared and installed only in `client/`. Layer
resolution accounts for that: from the app root it looks in the root
`node_modules`, then in the nested app project, then upward, and tells you which
one answered (`workspace: "client"`, `hoisted: false`). Asking from the app root
always works.

---

## Usage

```
npx @dreamtree-org/ai-builder <app-name> [options]
```

| Option | Description |
| --- | --- |
| `--db <mysql\|pg\|sqlite>` | Database client (default: `sqlite` for local dev) |
| `--modules <a,b,c>` | Starter module keys (default: `core`) |
| `--ai <provider\|none>` | Install the skill pack + MCP wiring into the new app (default: `claude`) |
| `--yes`, `-y` | Accept defaults, skip prompts |
| `--dry-run` | Show the file plan, write nothing |
| `--force` | Overwrite a non-empty target directory |
| `--help`, `-h` | Show help |

### Starter modules

`core` is always generated (RBAC, settings, per-tenant API tokens). The rest are
opt-in examples you can keep, replace, or delete:

| Key | Models | Demonstrates |
| --- | --- | --- |
| `core` | User, Role, Permission, ApiToken, Setting | RBAC engine + external API tokens |
| `billing` | Bill, Passbook | **row-level grants** (default-deny per-`Passbook` access) |
| `inventory` | Product, Category | plain CRUD with a foreign key |
| `crm` | Lead, Customer | CRUD + `export` action |

```bash
npx @dreamtree-org/ai-builder my-app --db pg --modules billing,inventory
```

---

## How it works

A zero-runtime-dependency CLI generates the app from a **module registry**.

```
argv ─▶ src/index.js ─┬─▶ src/prompts.js       (appName, db, modules, brand)
                      ├─▶ src/moduleCatalog.js
                      │     buildRegistry(modules) ─▶ modules.config.js
                      │     buildSchema(modules)   ─▶ schema/sync.json (KORM format)
                      ├─▶ src/generate.js
                      │     walk templates/app/** ─▶ src/substitute.js ─▶ target dir
                      └─▶ src/init.js          (--ai <provider>, in-process)
                            skill pack + MCP wiring ─▶ the new app
```

Token substitution is the only "templating engine" — no Handlebars/EJS. The
templates under `templates/app/**` are real, lint-clean files; dynamic pieces
(`modules.config.js`, `schema/sync.json`, the DB driver dependency, the
`.env.example` DB block) are computed from the chosen modules and injected as
`__TOKEN__` substitutions (`src/substitute.js`, shared by the generator, `init`
and the MCP server).

The last step runs `init` **in-process** against the new app, so a fresh scaffold
already has the skill pack + MCP wired for `--ai <provider>` (default `claude`,
`none` to skip). The provider value is validated *before* any file is written, and
nothing on this path touches the network.

### Generated app architecture

```
        Express API ──processRequest──▶ korm-js ──▶ DB (mysql/pg/sqlite)
            ▲
        /api/crud/:Model
            │
        Vite/React SPA ── composes ──▶ twreact-ui
```

The single source of truth in a generated app is **`modules.config.js`** — it
derives permissions, navigation, routes, and the model→module map. RBAC is
enforced uniformly as `(module, action, scope)`, with `BaseTenantModel` adding
branch scoping and instance-grant `WHERE … IN` injection for row-level access.
Multi-tenant by default: a platform DB (tenants, modules, superadmin) and a
per-tenant DB resolved per request by `middleware/tenantResolver.js`.

---

## Repository layout

| Area | Path |
| --- | --- |
| CLI entry | `bin/cli.js` |
| Orchestrator / subcommand dispatch | `src/index.js` |
| Interactive prompts | `src/prompts.js` |
| Module catalog → registry + schema | `src/moduleCatalog.js` |
| Generator (copy + token substitution) | `src/generate.js` |
| `__TOKEN__` substitution (shared by generate / init / mcp) | `src/substitute.js` |
| `init --ai` (skill pack + MCP wiring, managed blocks) | `src/init.js` |
| `update` (version check + family drift + re-sync) | `src/update.js` |
| Version policy + semver (`checkForUpdate`, `familyStatus`) | `src/version.js` |
| npm registry lookups (https → `npm view` → floor, cached) | `src/registry.js` |
| Read-only introspection of a generated app on disk | `src/project.js` |
| `project_state` assembly + the computed `nextAction` | `src/projectState.js` |
| Version-accurate layer docs from `node_modules` | `src/layerDocs.js` |
| MCP server (zero-dep stdio JSON-RPC, read-only) | `src/mcp/server.js` |
| Compact build knowledge (MCP + skill) | `src/knowledge.js` |
| Terminal UI helpers | `src/ui.js` |
| Generated-app templates | `templates/app/**` |
| Generated-app agent memory (plan / architecture / backlog) | `templates/app/tracking/**` |
| App-building skill body (installed by `init`) | `templates/skills/app-builder.md` |
| Design SSOT (decisions + rationale) | [`SOP-ai-app-builder.md`](SOP-ai-app-builder.md) |
| Architecture SSOT (HLD/LLD) | [`tracking/big-picture.md`](tracking/big-picture.md) |
| Bug / quality / vision backlog | [`tracking/backlog.md`](tracking/backlog.md) |

---

## Development

The scaffolder uses **Node built-ins only** (no runtime dependencies); requires
Node >= 18.

```bash
git clone git@github.com:DreamtreeTech/ai-builder.git
cd ai-builder
npm run test:smoke   # scaffolds + syntax-checks an app, parses schema/registry (no network)
```

Run the CLI locally without publishing:

```bash
node bin/cli.js my-app --dry-run
```

Two CI workflows guard the repo. `ci.yml` runs the **smoke** test on every PR and
push to `main` — fast, no network. `e2e.yml` does the real thing: scaffold →
`npm install` → `db:sync` → `seed:rbac` → `vite build` → boot → `/health`,
`/api/meta/modules` and an unauthenticated-CRUD-401 check, plus `layer_docs`
against the app's actual `node_modules`. It runs nightly, on push to `main`, and
as a gate on every release.

### Releasing

Publishing is **automated and tag-driven — never run `npm publish` by hand.**

1. Land the work on `main` with CI green.
2. Add the release's entry to [`CHANGELOG.md`](CHANGELOG.md) under a new
   `## [x.y.z]` heading, refresh any docs the change invalidated, and commit.
3. Bump + tag + push in one step:

   ```bash
   npm run release:patch   # or release:minor / release:major
   ```

   That runs `npm version`, which rewrites `package.json`, commits
   `chore(release): vX.Y.Z`, creates the annotated `vX.Y.Z` tag, and pushes both.

4. The tag push fires [`.github/workflows/release.yml`](.github/workflows/release.yml):
   the **e2e** gate, then the smoke test, then `npm publish`, then a GitHub
   release whose notes are the matching `CHANGELOG.md` section.

Nothing between step 3 and the published tarball is manual. If a pre-publish gate
fails, fix it and re-run the workflow — no version is burned, because nothing was
published.

### Contributing rules (must-read)

[`CLAUDE.md`](CLAUDE.md) is the single source of truth for any contributor (human
or AI). The non-negotiables:

1. The **SOP is binding** — changing a locked decision means updating
   `SOP-ai-app-builder.md` in the same change.
2. **Compose `twreact-ui`; never duplicate UI.** A gap is a GitHub issue against
   the twreact-ui repo, not an inline copy.
3. **All data access goes through KORM** — no raw SQL, no scattered `axios`.
4. **One module registry** drives permissions, nav, routes, and the model→module map.
5. **Schema is generated**, not hand-authored.
6. The **scaffolder stays zero-runtime-dependency.**

---

## License

MIT © **[Dreamtree Global](http://dreamtreeglobal.com/)**

## Support

- 📦 [npm package](https://www.npmjs.com/package/@dreamtree-org/ai-builder)
- 🐛 [Issue tracker](https://github.com/DreamtreeTech/ai-builder/issues)
- 🌐 [Dreamtree Global](http://dreamtreeglobal.com/)
- 📧 [preetham.krishna.dev@gmail.com](mailto:preetham.krishna.dev@gmail.com)
