### Start development server with npm Source: https://factory.mastra.ai/reference/create-factory Use npm to start the development server for the default template. Run from the generated directory. ```bash cd my-mastra-factory npm run dev ``` -------------------------------- ### Setup command for repository sandbox Source: https://factory.mastra.ai/configure/sandboxes Set this command in Settings → Repositories under Sandbox to install dependencies and generate files before the agent runs. It runs when the sandbox first starts and is skipped on warm restarts if successful. ```bash pnpm i && pnpm build ``` -------------------------------- ### Run create-factory with Bun Source: https://factory.mastra.ai/reference/create-factory Starts the interactive wizard using Bun. By default, dependencies are installed and the project is connected to Mastra platform resources. ```bash bun x create-factory@latest ``` -------------------------------- ### Start development server with Bun Source: https://factory.mastra.ai/reference/create-factory Use Bun to start the development server for the default template. Run from the generated directory. ```bash cd my-mastra-factory bun run dev ``` -------------------------------- ### Create project without platform setup using Bun Source: https://factory.mastra.ai/reference/create-factory Skips platform sign-in and resource provisioning with --no-platform using Bun. Still downloads the template and installs dependencies, but copies .env.example to .env without filling in platform credentials. ```bash bun x create-factory@latest my-mastra-factory --no-platform ``` -------------------------------- ### Install dependencies and build Factory Server (Bun) Source: https://factory.mastra.ai/deployment Run these commands from the Factory Server directory to install dependencies and build the server. The build writes the server and Factory UI to .mastra/output. ```bash npm ci --include dev # couldn't auto-convert command bun run check bun run build ``` -------------------------------- ### Run create-factory with npm Source: https://factory.mastra.ai/reference/create-factory Starts the interactive wizard using npm. By default, dependencies are installed and the project is connected to Mastra platform resources. ```bash npx create-factory@latest ``` -------------------------------- ### Install dependencies and build Factory Server (npm) Source: https://factory.mastra.ai/deployment Run these commands from the Factory Server directory to install dependencies and build the server. The build writes the server and Factory UI to .mastra/output. ```bash npm ci --include=dev npm run check npm run build ``` -------------------------------- ### Install dependencies and build Factory Server (pnpm) Source: https://factory.mastra.ai/deployment Run these commands from the Factory Server directory to install dependencies and build the server. The build writes the server and Factory UI to .mastra/output. ```bash npm ci --include=dev # couldn't auto-convert command pnpm run check pnpm run build ``` -------------------------------- ### Install dependencies and build Factory Server (Yarn) Source: https://factory.mastra.ai/deployment Run these commands from the Factory Server directory to install dependencies and build the server. The build writes the server and Factory UI to .mastra/output. ```bash npm ci --include=dev # couldn't auto-convert command yarn run check yarn build ``` -------------------------------- ### Run create-factory with pnpm Source: https://factory.mastra.ai/reference/create-factory Starts the interactive wizard using pnpm. By default, dependencies are installed and the project is connected to Mastra platform resources. ```bash pnpm dlx create-factory@latest ``` -------------------------------- ### Start development server with Yarn Source: https://factory.mastra.ai/reference/create-factory Use Yarn to start the development server for the default template. Run from the generated directory. ```bash cd my-mastra-factory yarn dev ``` -------------------------------- ### Create project without platform setup using npm Source: https://factory.mastra.ai/reference/create-factory Skips platform sign-in and resource provisioning with --no-platform using npm. Still downloads the template and installs dependencies, but copies .env.example to .env without filling in platform credentials. ```bash npx create-factory@latest my-mastra-factory --no-platform ``` -------------------------------- ### Start development server with pnpm Source: https://factory.mastra.ai/reference/create-factory Use pnpm to start the development server for the default template. Run from the generated directory. ```bash cd my-mastra-factory pnpm run dev ``` -------------------------------- ### Run create-factory with Yarn Source: https://factory.mastra.ai/reference/create-factory Starts the interactive wizard using Yarn. By default, dependencies are installed and the project is connected to Mastra platform resources. ```bash yarn dlx create-factory@latest ``` -------------------------------- ### Start Factory server with npm, pnpm, Yarn, or Bun Source: https://factory.mastra.ai/ Start the Factory server using your preferred package manager. The server prints a local Mastra Factory URL to open for sign-in. ```bash npm run dev ``` ```bash pnpm run dev ``` ```bash yarn dev ``` ```bash bun run dev ``` -------------------------------- ### Create project without platform setup using pnpm Source: https://factory.mastra.ai/reference/create-factory Skips platform sign-in and resource provisioning with --no-platform using pnpm. Still downloads the template and installs dependencies, but copies .env.example to .env without filling in platform credentials. ```bash pnpm dlx create-factory@latest my-mastra-factory --no-platform ``` -------------------------------- ### Create project without platform setup using Yarn Source: https://factory.mastra.ai/reference/create-factory Skips platform sign-in and resource provisioning with --no-platform using Yarn. Still downloads the template and installs dependencies, but copies .env.example to .env without filling in platform credentials. ```bash yarn dlx create-factory@latest my-mastra-factory --no-platform ``` -------------------------------- ### Check Node.js, npm, and Git versions Source: https://factory.mastra.ai/troubleshooting Run these commands to verify that Node.js, npm, and Git are installed and meet the version requirements reported by the installer. If any command is missing, install or update the corresponding tool and reopen the terminal before retrying the Factory command. ```bash node --version npm --version git --version ``` -------------------------------- ### Create Factory project with --no-platform flag (Bun) Source: https://factory.mastra.ai/deployment Use this command to create a new Factory project without platform credentials. The installer copies .env.example to .env without adding platform credentials, so you must configure authentication, database, and sandbox providers before deployment. ```bash bunx create-factory my-factory --no-platform ``` -------------------------------- ### Install the Mastra Factory skill with npm, pnpm, Yarn, or Bun Source: https://factory.mastra.ai/skill Install the Mastra Factory skill using your preferred package manager. During installation, select the target agent and the install scope: the current project or a global install. ```bash npx skills add mastra-ai/skills --skill mastra-factory ``` ```bash pnpm dlx skills add mastra-ai/skills --skill mastra-factory ``` ```bash yarn dlx skills add mastra-ai/skills --skill mastra-factory ``` ```bash bun x skills add mastra-ai/skills --skill mastra-factory ``` -------------------------------- ### Create Factory project with Mastra platform (Bun) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The installer signs in to Mastra platform, provisions resources, and writes configuration to .env. ```bash bunx create-factory my-factory cd my-factory ``` -------------------------------- ### Create Factory project with --no-platform flag (pnpm) Source: https://factory.mastra.ai/deployment Use this command to create a new Factory project without platform credentials. The installer copies .env.example to .env without adding platform credentials, so you must configure authentication, database, and sandbox providers before deployment. ```bash pnpm create factory my-factory --no-platform ``` -------------------------------- ### Create Factory project with Mastra platform (npm) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The installer signs in to Mastra platform, provisions resources, and writes configuration to .env. ```bash npm create factory@latest my-factory cd my-factory ``` -------------------------------- ### MastraFactory Constructor and Lifecycle Source: https://factory.mastra.ai/reference/mastra-factory-api Documentation for the MastraFactory constructor and its lifecycle methods (prepare and finalize) as shown in the usage example. ```APIDOC ## MastraFactory Constructor ### Description Creates a new MastraFactory instance that assembles Factory storage domains, integrations, boards, sessions, and background work into a Mastra application. ### Method Constructor ### Endpoint `new MastraFactory(options)` ### Parameters #### Constructor Options - **storage** (LibSQLFactoryStorage) - Required - Storage instance for Factory domains. - **sandbox** (function) - Required - Callback that receives an object with `sessionId` and returns a sandbox instance (e.g., `LocalSandbox`). - **auth** (object) - Optional - Authentication provider. Defaults to Mastra platform authentication. Must support both Server and Studio authentication. ### Request Example ```typescript const factory = new MastraFactory({ storage: new LibSQLFactoryStorage({ id: 'factory-storage', url: 'file:./factory.db', }), sandbox: ({ sessionId }) => new LocalSandbox({ workingDirectory: join(process.cwd(), 'sandboxes', sessionId) }), }) ``` ### Response Returns a `MastraFactory` instance. ## MastraFactory.prepare() ### Description Prepares the factory for use, returning a promise that resolves to the assembled Mastra application configuration. ### Method Async method ### Endpoint `await factory.prepare()` ### Parameters None ### Request Example ```typescript const mastra = new Mastra(await factory.prepare()) ``` ### Response Returns a promise that resolves to the prepared Mastra application configuration. ## MastraFactory.finalize() ### Description Finalizes the factory lifecycle, completing any necessary cleanup or setup after the Mastra application is created. ### Method Async method ### Endpoint `await factory.finalize()` ### Parameters None ### Request Example ```typescript await factory.finalize() ``` ### Response Returns a promise that resolves when finalization is complete. ``` -------------------------------- ### Create Factory project with --no-platform flag (npm) Source: https://factory.mastra.ai/deployment Use this command to create a new Factory project without platform credentials. The installer copies .env.example to .env without adding platform credentials, so you must configure authentication, database, and sandbox providers before deployment. ```bash npm create factory@latest my-factory -- --no-platform ``` -------------------------------- ### Create Factory project with Mastra platform (pnpm) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The installer signs in to Mastra platform, provisions resources, and writes configuration to .env. ```bash pnpm create factory my-factory cd my-factory ``` -------------------------------- ### PlatformSandbox configuration (src/mastra/sandbox.ts) Source: https://factory.mastra.ai/configure/sandboxes Selects Mastra platform explicitly. createRepoTemplate uses the session's repository and setup command to prepare a reusable template. ```typescript import type { MastraFactorySandboxConfig } from '@mastra/factory' import { PlatformSandbox, createRepoTemplate } from '@mastra/platform-workspace' export const sandbox: MastraFactorySandboxConfig = ctx => new PlatformSandbox({ id: ctx.sessionId, template: createRepoTemplate(ctx), }) ``` -------------------------------- ### Create Factory project with Mastra platform (Yarn) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The installer signs in to Mastra platform, provisions resources, and writes configuration to .env. ```bash yarn create factory my-factory cd my-factory ``` -------------------------------- ### Create Factory project with --no-platform flag (Yarn) Source: https://factory.mastra.ai/deployment Use this command to create a new Factory project without platform credentials. The installer copies .env.example to .env without adding platform credentials, so you must configure authentication, database, and sandbox providers before deployment. ```bash yarn create factory my-factory --no-platform ``` -------------------------------- ### finalize() method Source: https://factory.mastra.ai/reference/mastra-factory-api Initializes the controller and starts Factory work after the Mastra instance is constructed. Returns a Promise. Calling before preparation throws. ```typescript await factory.finalize() ``` -------------------------------- ### MastraFactory constructor and lifecycle with local storage and sandbox Source: https://factory.mastra.ai/reference/mastra-factory-api Constructor and lifecycle example for MastraFactory with local storage and local execution. Uses LibSQLFactoryStorage with a file URL and a LocalSandbox callback that creates a working directory per session. The factory is prepared and finalized around the Mastra instance. ```typescript import { join } from 'node:path' import { Mastra } from '@mastra/core' import { LocalSandbox } from '@mastra/core/workspace' import { MastraFactory } from '@mastra/factory' import { LibSQLFactoryStorage } from '@mastra/libsql' const factory = new MastraFactory({ storage: new LibSQLFactoryStorage({ id: 'factory-storage', url: 'file:./factory.db', }), sandbox: ({ sessionId }) => new LocalSandbox({ workingDirectory: join(process.cwd(), 'sandboxes', sessionId) }), }) export const mastra = new Mastra(await factory.prepare()) await factory.finalize() ``` -------------------------------- ### Configure WorkOS auth provider in src/mastra/index.ts Source: https://factory.mastra.ai/configure/auth Shows how to pass a MastraAuthWorkos instance to the `auth` option on `MastraFactory`. The generated server already includes WorkOS configuration as an alternative to the default Mastra platform sign-in. Follow the WorkOS setup instructions to configure or customize it. ```typescript import { MastraAuthWorkos } from '@mastra/auth-workos' import { MastraFactory } from '@mastra/factory' const factory = new MastraFactory({ storage, auth: new MastraAuthWorkos({ fetchMemberships: true }), // Keep your other Factory options. }) ``` -------------------------------- ### Configure LocalSandbox in src/mastra/sandbox.ts Source: https://factory.mastra.ai/configure/sandboxes Configure the sandbox callback to use LocalSandbox for local execution. Each session gets its own working directory under the configured root. Set MASTRACODE_LOCAL_SANDBOX_ROOT to an absolute path to choose where session directories are stored. ```typescript import { homedir } from 'node:os' import { join } from 'node:path' import { LocalSandbox } from '@mastra/core/workspace' import type { MastraFactorySandboxConfig } from '@mastra/factory' const root = process.env.MASTRACODE_LOCAL_SANDBOX_ROOT || join(homedir(), '.mastracode', 'web', 'sandboxes') export const sandbox: MastraFactorySandboxConfig = ctx => new LocalSandbox({ workingDirectory: join(root, ctx.sessionId), env: { HOME: homedir() }, }) ``` -------------------------------- ### Define and install a Quality board with MastraFactory Source: https://factory.mastra.ai/configure/boards-and-rules Add this board definition to src/mastra/index.ts and pass it in the existing MastraFactory configuration. The working phase requires a role; outcomes defines allowed moves without moving cards automatically. After restarting the server, open Quality in the Factory UI to see the three phases. ```typescript import { Mastra } from '@mastra/core' import { MastraFactory, defineBoard } from '@mastra/factory' import { LibSQLFactoryStorage } from '@mastra/libsql' const qualityBoard = defineBoard({ id: 'quality', title: 'Quality', initialPhase: 'queued', phases: { queued: { title: 'Queued', kind: 'resting', outcomes: { start: 'checking' } }, checking: { title: 'Checking', kind: 'working', role: 'quality-checker', outcomes: { pass: 'done', retry: 'queued' }, }, done: { title: 'Done', kind: 'terminal' }, }, }) const factory = new MastraFactory({ storage: new LibSQLFactoryStorage({ id: 'factory-storage', url: 'file:./factory.db' }), boards: [qualityBoard], }) export const mastra = new Mastra(await factory.prepare()) await factory.finalize() ``` -------------------------------- ### Configure LibSQLFactoryStorage in src/mastra/storage.ts Source: https://factory.mastra.ai/configure/storage Configure LibSQLFactoryStorage for a local database file or remote Turso database. Without LIBSQL_URL, creates factory.db in the server start directory; add the database and journal files to .gitignore. Leaving vector undefined uses Factory's default vector-store resolution. ```typescript import { resolve } from 'node:path' import { LibSQLFactoryStorage } from '@mastra/libsql' export const storage = new LibSQLFactoryStorage({ id: 'factory-storage', url: process.env.LIBSQL_URL || `file:${resolve('factory.db')}`, authToken: process.env.LIBSQL_AUTH_TOKEN, }) export const vector = undefined ``` -------------------------------- ### Configure PORT and MASTRACODE_PUBLIC_URL in .env Source: https://factory.mastra.ai/troubleshooting Set both PORT and MASTRACODE_PUBLIC_URL to the same available port (here 4112) in the generated .env file to avoid conflicts when port 4111 is occupied. Preserve other values in the file, restart Factory, and start a fresh login without reusing an old callback URL. ```dotenv PORT=4112 MASTRACODE_PUBLIC_URL=http://localhost:4112 ``` -------------------------------- ### transitionPolicy example for Quality board Source: https://factory.mastra.ai/reference/mastra-factory-api Add this property alongside `phases` in the Quality board definition to require a person to move the card to Done. The policy rejects the transition with code 'approval_required' when the target stage is 'done' and the transition is not human-initiated. ```typescript transitionPolicy: context => { if (context.toStage === 'done' && !context.isHumanTransition) { return { type: 'reject', code: 'approval_required', reason: 'A person must approve the quality check.', } } }, ``` -------------------------------- ### Set public endpoints in .env Source: https://factory.mastra.ai/configure/slack Set the public endpoints for the Factory Server. For local testing, forward a public HTTPS tunnel to the Factory Server. Keep browser authentication on its working local origin and set the separate channels origin. Replace the example channels URL with your actual public origin. ```dotenv MASTRACODE_PUBLIC_URL=http://localhost:4111 MASTRACODE_CHANNELS_PUBLIC_URL=https://your-factory-tunnel.example.com ``` -------------------------------- ### Add onEnter handler to checking phase for quality check Source: https://factory.mastra.ai/configure/boards-and-rules Add this onEnter handler to the checking phase to start a quality check when a manual card enters Checking. Requires a configured model provider and repository sandbox. After restarting the server, create a manual work item on Quality and move it from Queued to Checking to run the prompt. ```typescript onEnter: { manual: context => ({ type: 'invokeSkill', idempotencyKey: `${context.ingress.id}:quality-check`, role: 'quality-checker', prompt: 'Review the work item against the repository. Summarize your findings without changing files, then wait for a person to choose pass or retry.', }), }, ``` -------------------------------- ### Create project with name using Bun Source: https://factory.mastra.ai/reference/create-factory Downloads the Software Factory template and creates a project with the given name using Bun. Prompts for a name if not provided. ```bash bun x create-factory@latest my-mastra-factory ``` -------------------------------- ### Check and build the server with npm, pnpm, Yarn, or Bun Source: https://factory.mastra.ai/deployment Run these commands from the Factory Server directory to check and build the project before deployment. The npm, pnpm, Yarn, and Bun variants are equivalent. Review local environment values so a localhost callback origin isn't used by the deployed server. ```bash npm run check npm run build ``` ```bash pnpm run check pnpm run build ``` ```bash yarn run check yarn build ``` ```bash bun run check bun run build ``` -------------------------------- ### Create project with name using pnpm Source: https://factory.mastra.ai/reference/create-factory Downloads the Software Factory template and creates a project with the given name using pnpm. Prompts for a name if not provided. ```bash pnpm dlx create-factory@latest my-mastra-factory ``` -------------------------------- ### Create project with name using npm Source: https://factory.mastra.ai/reference/create-factory Downloads the Software Factory template and creates a project with the given name using npm. Prompts for a name if not provided. ```bash npx create-factory@latest my-mastra-factory ``` -------------------------------- ### Create project with name using Yarn Source: https://factory.mastra.ai/reference/create-factory Downloads the Software Factory template and creates a project with the given name using Yarn. Prompts for a name if not provided. ```bash yarn dlx create-factory@latest my-mastra-factory ``` -------------------------------- ### prepare() method Source: https://factory.mastra.ai/reference/mastra-factory-api Assembles configuration before constructing Mastra. Call once per Factory instance; a second call throws. Returns a Promise. ```typescript const mastraOptions = await factory.prepare() ``` -------------------------------- ### Create project with --org and --region using Bun Source: https://factory.mastra.ai/reference/create-factory Creates a project and supplies the organization and region non-interactively using Bun. These flags do not bypass authentication. ```bash bun x create-factory@latest my-mastra-factory --org my-org --region eu ``` -------------------------------- ### Configure Turso LIBSQL_URL and LIBSQL_AUTH_TOKEN in .env Source: https://factory.mastra.ai/configure/storage Set LIBSQL_URL and LIBSQL_AUTH_TOKEN in .env to connect Factory to a Turso database. Use these variables with the storage module and import shown above. ```dotenv LIBSQL_URL=libsql://your-database.turso.io LIBSQL_AUTH_TOKEN=your-turso-auth-token ``` -------------------------------- ### Create project with --org and --region using npm Source: https://factory.mastra.ai/reference/create-factory Creates a project and supplies the organization and region non-interactively using npm. These flags do not bypass authentication. ```bash npx create-factory@latest my-mastra-factory --org my-org --region eu ``` -------------------------------- ### Deploy to Mastra platform with npm, pnpm, Yarn, or Bun Source: https://factory.mastra.ai/deployment Run the deployment command from inside the Factory project directory. The CLI builds and uploads the application to a platform environment and reports its public URLs. Review the CLI's organization, project, and environment selection; the default environment is production. ```bash npm run deploy ``` ```bash pnpm run deploy ``` ```bash yarn deploy ``` ```bash bun run deploy ``` -------------------------------- ### Create project with --org and --region using pnpm Source: https://factory.mastra.ai/reference/create-factory Creates a project and supplies the organization and region non-interactively using pnpm. These flags do not bypass authentication. ```bash pnpm dlx create-factory@latest my-mastra-factory --org my-org --region eu ``` -------------------------------- ### defineBoard() Source: https://factory.mastra.ai/reference/mastra-factory-api Documentation for the defineBoard() API used to configure phase handlers, tool-result handlers, and transition policies in Factory. ```APIDOC ## [defineBoard] Configure Phase and Tool-Result Handlers ### Description Configure phase handlers and tool-result handlers through `defineBoard()`. This is the primary API for defining board rules in Factory. ### Method `defineBoard()` ### Parameters #### Configuration Object - **phases** (object) - Required - Phase definitions with handlers keyed by source (`manual`, `issue`, `pullRequest`, `linearIssue`). Each phase can have `onEnter` and `onExit` handlers. - **tools** (object) - Optional - Tool-result handlers declared as `{ toolName: { onResult: handler } }`. - **transitionPolicy** (function) - Optional - A function that receives a `FactoryStageRuleContext` and returns a transition policy decision. ### Handler Context Phase handlers receive a read-only `FactoryStageRuleContext` with common fields: `item`, `board`, `actor`, `ingress`, `itemRevision`, `configVersion`. Phase context also includes `source`, `stage`, `fromStage`, `toStage`. `ingress.id` identifies the event being processed. Tool-result handlers receive `FactoryToolResultRuleContext` which adds: `toolName`, `threadId`, `assistantMessageId`, `toolCallId`, `result.status` (`success` or `error`), `result.value` (JSON-compatible). ### Handler Return Values A handler returns one decision or `undefined`, synchronously or through a promise. Decision types: - `invokeSkill` - Start an agent with `prompt` or `skillName`. `role` must match the working phase. - `transition` - Request a move to a declared `board` and `stage`. - `upsertLinkedWorkItem` - Create or update a linked work item. - `sendMessage` - Send a message to a session. - `notify` - Send a notification with `title`, optional `body`, optional `level`. - `reject` - Reject the operation with `code` and `reason`. Action decisions require an `idempotencyKey` except for `reject`. Use a stable key derived from the event ID and action. ### Example ```typescript // Example transition policy const board = defineBoard({ phases: { /* ... */ }, transitionPolicy: context => { if (context.toStage === 'done' && !context.isHumanTransition) { return { type: 'reject', code: 'approval_required', reason: 'A person must approve the quality check.', } } }, }) ``` ``` -------------------------------- ### Deploy to staging in EU region with --region eu Source: https://factory.mastra.ai/deployment Deploy to a staging environment in the EU region by passing --region eu. This does not relocate an existing environment. Confirm the chosen environment and attached database region in Platform before deploying. ```bash npm run deploy -- --env staging --region eu ``` ```bash pnpm run deploy --env staging --region eu ``` ```bash yarn deploy --env staging --region eu ``` ```bash bun run deploy --env staging --region eu ``` -------------------------------- ### Create project with --org and --region using Yarn Source: https://factory.mastra.ai/reference/create-factory Creates a project and supplies the organization and region non-interactively using Yarn. These flags do not bypass authentication. ```bash yarn dlx create-factory@latest my-mastra-factory --org my-org --region eu ``` -------------------------------- ### Create Factory project without platform (pnpm) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The --no-platform flag skips Mastra platform provisioning and requires you to configure your own auth, storage, and sandbox providers. ```bash pnpm create factory my-factory --no-platform cd my-factory ``` -------------------------------- ### Deploy to a staging environment with --env staging Source: https://factory.mastra.ai/deployment Deploy to a named environment by passing the --env flag. The CLI can create the environment if it doesn't exist. Review configuration and secret changes when prompted, and use the deployed Factory URL and credentials for the target environment. ```bash npm run deploy -- --env staging ``` ```bash pnpm run deploy --env staging ``` ```bash yarn deploy --env staging ``` ```bash bun run deploy --env staging ``` -------------------------------- ### Create Factory project without platform (Bun) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The --no-platform flag skips Mastra platform provisioning and requires you to configure your own auth, storage, and sandbox providers. ```bash bunx create-factory my-factory --no-platform cd my-factory ``` -------------------------------- ### List Factory projects with mastra api factory project list Source: https://factory.mastra.ai/skill List the projects visible to the Factory server at the given URL. The agent uses this command after connecting to your Factory, and reports the choices when more than one project is plausible. ```bash mastra api --url "$FACTORY_URL" factory project list '{"page":0,"perPage":10}' ``` -------------------------------- ### MastraFactory Methods Source: https://factory.mastra.ai/reference/mastra-factory-api Methods for the MastraFactory instance: prepare, finalize, and shutdown. ```APIDOC ## `prepare()` ### Description Assemble configuration before constructing `Mastra`. Call once per Factory instance. A second call throws. ### Method `prepare()` ### Returns `Promise` - the constructor configuration for `Mastra`, including assembled controllers, server routes, authentication, storage, and workers. ### Usage Example ```typescript const mastraOptions = await factory.prepare() ``` ``` ```APIDOC ## `finalize()` ### Description Initialize the controller and start Factory work after the `Mastra` instance has been constructed. ### Method `finalize()` ### Returns `Promise` - Calling before preparation throws. ### Usage Example ```typescript await factory.finalize() ``` ``` ```APIDOC ## `shutdown()` ### Description Stop background dispatch owned by the Factory runtime during server shutdown. ### Method `shutdown()` ### Returns `Promise` - The server remains responsible for the Mastra instance and its other workers. ### Usage Example ```typescript await factory.shutdown() ``` ``` -------------------------------- ### MastraFactory Constructor Parameters Source: https://factory.mastra.ai/reference/mastra-factory-api Lists the constructor parameters for the Mastra Factory, describing each parameter's type, purpose, and default value. ```APIDOC ## MastraFactory Constructor Parameters ### Description This section documents the constructor parameters for the Mastra Factory. Each parameter configures a specific aspect of the factory's behavior, such as storage, authentication, vector search, event bus, and more. ### Parameters - **storage** (`FactoryStorage`) - Application and agent storage. Use PgFactoryStorage for Postgres or LibSQLFactoryStorage for local storage. - **auth** (`IMastraAuthProvider | null`) - Authentication provider with Server and Studio support. Defaults to Mastra platform authentication. Pass null to disable authentication for local development. - **vector** (`MastraVector`) - Vector store for recall search. When omitted, the SDK mount resolves its default. - **pubsub** (`PubSub`) - Distributed event bus. Omitted uses the in-process default. - **publicUrl** (`string`) - Public origin used for integration and authentication callbacks. Configure it to match the server topology. (Default: `http://localhost:4111`) - **allowedOrigins** (`string[]`) - Additional origins permitted for credentialed UI requests when the UI is served separately. - **sandbox** (`(ctx: FactorySandboxContext) => MastraSandbox`) - Constructs a sandbox for a session. Omitted disables repository sandboxes. - **sandboxStart** (`'lazy' | 'eager'`) - Start on the first command, or when the session workspace is first resolved. (Default: `lazy`) - **dispatcher** (`MastraFactoryDispatcherConfig`) - Background dispatch configuration. maxInFlight is a per-replica concurrency budget. - **stateSecret** (`string`) - Stable integration OAuth state-signing secret. Omitted generates a temporary secret, rejected by integrations requiring a stable signer. - **secretEncryption** (`FactorySecretEncryption`) - Encrypts persisted credentials and integration settings. Omitted enables plaintext compatibility and warns when auth is enabled. - **integrations** (`FactoryIntegration[]`) - Explicit integrations. Platform credentials supply missing GitHub and Linear integrations. - **configVersion** (`string`) - Configuration version recorded in audit entries. Does not change rule behavior. (Default: `factory-config-v1`) - **boards** (`readonly InstalledBoard[]`) - Additional board definitions. IDs must be unique; work and review are reserved. - **includeDefaultBoards** (`boolean`) - Whether built-in Work and Review boards are installed. (Default: `true`) - **platform** (`{ githubAppSlug?: string }`) - Identifies the deployment-owned GitHub App so its own writes are recognized. ``` -------------------------------- ### Create Factory project without platform (npm) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The --no-platform flag skips Mastra platform provisioning and requires you to configure your own auth, storage, and sandbox providers. ```bash npm create factory@latest my-factory -- --no-platform cd my-factory ``` -------------------------------- ### Configure PostgreSQL DATABASE_URL in .env Source: https://factory.mastra.ai/configure/storage Set DATABASE_URL to your PostgreSQL connection string and restart Factory. The generated server selects PostgreSQL when this variable is set. ```dotenv DATABASE_URL=postgresql://user:password@database-host:5432/factory ``` -------------------------------- ### Create Factory project without platform (Yarn) Source: https://factory.mastra.ai/ Run from a directory outside your target repository. The --no-platform flag skips Mastra platform provisioning and requires you to configure your own auth, storage, and sandbox providers. ```bash yarn create factory my-factory --no-platform cd my-factory ``` -------------------------------- ### Configure Linear OAuth credentials in .env Source: https://factory.mastra.ai/configure/linear Set both credentials on the Factory Server and restart it to enable a self-managed Linear OAuth connection. The generated entry uses this explicit integration when both values are present. ```dotenv LINEAR_CLIENT_ID=your-linear-client-id LINEAR_CLIENT_SECRET=your-linear-client-secret ``` -------------------------------- ### Configure PgFactoryStorage and PgVector in src/mastra/storage.ts Source: https://factory.mastra.ai/configure/storage Explicit PostgreSQL storage configuration module for Factory. Requires DATABASE_URL to be set; throws an error if missing. The generated project includes @mastra/pg. ```typescript import { PgFactoryStorage, PgVector } from '@mastra/pg' const connectionString = process.env.DATABASE_URL if (!connectionString) throw new Error('Set DATABASE_URL before starting Factory') export const storage = new PgFactoryStorage({ id: 'factory-storage', connectionString, }) export const vector = new PgVector({ id: 'factory-vectors', connectionString, }) ``` -------------------------------- ### transitionPolicy(context) Source: https://factory.mastra.ai/reference/mastra-factory-api Documentation for the transitionPolicy function used to control stage transitions in Factory boards. ```APIDOC ## [transitionPolicy] Transition Policy Function ### Description Define a `transitionPolicy` function to control stage transitions. It receives an immutable context and returns a policy decision. ### Method `transitionPolicy(context)` ### Parameters #### Context (immutable) - **fromStage** (string) - The stage being left. - **toStage** (string) - The stage being entered. - **isHumanTransition** (boolean) - Whether the transition is initiated by a human. - **initialEntry** (boolean) - Whether this is the initial entry into the board. - **reenter** (boolean) - Whether this is a re-entry. - **work item** (object) - The work item being moved. ### Return Values - `undefined` - Apply Factory's remaining checks without additional policy decision. - `{ type: 'allow', triageType?, accept? }` - Allow the move subject to remaining checks. `accept: true` records acceptance. - `{ type: 'reject', code, reason }` - Reject the move with an explanation. ### Example ```typescript transitionPolicy: context => { if (context.toStage === 'done' && !context.isHumanTransition) { return { type: 'reject', code: 'approval_required', reason: 'A person must approve the quality check.', } } }, ``` ``` -------------------------------- ### Generate credential encryption key with openssl Source: https://factory.mastra.ai/ Generate a random 32-byte base64-encoded key to use as FACTORY_CREDENTIAL_ENCRYPTION_KEY. Run once per project and save the output in .env, keeping a protected backup. ```bash openssl rand -base64 32 ``` -------------------------------- ### Import storage and vector in src/mastra/index.ts Source: https://factory.mastra.ai/configure/storage Replace the generated database-selection block in src/mastra/index.ts with this import. Also replace the databaseUrl, storage, and vector definitions and remove the missing-database URL check. ```typescript import { storage, vector } from './storage' ``` -------------------------------- ### MastraFactory configVersion Source: https://factory.mastra.ai/reference/mastra-factory-api Documentation for the configVersion option on MastraFactory to identify deployed configurations. ```APIDOC ## [MastraFactory] Configuration Version ### Description Set `configVersion` on `MastraFactory` to identify the deployed configuration in audit records and rule context. ### Method `MastraFactory` constructor option ### Parameters #### Configuration Object - **configVersion** (string) - Optional - Identifier for the deployed configuration. Default is `factory-config-v1`. Changing the value doesn't change which handlers run. ### Example ```typescript const factory = new MastraFactory({ configVersion: 'my-config-v2', // ... other options }) ``` ``` -------------------------------- ### Set Slack server credentials in .env Source: https://factory.mastra.ai/configure/slack Store the Slack app's credentials in the server environment, preserving other generated settings. The signing secret enables the integration and verifies inbound requests. The bot token allows replies. Account linking also needs the client credentials and an HTTPS redirect origin. ```dotenv SLACK_APP_SIGNING_SECRET=your-slack-signing-secret SLACK_APP_BOT_TOKEN=your-slack-bot-token SLACK_APP_CLIENT_ID=your-slack-client-id SLACK_APP_CLIENT_SECRET=your-slack-client-secret ``` -------------------------------- ### Configure GitLab access token in .env Source: https://factory.mastra.ai/configure/gitlab Set these environment variables on the Factory Server to authenticate with a GitLab Personal Access Token or Group Access Token. The token must have the `api` and `write_repository` scopes. `GITLAB_BASE_URL` must use HTTPS; plain HTTP is only accepted for loopback development instances. `GITLAB_WEBHOOK_SECRET` is optional and enables the direct webhook. ```dotenv GITLAB_ACCESS_TOKEN=your-gitlab-access-token GITLAB_ACCESS_TOKEN_TYPE=personal # Or group. GITLAB_BASE_URL=https://gitlab.example.com # Omit for gitlab.com. GITLAB_WEBHOOK_SECRET=your-webhook-secret # Optional, enables the direct webhook. ``` -------------------------------- ### Import sandbox callback in src/mastra/index.ts Source: https://factory.mastra.ai/configure/sandboxes Import the sandbox callback from src/mastra/sandbox.ts and use it in the generated entry file. Replace the existing inline sandbox callback in new MastraFactory(...) with this imported value. ```typescript import { sandbox } from './sandbox' ``` -------------------------------- ### Mastra platform sandbox environment variables (.env) Source: https://factory.mastra.ai/configure/sandboxes Set these values in .env to use platform sandboxes from a local server. Use an API token from your Mastra platform organization's API Tokens settings and the IDs for the project and environment where sandboxes should run. ```dotenv MASTRA_PLATFORM_ACCESS_TOKEN=your-platform-api-token MASTRA_PROJECT_ID=your-platform-project-id MASTRA_ENVIRONMENT_ID=your-platform-environment-id ``` -------------------------------- ### Jira self-managed credentials in .env Source: https://factory.mastra.ai/configure/jira Set these three environment variables on the Factory Server to use your own Jira credentials. All three values must be present for the explicit integration to be used; a partial group disables direct Jira and logs a warning. Credentials are deployment-global, so every member reads Jira through the same account. ```dotenv JIRA_BASE_URL=https://acme.atlassian.net JIRA_EMAIL=you@example.com JIRA_API_TOKEN=your-jira-api-token ``` -------------------------------- ### Configure tool rule for execute_command onResult Source: https://factory.mastra.ai/configure/boards-and-rules Add this tools property alongside phases in the same Quality board definition to react to tool call results. It sends a warning when execute_command reports a tool error during Checking. The rule leaves the card in its current phase; a nonzero exit code isn't necessarily a tool error. ```typescript tools: { execute_command: { onResult: context => { if (context.item.stages[0] !== 'checking' || context.result.status !== 'error') return return { type: 'notify', idempotencyKey: `${context.ingress.id}:quality-command-error`, title: 'Quality check command failed', body: 'Inspect the tool error before continuing the quality check.', level: 'warning', } }, }, }, ``` -------------------------------- ### Set INCIDENT_IO_API_KEY in .env Source: https://factory.mastra.ai/configure/incidentio Set this environment variable on the Factory Server to use a self-managed incident.io connection. The key must have permission to read incidents and follow-ups and to update follow-up statuses. When present, this explicit integration takes precedence over a Platform connection and is deployment-global. ```dotenv INCIDENT_IO_API_KEY=your-incident-io-api-key ``` -------------------------------- ### Opt out of telemetry with MASTRA_TELEMETRY_DISABLED Source: https://factory.mastra.ai/reference/create-factory Disable CLI telemetry by setting MASTRA_TELEMETRY_DISABLED=1 before running create-factory with the --no-platform flag. Shown for npm, pnpm, Yarn, and Bun package managers. ```bash MASTRA_TELEMETRY_DISABLED=1 npx create-factory@latest my-mastra-factory --no-platform ``` ```bash MASTRA_TELEMETRY_DISABLED=1 pnpm dlx create-factory@latest my-mastra-factory --no-platform ``` ```bash MASTRA_TELEMETRY_DISABLED=1 yarn dlx create-factory@latest my-mastra-factory --no-platform ``` ```bash MASTRA_TELEMETRY_DISABLED=1 bun x create-factory@latest my-mastra-factory --no-platform ``` -------------------------------- ### shutdown() method Source: https://factory.mastra.ai/reference/mastra-factory-api Stops background dispatch owned by the Factory runtime during server shutdown. Returns a Promise. The server remains responsible for the Mastra instance and its other workers. ```typescript await factory.shutdown() ``` -------------------------------- ### Slack test message Source: https://factory.mastra.ai/troubleshooting Send this message to the Slack app to verify integration. Confirm a reply, the selected Factory, and the corresponding session in the web app. Reply in the same thread to confirm conversation continuity. ```text Inspect the README and summarize the documented setup steps. Do not change files. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.