Open MercatoDocsSearch docsAPI reference

Customization

Create a standalone app

A standalone app gives your team its own repository for business rules, pages and modules. Choose a starter or template, check what it enables, and keep your framework dependencies versioned so you can review upgrades as ordinary code changes.

Create a project that installs the framework from npm and keeps your business modules in your own repository. Start here when you are building an application.

Tip · Recommended for production apps

This is the recommended path for teams building production applications on top of Open Mercato. You get a self-contained project that installs Open Mercato packages from npm – no monorepo clone required. If you're a framework contributor or want to explore the source, see Local setup for the monorepo path.

The create-mercato-app CLI scaffolds a fully configured, self-contained Open Mercato application outside the monorepo. The generated project includes Next.js, all core modules pre-enabled, Docker services, and development tooling – ready to customize and deploy independently.

Prerequisites

Useful one-time setup commands:

gh auth login
npm i -g @openai/codex
curl -fsSL https://claude.ai/install.sh | bash

Scaffold the app

npx create-mercato-app my-store

This creates a my-store/ directory with the full application template, including package.json, docker-compose.yml, environment templates, and the src/ tree.

Options

OptionDescription
--app <name>Import the official ready app open-mercato/ready-app-<name> at the tag of this CLI version.
--app-url <url>Import a ready app from a GitHub repository URL, optionally with /tree/<ref>.
--template <slug | owner/repo>[#ref]Create the app from an app template instead of the scaffold. See Start from an app template.
--keep-nameWith --template, keep the template's package.json name.
--preset <id>Select classic, empty, crm, or wms without the preset prompt.
--agents <list>Install the standalone AI harness non-interactively for claude-code, codex, cursor, a comma-separated subset, all, or none.
--skip-agentic-setupSkip the AI setup wizard; equivalent to --agents none.
--modules <list>Plan modules from the Open Mercato Modules catalog that are verified on this Open Mercato line. Prints their yarn mercato module add commands; installs nothing.
--module-pickerPick catalog modules from a numbered list. In a terminal it is offered by default when neither --preset nor --modules is given; Enter adds none.
--no-module-pickerDo not offer the catalog module picker.
--registry <url>Use a custom npm registry for @open-mercato packages.
--verdaccioShorthand for --registry http://localhost:4873 (local Verdaccio).
--help, -hShow usage information.
--version, -vPrint the CLI version.

App name rules: lowercase alphanumeric characters and hyphens only. Cannot start or end with a hyphen.

Start from an app template

An app template is a GitHub repository with a complete standalone app at its root, for example a CRM or a partner portal. Browse the listed ones at modules.openmercato.com/templates.

npx create-mercato-app my-crm --template crm
npx create-mercato-app my-portal --template some-agency/b2b-portal#v1.0.0

Then follow the next steps the CLI prints. They match the scripts in the app's package.json:

To share your own app as a template, save it with create-mercato-template: prepare builds a reviewed, code-only snapshot of one commit and publish pushes it as a one-commit GitHub template repository.

--app <name> still imports open-mercato/ready-app-<name> at the tag of your CLI version. When that repository does not exist, the error points to app templates.

Set up the AI development harness

Choose the coding tools during the interactive scaffold, or make the selection reproducible in CI and scripts:

npx create-mercato-app my-store --preset classic --agents all
npx create-mercato-app my-store --agents claude-code,codex

--agents applies to bare scaffolds. Apps imported with --app, --app-url or --template manage their own setup; after importing one, run yarn mercato agentic:init inside it instead. The generated harness is standalone-specific and includes a compact root router, task and module guides, local skills, pinned delivery skills from open-mercato/skills, context tools, and reproducible evaluations.

The setup attempts to install the selected skill set. Re-run the integrity-checked installer after cloning, when a setup-time download was unavailable, or after changing tiers:

yarn install-skills --list
yarn install-skills
yarn install-skills --with automation # opt in to loop/issue/release-maintenance workflows

The default installs the local core tier and the 15-skill dependency-closed daily external tier. Advanced loop engines, issue authoring, and upgrade-note maintenance stay opt-in through --with automation (or --all). Skills are discovered from .agents/skills/; Claude Code receives the compatibility links it needs. The installer verifies the pinned external commit and file hashes and activates the selected external set as one transaction, restoring the complete previous set on failure before local installation continues. It preserves unknown user-owned skills and quarantines stale or modified installer-owned copies instead of silently trusting them.

Upgrade an existing generated harness

After upgrading Open Mercato, refresh generated harness files through the ownership manifest instead of deleting local AI context:

yarn mercato agentic:init --update-harness

Unmodified generated files are replaced, missing owned files are recreated, and the manifest is refreshed atomically. User-modified or unknown files are preserved; an exact generated-path conflict is written beside the file as .incoming for review. Managed paths are resolved below the canonical app root and a symlinked ancestor is rejected before publication. Use --force only when you intentionally want to replace known generated targets. Skill installation runs afterward as a separate retryable step, so an offline registry does not invalidate the refreshed harness.

Load exact framework context only when needed

The app's root router starts with a small instruction set. When a task needs a framework implementation detail, use the context escape hatch rather than scanning all of node_modules:

yarn framework:context --module customers --query makeCrudRoute
yarn framework:context --package @open-mercato/ui --query CrudForm
yarn framework:context --root

The resolver follows the versions actually installed by the standalone app, locates their source and nearest package/module AGENTS.md chain, and materializes the smallest read-only snapshot under ignored .ai/framework-context/. It reports a warning when exact TypeScript source or instructions are unavailable; generated facts are a fast index, not a substitute for exact context when a contract is uncertain.

Validate and release the harness

Framework maintainers can find the architecture, case-authoring workflow, model-compatibility policy, evaluation lanes, containment design, and release-evidence contract in Standalone AI development harness.

Use deterministic validation while authoring guidance or cases:

yarn harness:validate --case OMH-009
yarn harness:validate --family testing
yarn harness:validate --all

harness:validate --all checks the complete catalog deterministically. Authenticated live routing can be sampled with --runner codex or --runner claude. The controller adds host filesystem containment on macOS (sandbox-exec) and Linux (Bubblewrap). The model gets no shell, process, environment, discovery, browser, or network tool; both CLIs receive only an evaluator-owned, env -i MCP server for exact-path reads and case-allowlisted writes. The selected app is intentionally readable through that narrow tool, so use a freshly generated or otherwise non-sensitive app. macOS sandbox-exec can enforce network-free lanes but cannot isolate loopback from the host; native macOS and Windows must use a contained Linux VM/container with Bubblewrap for the complete release gate.

Once per Open Mercato release, install the pinned skills and run the full matrix from a fresh controller scaffold:

yarn install-skills
yarn harness:release --runner codex --prepare-targets /absolute/empty-release-targets --acknowledge-writes

This is the actual full release gate. The current catalog contains 192 cases, including framework-neutral business requests and 45 (23.4%) writable implementation/regression cases. The suite prepares a separate disposable app for every writable case and runs deterministic coverage, configured live runners, trusted writable oracles, target generate/typecheck/lint/build, any declared generated test, and isolated generated-code review for every writable result. Its four test-authoring cases execute focused Jest unit tests plus Linux/Bubblewrap-only Playwright API and browser tests with fixed controller-owned commands and host-isolated loopback. Runtime reports must attest at least one passed test and zero skipped, todo, focused, flaky, or expected-failure tests. It writes a schema-validated, sanitized, mode-0600 report under .ai/harness/results/. An unavailable required runner, browser, or containment prerequisite is reported as unavailable and blocks a complete release claim.

The complete release gate fails closed unless it runs on Linux with trusted system Bubblewrap (bwrap) and user namespaces available. Native macOS and Windows users must run it in a Linux VM or container. Before it prepares targets, invokes a provider-backed runner, or starts any writable lane, preflight rejects untrusted/no-op Bubblewrap executables and proves that case-local loopback works while a host-loopback listener remains unreachable and the payload retains no effective, permitted, inheritable, ambient, or bounding capability.

The target directory must be an absolute, new or empty regular directory outside the controller app. Start from a fresh, sanitized controller: automatic preparation fails before copying .env/.env.* local configuration (while allowing .env.example, .env.sample, and .env.template), credential files, or private-key files. Foundation and model-authored validation commands – including yarn build – receive a minimal sanitized environment with network access denied; target commands can write only their disposable target/temp area and see controller dependencies as read-only. Persisted diagnostics redact sensitive inherited environment scalars and URL userinfo. Generated tests are stricter: the complete target is read-only, unit tests have no network, and API/browser tests receive loopback only inside the Linux/Bubblewrap network namespace. macOS sandbox-exec shares host loopback, so it is not accepted for those tests. Do not weaken containment to make a failing release pass.

When a new failure or use case is discovered, invoke the bundled om-evolve-harness skill: add a failing semantic case first, choose one smallest knowledge owner, run generated tests and target checks, perform mandatory code review, then run the full release suite. Framework maintainers also run $om-refresh-standalone-harness --from <release-ref> --to <release-ref> in the Open Mercato monorepo to classify each local release change, extend coverage when needed, and publish a sanitized local maintenance report.

Efficient task workflows

Set up and run

cd my-store
yarn setup

yarn setup copies .env.example to .env when it is missing (an existing .env is never overwritten), checks Docker, starts PostgreSQL, Redis and Meilisearch from docker-compose.yml and waits until they are healthy. Only then does it install dependencies, generate, migrate, initialize and start the dev server. If Docker is missing or stopped, or a port is taken, it stops before touching the database and says what to fix. Re-running it is safe: containers and volumes are reused and an already initialized database is kept.

Running PostgreSQL, Redis and Meilisearch yourself? Point .env at them and run:

yarn setup --no-infra

It makes no Docker calls and keeps your URLs. The containers on their own: yarn infra:up (start and wait for health) and yarn infra:down (stop, data kept; --volumes --yes deletes it).

The manual equivalent, against services you started yourself:

cp .env.example .env   # then set DATABASE_URL, JWT_SECRET, REDIS_URL at minimum
yarn install
yarn initialize        # generates modules, runs migrations, seeds data
yarn dev

Info

yarn initialize handles code generation (yarn generate) and database migrations (yarn db:migrate) internally – you do not need to run them separately. It also seeds default data and will abort if existing users are found (yarn setup passes --skip-if-initialized, which keeps the existing data instead). For upgrades on an existing database, run yarn db:migrate instead of yarn initialize.

If you prefer the old raw terminal output with no splash screen during standalone bootstrap, use yarn setup:classic instead of the compact setup flow.

yarn dev starts the compact development runtime with a splash screen that shows live startup progress. On native local runs the splash is served on http://localhost:4000 by default and auto-opens when supported; the terminal also prints the backend URL at http://localhost:3000/backend. Once the app is ready, the splash can also expose:

If you want the previous raw passthrough experience instead, run yarn dev:classic.

Useful standalone splash env vars:

To run several persistent standalone apps against the same PostgreSQL server, pass --database-name[=<name>] to yarn setup or yarn dev:

yarn setup --database-name=client_a   # explicit name; offers to update .env (default yes)
yarn setup --database-name            # derives name from the current directory
yarn dev --database-name=temp_run --no-update-env  # only injects DATABASE_URL into this run

Set OM_DEV_DATABASE_NAME / OM_DEV_DATABASE_UPDATE_ENV for non-interactive automation. Without the flag, yarn setup and yarn dev keep their current behavior – no prompt, no .env mutation.

Navigate to http://localhost:3000/backend and sign in with the credentials printed by yarn initialize.

Test create-mercato-app locally from the monorepo

If you are contributing to Open Mercato itself and changing the scaffold, validate it from the monorepo before publishing packages.

Scaffold-only smoke test

Run this from the monorepo root:

yarn test:create-app

This command:

If you only want the generated path and do not want an interactive shell:

yarn test:create-app --no-shell

Full standalone integration parity

To run the ephemeral standalone integration flow against a freshly scaffolded app:

yarn test:create-app:integration

This command scaffolds a temporary standalone app, installs fresh local @open-mercato/* tarballs from the current branch, and runs the standalone integration suite through the local CLI. Docker must be available for this flow.

What's in the box

The scaffolded app comes with 27 pre-enabled modules covering the most common commerce and business operations:

All modules are listed in src/modules.ts and can be individually disabled or ejected.

Project structure

my-store/
├── .dockerignore
├── .env.example                  # Environment variable reference
├── .gitignore
├── .yarnrc.yml                   # Yarn config (registry settings)
├── AGENTS.md                     # AI agent guidelines (Claude Code)
├── CLAUDE.md                     # Claude Code project instructions
├── components.json               # shadcn/ui component config
├── Dockerfile                    # Multi-stage production build
├── docker-compose.yml            # Services only (PostgreSQL, Redis, Meilisearch)
├── docker-compose.fullapp.yml    # Full stack for production-style deploy
├── docker-compose.fullapp.dev.yml # Full stack with hot reload (Windows-friendly)
├── docker/
│   └── scripts/
│       └── dev-entrypoint.sh     # Dev container entrypoint
├── next.config.ts                # Next.js configuration
├── package.json                  # Scripts, dependencies
├── postcss.config.mjs            # PostCSS / Tailwind config
├── tsconfig.json                 # TypeScript paths
├── yarn.lock
├── types/                        # Type declarations
│   ├── pg/index.d.ts
│   └── react-big-calendar/index.d.ts
├── public/                       # Static assets (SVGs)
└── src/
    ├── bootstrap.ts              # App initialization
    ├── di.ts                     # DI overrides
    ├── modules.ts                # Enabled modules and their sources
    ├── proxy.ts                  # Proxy configuration
    ├── app/
    │   ├── layout.tsx            # Root layout
    │   ├── page.tsx              # Public landing page
    │   ├── globals.css           # Global styles
    │   ├── (backend)/backend/    # Admin panel routes
    │   ├── (frontend)/           # Frontend routes
    │   └── api/                  # API dispatcher + OpenAPI docs
    ├── components/               # Shared UI components
    │   ├── ClientBootstrap.tsx
    │   ├── GlobalNoticeBars.tsx
    │   ├── NotificationBellWrapper.tsx
    │   ├── OrganizationSwitcher.tsx
    │   ├── StartPageContent.tsx
    │   └── ui/                   # shadcn/ui primitives
    ├── i18n/                     # Locale files (en, pl, es, de)
    └── modules/                  # Your custom modules (from: '@app')
        └── auth/
            └── __integration__/  # Integration test scaffold
                ├── TC-AUTH-001.spec.ts
                └── helpers/auth.ts

Key files

Response security headers

New standalone apps include the maintained Open Mercato browser-security baseline in next.config.ts: Content Security Policy (CSP), strict referrer handling, MIME-sniffing protection, same-origin framing, and a separate sandboxed policy for attachment downloads. The default CSP includes the Stripe script and frame origins used by the bundled payment integration.

If an app adds a provider that loads scripts, frames, images, or browser connections from another origin, extend only the matching directive in contentSecurityPolicy in next.config.ts. Keep the existing directives and the /api/attachments/file/:path* sandbox rule intact, and prefer an exact provider origin over a broad wildcard. Re-run the provider's browser flow after changing the policy.

Forcing a single locale

Set the OM_FORCE_LOCALE env var to pin the whole app to one supported locale (e.g. OM_FORCE_LOCALE=pl for Polish). When set, cookie and Accept-Language detection are bypassed, the in-app language switcher is hidden, and the locale-change endpoint returns 409. Leave it unset (the default) for normal per-user detection.

Docker Compose variants

The scaffolded app includes three Compose files for different scenarios:

FileWhen to use
docker-compose.ymlLocal development – starts only infrastructure services (PostgreSQL, Redis, Meilisearch). You run the app with yarn dev on the host.
docker-compose.fullapp.dev.ymlContainerized development – runs the full stack including the app with hot reload. The app container exposes the dev splash progress page and backend URL on stable host ports. Recommended for Windows or fully containerized workflows.
docker-compose.fullapp.ymlProduction-style deploy – builds and runs the app in production mode inside Docker. Suitable for demos, staging, or deployment.

All three gate the optional opencode (and, in the full-stack files, mcp) services behind the agents Compose profile, so a plain docker compose up starts exactly what it always did. See Agent Orchestrator.

Agent Orchestrator (enterprise)

The scaffolded app ships the Agent Orchestrator wiring switched off. It is a commercial module – the package installs from npm without a key, but production use requires a licence (see packages/enterprise/LICENSE.md).

Turn on the in-process (native) runtime with two flags in .env:

OM_ENABLE_ENTERPRISE_MODULES=true
OM_ENABLE_ENTERPRISE_MODULES_AGENTS=true

then yarn generate && yarn db:migrate && yarn mercato auth sync-role-acls. That is enough for agents declared with defineAgent in a module's ai-agents.ts, and for the example agents in src/modules/agent_examples/.

File-defined (OpenCode) agents additionally need two containers, gated behind the agents Compose profile so they cost nothing until you ask for them:

# Containerized: app + mcp + opencode
docker compose --profile agents -f docker-compose.fullapp.yml up

# Hybrid: app and MCP on the host (yarn dev), only OpenCode in a container
docker compose --profile agents up -d opencode

The mcp service is the tool plane the agents call back into; it provisions its own API key into a shared volume, which opencode reads. Both are described in MCP Server.

The agent definitions themselves live in src/modules/<module>/agents/<id>/ (AGENT.md + OUTCOME.md, plus optional skills/, sub-agents/, tools/). yarn generate compiles them into docker/opencode/agents/ and docker/opencode/skills/, which the opencode container mounts read-only. OpenCode reads those files when a session starts and does not reliably hot-reload, so restart the container after regenerating:

yarn generate && docker compose --profile agents restart opencode

Two things worth knowing before exposing this beyond your own machine:

AI tooling

When selected at scaffold time, the project includes the shared AGENTS.md router plus tool-specific Claude Code, Codex, and/or Cursor configuration. Durable standalone knowledge lives in .ai/guides/ and .ai/skills/; installed skill discovery lives in .agents/skills/. Prefer extending the routed guide or skill that owns a rule over growing the root file. See Set up the AI development harness for installation, exact framework context, evaluation, and release maintenance.

Integration test scaffold

The project includes a starter integration test at src/modules/auth/__integration__/TC-AUTH-001.spec.ts with a helper module for authentication. Use this as a reference when writing Playwright-based integration tests for your custom modules. Run tests with yarn test:integration.

Available scripts

CommandDescription
yarn setup:classicRun standalone setup and startup in the legacy raw passthrough mode with no splash screen.
yarn devStart the compact development runtime with hot reload and a splash progress page.
yarn dev:classicStart the legacy raw passthrough runtime with no splash screen.
yarn buildBuild the Next.js application for production.
yarn startStart the production server.
yarn generateRun all code generators (registry, entities, DI, API client).
yarn install-skillsVerify and install the selected local and pinned external AI skills.
yarn framework:contextMaterialize bounded context from the exact installed Open Mercato packages.
yarn harness:validateRun focused, family, deterministic, or authenticated live harness evaluations.
yarn harness:releaseRun the contained full per-release evaluation matrix and write a sanitized report.
yarn db:generateGenerate database migrations from entity diffs.
yarn db:migrateApply pending database migrations.
yarn db:greenfieldDestructive reset – drops all tables and regenerates.
yarn initializeFull bootstrap: generate, migrate, seed roles and data.
yarn reinstallDrop everything and re-bootstrap from scratch.
yarn testRun the test suite.
yarn lintLint the codebase.

Add a custom module

Create a new module under src/modules/ and register it in modules.ts:

  1. Scaffold the directory:

    mkdir -p src/modules/inventory
    
  2. Add src/modules/inventory/index.ts:

    export const metadata = { title: 'Inventory', group: 'Modules' }
    
  3. Register in src/modules.ts:

    export const enabledModules: ModuleEntry[] = [
      // ... existing modules
      { id: 'inventory', from: '@app' },
    ]
    
  4. Regenerate and run:

    yarn generate
    yarn dev
    

Add backend pages, API routes, entities, and other module files using the standard module file conventions.

Tip · Following the tutorials

The Build your first Open Mercato app tutorial series walks through building an inventory module step by step. Those tutorials use monorepo paths (apps/mercato/src/modules/) but the patterns are identical – in a standalone app, use src/modules/ instead. Everything else (module files, conventions, API routes, backend pages) works the same way.

Eject a core module

When you need to deeply customize a core module – changing its entities, business logic, or UI beyond what overrides allow – you can eject it. Ejecting copies the module's full source into your src/modules/ directory and switches it to from: '@app' so the framework loads your local version.

# See which modules can be ejected
yarn mercato eject --list

# Eject the currencies module
yarn mercato eject currencies

# Regenerate after ejection
yarn mercato generate all

After ejection, the module is fully yours to modify. See the mercato eject CLI reference for the full list of ejectable modules and detailed usage.

Caution

Ejected modules no longer receive automatic updates from package upgrades. You are responsible for merging upstream changes manually when upgrading Open Mercato versions.

Environment configuration

The .env.example file documents all available variables. Key sections:

VariableRequiredDescription
DATABASE_URLYesPostgreSQL connection string.
JWT_SECRETYesSecret for signing auth tokens.
REDIS_URLYesRedis connection for caching and events.
MEILISEARCH_HOSTNoMeilisearch URL for full-text search.
OPENAI_API_KEYNoEnables OpenAI-backed AI features; pair it with OM_DISABLE_VECTOR_SEARCH_AUTOINDEXING=false when you want vector auto-indexing.
OM_DISABLE_VECTOR_SEARCH_AUTOINDEXINGNoDefaults to true in the example env. Set to false or remove it to enable automatic vector indexing.
CACHE_STRATEGYNomemory, sqlite, redis, or jsonfile. Defaults to memory.
QUEUE_STRATEGYNolocal or async. Use async with Redis for production.
APP_URLNoPublic URL, used in emails and onboarding.

Docker services

The generated docker-compose.yml starts three services:

ServiceImageDefault Port
PostgreSQLpgvector/pgvector:pg17-trixie5432
Redisredis:7-alpine6379
Meilisearchgetmeili/meilisearch:v1.117700

Start them with docker compose up -d and stop with docker compose down. Add -v to remove volumes and reset all data.

Upgrading

To upgrade Open Mercato packages in your standalone app:

# Update all @open-mercato packages to the latest version
yarn up '@open-mercato/*'

# Regenerate and apply any new migrations
yarn generate
yarn db:migrate

Review the changelog for breaking changes before upgrading.

Troubleshooting

Check the released starter before troubleshooting setup

The published 0.10.0 CLI supports classic, empty, crm and wms presets. The generated project's packageManager field pins the Yarn version. On first launch, yarn setup starts the development runtime after initialization. Use the Backend URL printed by that process.

Previous: List inventory items