Skip to content

The open alternative to Salesforce, designed for AI.

feat(cli): introduce the Twenty command line (#27295)

Weikod82573148f49
diff --git a/packages/twenty-cli/.oxlintrc.json b/packages/twenty-cli/.oxlintrc.json
new file mode 100644
index 00000000000..470ab3c8640
--- /dev/null
+++ b/packages/twenty-cli/.oxlintrc.json
@@ -0,0 +1,60 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "plugins": ["typescript", "import", "unicorn"],
+ "jsPlugins": ["../twenty-oxlint-rules/dist/oxlint-plugin.mjs"],
+ "options": {
+ "typeAware": true
+ },
+ "categories": {
+ "correctness": "off"
+ },
+ "ignorePatterns": ["node_modules", "dist"],
+ "rules": {
+ "func-style": ["error", "declaration", { "allowArrowFunctions": true }],
+ "no-console": "off",
+ "no-control-regex": "off",
+ "no-debugger": "error",
+ "no-duplicate-imports": "error",
+ "no-undef": "off",
+ "no-unused-vars": "off",
+ "no-redeclare": "off",
+ "import/no-duplicates": "error",
+ "typescript/no-redeclare": "error",
+ "typescript/ban-ts-comment": "error",
+ "typescript/consistent-type-imports": [
+ "error",
+ {
+ "prefer": "type-imports",
+ "fixStyle": "inline-type-imports"
+ }
+ ],
+ "typescript/explicit-function-return-type": "off",
+ "typescript/explicit-module-boundary-types": "off",
+ "typescript/no-empty-object-type": [
+ "error",
+ {
+ "allowInterfaces": "with-single-extends"
+ }
+ ],
+ "typescript/no-empty-function": "off",
+ "typescript/no-explicit-any": "error",
+ "typescript/no-unused-vars": [
+ "warn",
+ {
+ "vars": "all",
+ "varsIgnorePattern": "^_",
+ "args": "after-used",
+ "argsIgnorePattern": "^_"
+ }
+ ],
+ "typescript/no-floating-promises": "error",
+ "typescript/no-misused-promises": "error",
+ "twenty/no-miscased-acronym-in-identifier": "error",
+ "twenty/types-folder-filename": [
+ "error",
+ {
+ "convention": "kebab-case-type-suffix"
+ }
+ ]
+ }
+}
diff --git a/packages/twenty-cli/CONTRIBUTING.md b/packages/twenty-cli/CONTRIBUTING.md
new file mode 100644
index 00000000000..378378a164d
--- /dev/null
+++ b/packages/twenty-cli/CONTRIBUTING.md
@@ -0,0 +1,114 @@
+# Contributing to Twenty CLI
+
+This package is the `twenty` executable in the Twenty monorepo. Its Nx project
+is named `twenty-cli`; its Yarn workspace and npm package are named `twenty`.
+Follow the repository's development instructions and nearby code conventions.
+
+## Build and verify
+
+Run these from the repository root after installing its dependencies:
+
+```bash
+yarn nx build twenty-cli
+node packages/twenty-cli/dist/cli.cjs --help
+yarn nx lint twenty-cli
+yarn exec tsgo -p packages/twenty-cli/tsconfig.json --noEmit
+```
+
+Tests that use real applications or SDK parity references require the repository
+SDK to be built. Its Nx target builds its dependencies:
+
+```bash
+yarn nx build twenty-sdk
+cd packages/twenty-cli
+yarn exec vitest run --maxWorkers=2
+```
+
+For a focused change, pass its test file or directory to `vitest run`. Command
+tests execute the public command runner with local HTTP fixtures. Worker tests
+exercise subprocess output, cancellation and snapshot lifetime. Parity suites
+compare generated source and artifacts against the SDK implementation;
+the SDK is a test reference, not a runtime tooling dependency.
+
+Rebuild `twenty-shared` with `--skip-nx-cache` after switching branches or changing
+shared exports. Generated `dist` directories are not tracked, and stale outputs
+can invalidate dependent test and typecheck results. Use the direct TypeScript
+command above when checking a fix rather than relying on an Nx cache hit.
+
+No live workspace is required for the unit suite. Passing it does not establish
+live authorization, remote upload or server-version compatibility. Exercise
+changed server workflows against a disposable workspace when appropriate.
+
+## Package map
+
+| Location | Responsibility |
+| --- | --- |
+| `src/catalog` | Command definitions, topics and lazy handler loading |
+| `src/commands` | Command orchestration and user-visible results |
+| `src/program` | Argument parsing, target setup, interaction and command lifecycle |
+| `src/config`, `src/target`, `src/oauth` | Saved connections, target selection and authentication |
+| `src/transport` | HTTP/GraphQL requests, proxy routing, limits and cancellation |
+| `src/metadata`, `src/data` | Workspace metadata inspection and record reads |
+| `src/doctor` | Read-only setup and connection diagnostics |
+| `src/app` | Project tooling and application lifecycle, see its [module map](src/app/README.md) |
+| `src/input`, `src/output` | Input parsing, human/JSON/NDJSON output and error contracts |
+| `app-template-overlay` | CLI-based test harness applied over the shared app template |
+
+Command definitions are the source for help and `twenty commands`. Keep handlers
+lazy so discovery does not load compiler or app code. Put a workflow's rules in
+its owning module; a command handler should connect parsed input, that module
+and output. Preserve meaningful behavior tests when moving implementation files.
+
+## Application tooling guarantees
+
+The [application module documentation](src/app/README.md) describes each stage.
+Changes must preserve these contracts:
+
+- App definitions execute as trusted code in a disposable worker. The worker
+ contains process exits, filters CLI credentials and captures bounded output;
+ it is not a filesystem or network sandbox. Executable configs stay in the
+ worker, and only serializable requests and results cross IPC.
+- A build's immutable snapshot stays alive until its consumers finish. Uploads
+ verify containment, size and checksums. Failed or cancelled work must release
+ the snapshots it owns without removing another build's files.
+- Apply reports which remote phases completed and whether the outcome is known.
+ Do not retry writes or claim rollback when the server's result is unknown.
+ Each apply uses a fresh preview; approval does not carry across dev revisions.
+- Pull stages source writes and its target-bound baseline together. Ordinary
+ failures restore originals; interrupted workers and failed rollback report
+ uncertainty and retain recovery information. Unsupported definitions remain
+ visible in coverage reports.
+- JSON emits one result envelope. Streaming commands honor backpressure, bound
+ buffering and emit a terminal result or error. Cancellation exits 130 unless
+ the operation has already acknowledged its completed result.
+
+## Packaging
+
+Vite builds the CLI, its worker and lazy chunks into `dist`. It also copies the
+`create-twenty-app` template and the CLI test-harness overlay there. Chokidar,
+esbuild, tinyglobby and the CLI's TypeScript parser are runtime dependencies;
+other imported libraries are bundled. The parser is separate from the app's
+compiler used for typechecking.
+
+The archive includes the command reference, contributor guide and application
+module READMEs so their relative links also work outside a repository checkout.
+It does not include the CLI's TypeScript implementation or tests.
+
+For packaging changes, build and inspect the archive before release:
+
+```bash
+yarn workspace twenty pack --dry-run
+```
+
+Check both executable entry points, lazy chunks and templates in the packed
+package. Smoke-test help and app initialization from an extracted archive with
+its declared dependencies. This checks packaging without publishing anything.
+
+## App integration tests
+
+`app-template-overlay` supplies the integration-test setup for CLI-created apps.
+It deploys the app before tests and uninstalls it afterward by invoking the
+installed CLI with `--json`. Apps invoke the executable rather than import the
+CLI as a library or add it as a dependency. See the
+[template contract](docs/commands.md#create-an-app) for executable selection and
+the [compiler requirements](src/app/typecheck/README.md) for project setup.
diff --git a/packages/twenty-cli/README.md b/packages/twenty-cli/README.md
index b87067ff1cd..6ec4f73dbe7 100644
--- a/packages/twenty-cli/README.md
+++ b/packages/twenty-cli/README.md
@@ -1,6 +1,83 @@
# Twenty CLI
-The new command-line interface for [Twenty](https://twenty.com) is coming soon.
+Work with [Twenty](https://twenty.com) from your terminal: connect to workspaces,
+inspect metadata and records, send API requests, and develop applications.
-This package does not provide an executable yet. For the currently available CLI,
-use [twenty-sdk](https://www.npmjs.com/package/twenty-sdk).
+Build this CLI from source using the instructions below. It supports
+development-app deployment. Application publishing is not supported.
+
+## Get started
+
+Use Node.js 24.5 or later within Node 24 and the repository's Yarn setup. From
+the repository root:
+
+```bash
+yarn nx build twenty-cli
+node packages/twenty-cli/dist/cli.cjs --help
+```
+
+The examples below use `twenty` for the built executable. Run it as
+`node /absolute/path/to/twenty/packages/twenty-cli/dist/cli.cjs`.
+
+```bash
+twenty doctor --offline
+twenty auth login --url https://acme.twenty.com --name dev --use
+twenty metadata object list
+twenty data list companies --limit 5
+twenty open
+```
+
+Replace the example URL with your workspace's address. Workspace commands do
+not require an application project. Use `--remote <name>` to select another
+saved connection and `--json` for a structured result.
+
+## Develop an application
+
+```bash
+twenty app init my-app
+cd my-app
+yarn install
+twenty app build
+twenty app apply --create --remote dev
+twenty app dev --remote dev
+```
+
+`app init` writes files without installing dependencies. `app build` checks the
+project locally. `app apply --create` registers and installs a new development
+app, uploads its build and synchronizes its metadata. Once registered, inspect
+changes with `twenty app plan` before applying them. `app dev` watches inputs and
+syncs successful builds.
+
+Missing definitions imply remote deletions by default. Pass `--no-delete` to
+preserve them. Object and field deletions require confirmation because they
+also delete stored data. Pull can overwrite local edits; read its
+[reconciliation rules](docs/commands.md#pull-an-app) before using it.
+
+## CLI and app dependencies
+
+The CLI is intended to be installed globally, separately from each app. Apps
+keep `twenty-sdk` as a development dependency for authoring and build-time APIs,
+`typescript` for checks, and
+`twenty-client-sdk` when they use a generated API client. Neither apps nor SDK
+packages need `twenty` in their dependencies or devDependencies. CI can pin its
+CLI installation separately.
+
+The CLI owns builds and filesystem operations. It uses the app's installed
+SDK authoring exports and TypeScript compiler. Configuration and project-reference
+errors fail builds. See [build requirements](docs/commands.md#build-and-check-an-app)
+for supported SDK exports and compiler configuration.
+
+Use `twenty doctor --offline` to inspect which package owns the `twenty`
+executable on PATH. A missing project-local CLI is normal.
+
+## Documentation
+
+- [Command reference](docs/commands.md), authentication, flags, output, permissions
+ and recovery for each workflow.
+- [Contributing](CONTRIBUTING.md), package structure, builds, tests and release checks.
+- [Application tooling](src/app/README.md), module responsibilities and invariants.
+
+Run `twenty commands` for the command inventory or `twenty <command> --help` for
+its arguments and options.
+
+Generated next-step commands use PowerShell on Windows and POSIX shell syntax on macOS/Linux.
diff --git a/packages/twenty-cli/app-template-overlay/src/__tests__/global-setup.ts b/packages/twenty-cli/app-template-overlay/src/__tests__/global-setup.ts
new file mode 100644
index 00000000000..abc8acab503
--- /dev/null
+++ b/packages/twenty-cli/app-template-overlay/src/__tests__/global-setup.ts
@@ -0,0 +1,56 @@
+import { runTwenty } from './run-twenty';
+
+function validateEnv(): { apiUrl: string; apiKey: string } {
+ const apiUrl = process.env.TWENTY_API_URL;
+ const apiKey = process.env.TWENTY_API_KEY;
+
+ if (!apiUrl || !apiKey) {
+ throw new Error(
+ 'TWENTY_API_URL and TWENTY_API_KEY must be set.\n' +
+ 'Start a local server: yarn twenty docker:start\n' +
+ 'Or set them in vitest env config.',
+ );
+ }
+
+ return { apiUrl, apiKey };
+}
+
+async function checkServer(apiUrl: string) {
+ let response: Response;
+
+ try {
+ response = await fetch(`${apiUrl}/healthz`);
+ } catch {
+ throw new Error(
+ `Twenty server is not reachable at ${apiUrl}. ` +
+ 'Make sure the server is running before executing integration tests.',
+ );
+ }
+
+ if (!response.ok) {
+ throw new Error(`Server at ${apiUrl} returned ${response.status}`);
+ }
+}
+
+export async function setup() {
+ const { apiUrl } = validateEnv();
+
+ await checkServer(apiUrl);
+ await runTwenty(['app', 'uninstall', '--yes']);
+
+ const result = await runTwenty(['app', 'apply', '--create']);
+
+ if (!result.ok) {
+ throw new Error(
+ `App apply failed: ${result.error.code} ${result.error.message}`,
+ );
+ }
+}
+
+export async function teardown() {
+ const result = await runTwenty(['app', 'uninstall', '--yes']);
+
+ if (!result.ok) {
+ console.warn(`App uninstall failed: ${result.error.message}`);
+ }
+}
diff --git a/packages/twenty-cli/app-template-overlay/src/__tests__/run-twenty.ts b/packages/twenty-cli/app-template-overlay/src/__tests__/run-twenty.ts
new file mode 100644
index 00000000000..9a9ffeb7650
--- /dev/null
+++ b/packages/twenty-cli/app-template-overlay/src/__tests__/run-twenty.ts
@@ -0,0 +1,66 @@
+import { spawn } from 'child_process';
+import { delimiter, join } from 'path';
+
+type TwentyCliError = {
+ code: string;
+ message: string;
+ hint?: string;
+};
+
+export type TwentyCliResult =
+ | { ok: true; data: unknown }
+ | { ok: false; error: TwentyCliError };
+
+function withoutProjectBinaries(pathValue: string) {
+ return pathValue
+ .split(delimiter)
+ .filter(
+ (entry) =>
+ entry !== process.env.BERRY_BIN_FOLDER &&
+ !entry.endsWith(join('node_modules', '.bin')),
+ )
+ .join(delimiter);
+}
+
+export function runTwenty(args: string[]): Promise<TwentyCliResult> {
+ const executable = process.env.TWENTY_CLI ?? 'twenty';
+
+ return new Promise((resolve, reject) => {
+ const child = spawn(executable, [...args, '--json'], {
+ env: {
+ ...process.env,
+ PATH: withoutProjectBinaries(process.env.PATH ?? ''),
+ },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+ let stdout = '';
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ stdout += chunk;
+ });
+
+ child.on('error', (error: NodeJS.ErrnoException) => {
+ reject(
+ error.code === 'ENOENT'
+ ? new Error(
+ `${executable} was not found. Install the Twenty CLI globally, or set TWENTY_CLI to its path.`,
+ )
+ : error,
+ );
+ });
+
+ child.on('close', (exitCode) => {
+ try {
+ resolve(JSON.parse(stdout));
+ } catch {
+ reject(
+ new Error(
+ `${executable} ${args.join(' ')} exited with code ${exitCode} without a JSON result. ` +
+ 'Check that it is the Twenty CLI (twenty --version), or set TWENTY_CLI to its path.',
+ ),
+ );
+ }
+ });
+ });
+}
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.md
new file mode 100644
index 00000000000..c6b75119714
--- /dev/null
+++ b/packages/twenty-cli/docs/commands.md
@@ -0,0 +1,540 @@
+# Command reference
+
+For available commands and flags, run `twenty commands` or
+`twenty <command> --help`. This reference describes behavior, permissions and
+failure recovery. See the [README](../README.md) to build and start the CLI.
+
+- [Connections and authentication](#connections-and-authentication)
+- [Raw API requests](#raw-api-requests)
+- [Network proxies](#network-proxies)
+- [Doctor](#diagnose-your-setup)
+- [Open](#open-the-workspace)
+- [Metadata](#inspect-the-data-model)
+- [Records](#read-records)
+- [App init](#create-an-app) and [add](#add-definitions-to-an-app)
+- [Build and typecheck](#build-and-check-an-app)
+- [Plan](#preview-app-changes), [apply](#apply-an-app) and [dev](#develop-an-app)
+- [Pull](#pull-an-app) and [uninstall](#uninstall-an-app)
+- [Function execution](#execute-an-app-function) and [logs](#watch-app-logs)
+- [Expired browser sessions](#expired-browser-sessions)
+- [Output and exit codes](#output)
+
+## Connections and authentication
+
+```bash
+twenty auth login --url https://acme.twenty.com --name dev --use
+twenty auth status --remote dev
+twenty remote list
+twenty remote use dev
+```
+
+A remote is a named workspace connection. Browser login requires an interactive
+terminal and saves a user OAuth session after verifying it with the server.
+Workspace commands do not require an app project or register an application in
+that workspace. Application deployment is a separate operation.
+
+For scripts, pass an API key through standard input:
+
+```bash
+printf '%s' "$TWENTY_API_KEY" | twenty auth login --with-token --url https://acme.twenty.com --name ci
+```
+
+Credentials and remote settings are saved in `~/.twenty/config.json`, with
+owner-only file permissions. Login validates credentials before saving them.
+`--use` makes the remote the default; the first remote also becomes the default.
+Use `twenty auth login --remote dev` to sign in again to a saved URL. Changing an
+existing remote's URL requires `--replace`.
+
+Commands select a workspace in this order:
+
+1. `--remote <name>`, ignoring environment target settings with a warning.
+2. `TWENTY_REMOTE`, which cannot be combined with either API environment variable.
+3. `TWENTY_API_URL` and `TWENTY_API_KEY`, which must both be set and are not saved.
+4. The saved default remote.
+
+```bash
+twenty remote rename dev development
+twenty auth logout --remote development
+twenty remote remove development
+```
+
+Logout forgets saved credentials but keeps the remote. Removing a remote deletes
+both. Neither command revokes the server-side credential. `twenty auth token`
+prints the selected credential for use in another tool; its output is a secret,
+including in JSON mode.
+
+`--no-input` disables prompts and browser opening. JSON/NDJSON output, redirected
+stdin and CI also disable interaction. Pass required values and explicit
+command-specific approvals, such as `app apply --create` or `--yes`, in scripts.
+Disabling prompts does not approve an operation.
+
+## Raw API requests
+
+```bash
+twenty api rest '/rest/companies?limit=5'
+twenty api graphql --query '{ companies(first: 2) { edges { node { name } } } }'
+twenty api graphql --metadata --query '{ currentWorkspace { displayName } }'
+```
+
+Both commands use the selected connection without an app project. REST paths
+stay inside its API URL; credentials are not sent to an arbitrary host. REST
+uses GET by default. `--body` accepts JSON inline, `@file.json`, or `-` for stdin
+and requires an explicit `--method`.
+
+```bash
+twenty api rest /rest/companies --method POST --body '{"name":"Example"}'
+twenty api graphql --query @query.graphql --variables @variables.json
+```
+
+GraphQL uses the core endpoint by default and the metadata endpoint with
+`--metadata`. `--query` accepts a document inline, `@file.graphql` or `-`;
+`--variables` accepts a JSON object through the same input forms. Only one option
+can read stdin. Mutations and REST writes execute directly, without the app
+plan/apply confirmation flow. Server permissions still apply.
+
+Human output displays the response body. In JSON mode, REST returns status,
+selected response headers and body in `data`; GraphQL returns its data there.
+HTTP and GraphQL errors use the standard error envelope. Responses are bounded
+by the transport's 16 MiB limit; raw requests do not paginate automatically.
+
+## Network proxies
+
+API requests, browser sign-in requests and app uploads honor `HTTP_PROXY`,
+`HTTPS_PROXY` and `NO_PROXY` (also their lowercase equivalents, which take
+precedence). `HTTP_PROXY` also covers HTTPS when `HTTPS_PROXY` is unset.
+Use `NO_PROXY=localhost,127.0.0.1` to bypass a proxy for local development,
+or `NO_PROXY=*` to bypass it for all hosts. Proxies must support HTTP CONNECT.
+For a corporate certificate authority, set `NODE_EXTRA_CA_CERTS` before starting
+the CLI. TLS certificate verification stays enabled.
+
+## Diagnose your setup
+
+```bash
+twenty doctor
+twenty doctor --remote staging --path ./my-app --json
+twenty doctor --offline
+```
+
+`doctor` checks the running CLI and Node version, executable ownership and precedence on PATH, configuration, the selected connection, and an app's installed SDK authoring exports. It works without an app or saved remote; unavailable optional checks are marked `skipped`. Use `--path` to require a specific app. PATH inspection does not execute binaries or inspect shell aliases, functions or command caches; package-manager wrappers whose owner cannot be determined are reported as unknown.
+
+By default it sends one read-only request to the selected workspace's metadata endpoint to check access. This does not prove access to every object or app operation. `--offline` disables network requests. Doctor never imports app or SDK code, builds an app, installs packages, repairs files, or refreshes credentials. An expired OAuth access token skips the network check: it produces a warning when a refresh token is saved (renewal remains unverified), or a failure when there is none. Renew through `twenty auth status` for the same remote, or sign in again.
+
+Each check has an `id`, `status` (`pass`, `warning`, `fail`, or `skipped`), message, and optional code, hint and details. Failed checks exit 1 with `DOCTOR_FAILED`; JSON includes the checklist in `error.details.checks`. Otherwise exit 0, with the same checklist in `data.checks`, including warnings and skipped checks. Human output includes the full checklist in either case. Ctrl+C exits 130. Output omits credentials, server response bodies and user identity information, but includes local paths and the selected API URL.
+
+## Open the workspace
+
+```bash
+twenty open
+twenty open settings/applications
+twenty open --remote staging --url-only --json
+```
+
+`open` asks the selected workspace for its web address, which is its custom domain when one is enabled and its subdomain otherwise. It then opens that address, or a page inside it, in your default browser. The address carries no credentials, so sign in to the workspace in the browser if needed. A browser only opens in an interactive terminal: with `--no-input`, JSON output, redirected stdin or in CI, the command stops with `USAGE` (exit 2) unless `--url-only` is set, which prints the address instead. A page is a path inside the workspace; one that would lead to another site is refused with `USAGE`.
+
+If the workspace returns no web address, `open` uses the frontend origin from
+the server's OAuth discovery document. It drops the authorization path, query,
+fragment and any URL credentials. Invalid addresses and failed metadata
+authentication still stop the command.
+
+## Inspect the data model
+
+```bash
+twenty metadata object list
+twenty metadata object describe companies
+twenty metadata field list companies --all
+twenty metadata field describe companies tier --json
+```
+
+Object arguments accept exact, case-sensitive singular or plural API names. Field arguments accept exact API names. Labels are never matched, and ambiguous names fail with `AMBIGUOUS_RESOURCE` (exit 2). Missing names return `NOT_FOUND` (exit 4).
+
+Object describe shows object properties. Use field list to inspect its fields; system fields are hidden unless `--all` is present. Field describe can inspect a named system field directly. Each field reports its own owner, independently of its object. If application names cannot be read, Custom remains identifiable and other owners are reported as unknown with a warning; ownership is not a permission check.
+
+Inspection reads every metadata page before resolving names, so a match on an early page cannot hide an ambiguity on a later one. Each object/field traversal is capped at 10,000 items or 16 MiB of node data; exceeding either limit fails instead of returning incomplete metadata. Requests use the selected connection and fetch live metadata on every invocation. Human output shows labels, constraints, options and relationships; JSON also preserves IDs, universal identifiers, settings and relationship endpoints.
+
+## Read records
+
+```bash
+twenty data list companies --limit 20
+twenty data list companies --filter 'employees[gte]:5000' --order-by 'employees[DescNullsLast]'
+twenty data get people <id> --json
+twenty data list people --all --format ndjson
+```
+
+These commands resolve the same exact singular/plural API names as metadata inspection, including custom objects, and reuse the selected connection. They require access to object metadata as well as the records. `data get` reads one record with one level of related records; it does not recursively expand or paginate relations.
+
+`data list` reads one page by default, with a default `--limit` of 50 and a maximum of 200. `--cursor` passes the opaque REST `starting_after` cursor. `--filter` and `--order-by` pass REST expressions unchanged; server ordering and its ID tie-breaker are preserved. Every result includes page information, and human output shows a next-page command. Pagination is not a database snapshot; concurrent writes can change results or totals during traversal.
+
+`--fields name,employees` selects human table columns only. Tables shorten cells longer than 60 characters and display absent values as `-`. JSON and NDJSON retain full records, including composite values and relation identifiers.
+
+`--all` reads every remaining page, including when starting from `--cursor`. Human/JSON results are limited to 10,000 records and 16 MiB of serialized payload; human tables are also bounded. Exceeding a limit returns `RESULT_LIMIT_EXCEEDED` (exit 2), with no partial success. Every HTTP response is separately limited to 16 MiB, including in NDJSON mode.
+
+Use explicit `--format ndjson` for larger traversals. It emits numbered `start`, `record`, page `progress`, and terminal `result`/`error` events, reading one page at a time and waiting for stdout when the reader is slow. `resumeCursor` advances only after a complete page has been written. After a partial page or a failure, resume with the last reported cursor and the same filter/order; records from the partial page may repeat. With no completed page, use the original cursor or restart without one. A stream without a terminal event is incomplete. Without `--all`, NDJSON still reads only one page.
+
+## Create an app
+
+```bash
+twenty app init my-app
+twenty app init billing --path ./apps/billing --display-name Billing --json
+```
+
+`app init` creates a new app from the template bundled with the CLI, with fresh universal identifiers and `twenty-client-sdk`, `twenty-sdk` and `twenty-ui` pinned to the exact version the CLI was built with. It needs no installed SDK, saved remote or network access, and it only writes files: it does not install dependencies, create a Git repository, start a server, sign in or sync anything. The next steps it prints, and returns as `data.nextSteps` in JSON, cover the rest, and name the remote when you pass `--remote`.
+
+The name must be a valid npm package name, otherwise the command fails with `INVALID_APP_NAME` (exit 2). The app is created in `./<name>` unless `--path` says otherwise; `--display-name` and `--description` set what Twenty shows. The target must not exist yet or be an empty directory; anything else fails with `APP_PATH_UNAVAILABLE` (exit 6) and nothing is written. The template is rendered in a hidden sibling directory and moved into place only after every placeholder was filled, so a failure or Ctrl+C does not leave a half-created app behind. An existing empty directory is filled with create-only writes, so a file that appears there meanwhile is never overwritten.
+
+New apps declare `engines.twenty` as `>=` the template release version. The server
+checks this range against the workspace's completed upgrade version on apply.
+Upgrade the workspace before deploying a newer template, including during local
+development. Adjust the range only after testing the app against older versions.
+
+The integration tests of a new app run against a workspace through this CLI.
+`src/__tests__/global-setup.ts` uninstalls any previous copy, runs
+`twenty app apply --create` before the tests and `twenty app uninstall --yes`
+after them, through `src/__tests__/run-twenty.ts`. That helper runs `twenty` with
+`--json`, returns its result, and passes its progress through. It skips the
+binaries a package manager puts first on `PATH` inside `yarn test`, so the
+globally installed CLI runs; set `TWENTY_CLI` to use another executable.
+Credentials come from `TWENTY_API_URL` and `TWENTY_API_KEY`,
+which the template's Vitest config sets.
+
+## Add definitions to an app
+
+```bash
+twenty app add
+twenty app add object --name invoice --name-plural invoices --no-input
+twenty app add field --name amount --type NUMBER --object <object-universal-identifier> --json
+twenty app add logic-function --name send-invoice --no-input
+twenty app add front-component --name invoice-panel --no-input
+```
+
+`app add` creates one standalone definition from the CLI's templates.
+It discovers the containing app, or accepts `--path <app-directory>`. No sign-in
+or workspace connection is needed. Use `object`, `field`, `logic-function` or
+`front-component`; other generators and optional object views, layouts and menu
+companions are not supported.
+
+Files are created under `src/objects`, `src/fields`, `src/logic-functions` and
+`src/front-components`, with kebab-case filenames and fresh universal UUIDs.
+Existing files are never replaced, including filename collisions after case
+normalization. Symlinked destination paths are refused. Both cases exit 6.
+JSON returns app-relative paths in `data.createdPaths`.
+
+Omitted values are prompted only in a human interactive terminal. With `--json`,
+`--no-input`, redirected stdin or CI, required values must be supplied explicitly
+or the command exits 2 before creating files. Labels default to the name; fields
+default to `TEXT`. `--object` requires the parent's universal identifier, not its
+workspace database ID. Relations additionally require `--target-object` and
+`--target-field`; `--relation-type` defaults to `ONE_TO_MANY` and `--on-delete`
+to `CASCADE`. The command does not create the reverse field or
+check that these identifiers exist in a workspace.
+
+Review the generated definition and its type-specific settings, then run
+`twenty app build` and `twenty app plan`. Generation does not install or apply
+anything. Cancellation before the file is created exits 130; existing app files
+stay untouched, although empty parent directories can remain.
+
+## Build and check an app
+
+```bash
+twenty app build
+twenty app typecheck
+twenty app build --path ./apps/billing --json
+```
+
+These commands run inside an app project: the nearest folder, from the current one upwards, whose `package.json` depends on `twenty-sdk`. Pass `--path` to choose another app. In a folder that contains several apps, `--path` is required, and the error lists them.
+
+The CLI owns manifest generation, bundling and typechecking. It uses the app's
+installed `twenty-sdk` authoring exports (`define` and `front-component`, SDK
+`>=1.23.0`). An app without an installed SDK fails with `SDK_NOT_INSTALLED`;
+missing or unsupported authoring
+exports fail with `SDK_SOURCE_UNSUPPORTED`; an incompatible SDK Node requirement
+fails with `NODE_VERSION_UNSUPPORTED`. The CLI never installs dependencies or
+substitutes another SDK. Yarn Plug'n'Play is not supported; use
+`nodeLinker: node-modules`.
+
+Typechecking uses `typescript` installed in the app or its workspace, never the
+global CLI's parser dependency. Missing TypeScript fails with
+`TYPESCRIPT_NOT_INSTALLED`. Configuration errors and unbuilt project references
+fail with `TYPECHECK_FAILED`. For example, a project with an unbuilt reference
+to `tsconfig.spec.json` can report `TS6305`: remove an unintended reference, or
+build the referenced project before checking the app. Changing compiler versions
+can also change diagnostics.
+
+Builds run in a separate worker process. That process does not receive the CLI's
+connections or credentials: `TWENTY_API_URL`, `TWENTY_API_KEY`, `TWENTY_REMOTE`
+and every `TWENTY_*` token, key, secret or password variable are removed from its
+environment. App and SDK output becomes `PROJECT_OUTPUT` diagnostics; an app
+that exits the process fails with `WORKER_FAILED`. This separates output and
+process state; it is not a sandbox for untrusted code.
+
+`app build` produces a temporary snapshot under `.twenty/cli/snapshots`, reports
+its files, upload roles, sizes, SHA-256 checksums, content hash and manifest, then
+deletes the snapshot. Nothing is uploaded or kept. `app typecheck` checks the
+project without writing files. Build and type errors exit 1 with diagnostics in
+`error.details.diagnostics`. Worker failures report the underlying code in
+`error.details.toolingErrorCode`. Worker process failures use
+`error.details.workerErrorCode`. Ctrl+C cancels the worker and exits 130; a
+worker that does not stop within a few seconds is killed. The JSON `sdk` object
+identifies the app's installed authoring SDK version.
+
+The CLI version determines build rules, including derived permission identifiers.
+Different tooling versions can produce different manifests. Run `twenty app plan`
+and inspect the changes before applying an app with a different tooling version.
+
+## Preview app changes
+
+```bash
+twenty app plan --remote dev
+twenty app plan --path ./apps/billing --no-delete --json
+```
+
+`app plan` builds once with the CLI pipeline, releases the temporary snapshot, then requests the server's metadata preview with `dryRun: true`. It uses the usual connection selection and requires the server's `APPLICATIONS` permission. The server enforces authorization, ownership and manifest/version compatibility. No registration, installation, upload or metadata synchronization is performed, and planning never advances a pull base. The local build can generate app artifacts, just as `app build` does.
+
+JSON marks plans with `plan: true`. A plan is not a saved approval: remote changes can alter what a later apply does. A missing owned application registration returns `PLAN_UNAVAILABLE` (exit 1). Register the app with `twenty app apply --create`, then plan again.
+
+Entities missing from source are included as deletions by default. `--no-delete` passes `inferDeletionFromMissingEntities: false` to the preview. Human output lists every action, identifies object/field deletions that would remove stored data, and shows the opt-out hint. JSON includes action details and counts. Application-variable values, including previous values in updates, are redacted from all plan actions regardless of their `isSecret` setting. A plan exceeding 10,000 actions or the transport's 16 MiB response limit fails instead of displaying an incomplete preview.
+
+## Apply an app
+
+```bash
+twenty app apply --remote dev
+twenty app apply --create --json
+twenty app apply --no-delete
+```
+
+`app apply` builds the app once with the CLI pipeline and keeps that build's snapshot until it finishes, so the files it uploads are the ones it built. It then asks the workspace for a fresh preview, shows it, and applies it: it installs the development app if needed, uploads the snapshot files, synchronizes the manifest, and regenerates the app's typed API client. It needs the server's `APPLICATIONS` and `UPLOAD_FILE` permissions.
+
+- **New apps.** An app without a registration needs `--create`, or a yes at the prompt in an interactive terminal. The CLI then registers the app (the server also requires `API_KEYS_AND_WEBHOOKS` for this), installs it, and previews it before uploading anything. Without approval it stops with `CREATE_REQUIRED` (exit 2). The registration's client secret is never requested.
+- **Deletions.** Entities missing from source are deleted by default, as in `app plan`; `--no-delete` keeps them and is sent to both the preview and the sync. Object and field deletions permanently delete stored data, so they need `--yes` or a yes at the prompt. Otherwise the command stops with `CONFIRMATION_REQUIRED` (exit 2) before changing anything. `--yes` never changes which entities are deleted.
+- **Uploads.** File bytes go straight to the upload URLs the server returns, without the CLI's credentials. Each file is checked against the build's size and SHA-256 before anything is uploaded.
+- **Pull baseline.** After an acknowledged sync, the CLI fetches the workspace ID and fresh application export, then atomically records `.twenty/cli/pull-base.json`. This baseline lets `app pull` distinguish workspace changes from local edits. It is bound to the normalized API URL, workspace UUID and app UUID. JSON reports `pullBase: "recorded"`, `"failed"` or `"unsupported"`; only a recorded base adds `pullBase` to `completedPhases`. Invalid exports or file-write errors preserve the prior base, warn with `PULL_BASE_NOT_RECORDED`, and allow client generation to continue. A server without the export API reports `"unsupported"` without a warning on every apply. The export is recorded as the server sent it; collections it lacks are read as empty by pull. Cancellation before the base is committed exits 130 with `outcome: "applied"` and `phase: "pullBase"`.
+- **Typed client.** After the sync, the CLI fetches the app's GraphQL schema from the workspace and calls the app's own `twenty-client-sdk/generate` to regenerate the client in the app's own `node_modules/twenty-client-sdk` (`clientGeneration: "generated"`). It is skipped with a `CLIENT_NOT_GENERATED` warning when the app has no `node_modules/twenty-client-sdk` of its own, as in a hoisted workspace. A symlinked client package is followed and its target rewritten, so don't apply two apps that share one client package at the same time.
+- **Failures.** A failed apply reports `details.phase`, `details.completedPhases` and `details.outcome`: `not-started` when the failing step changed nothing, `partial` when some files were uploaded, `unknown` when a request was sent but its effect is not known, such as a failed or interrupted sync, and `applied` when the sync succeeded but baseline recording was cancelled or client generation failed. Earlier steps, like a new registration, stay done. There is no rollback and no automatic retry: run `twenty app plan` to see where the workspace stands, then apply again. After `applied`, the workspace has the new version but the client files may be incomplete: fix the problem, then run `twenty app apply` again, which repeats the preview, upload and sync before regenerating the client. Ctrl+C exits with 130 and reports the step it interrupted.
+
+Remote changes made between the preview and the sync can change what the sync does. Remote changes between the acknowledged sync and the export can also enter the saved baseline without appearing in local source; this is not an atomic server snapshot of the sync. Planning, a failed sync, or a sync with an unknown outcome never advances the baseline.
+
+## Develop an app
+
+```bash
+twenty app dev --remote dev
+twenty app dev --create --no-delete
+twenty app dev --path ./apps/billing --format ndjson --no-delete
+```
+
+`app dev` builds and syncs once, then watches for edits. Each attempt uses the
+same CLI build and strict project TypeScript checks as `app apply`. A failed
+build prints diagnostics and keeps watching; it never uploads an incomplete
+revision. It needs the same `APPLICATIONS` and `UPLOAD_FILE` permissions as apply.
+
+The CLI watches the app folder and the external local files read by definition
+loading, bundling and typechecking, including linked packages and extended
+TypeScript configs. Relative imports of missing external files watch the nearest
+existing parent, so creating the file can recover a failed build. The last
+successful input graph stays watched after a failure. `.git`, `.twenty`,
+`node_modules`, root `dist`, editor temporary files and `.DS_Store` are ignored.
+Arbitrary filesystem reads inside app code are not discovered. Restart dev after
+installing dependencies or changing the package manager's links.
+
+Only one remote apply runs at a time. The compiler can prepare a newer complete
+snapshot while that apply finishes; intermediate edits coalesce into the latest
+revision. Uploads read independent, checksum-verified files, so a later build
+cannot overwrite them. An unchanged content hash skips sync only after that
+snapshot was acknowledged by the workspace. This is eventual convergence after
+edits settle, not an atomic checkout of files being edited concurrently.
+
+Registration uses `--create` or a terminal confirmation. Deletion inference is
+on by default, with `--no-delete` to keep missing entities. Object and field
+deletions require a terminal confirmation or `--yes`. Every revision requests a
+fresh preview. An edit cancels a pending confirmation; approval for the
+old revision cannot authorize the new one. A remote failure is reported with the
+same phase/outcome details as apply and is retried only after a new source edit,
+with a new preview. Inspect `twenty app plan` when a request's outcome is unknown.
+
+After an acknowledged sync, dev records the pull base and regenerates the app's
+own typed client when its schema, generator package or generated files changed.
+Compilation pauses during generation, then explicitly rebuilds. Unchanged client
+inputs and unchanged build output prevent a generation/sync loop. A schema fetch
+failure keeps the old client and prints a warning. If generation starts writing
+and fails, dev stops because the client files may be incomplete; fix the problem
+and run `twenty app apply` before restarting dev.
+
+Use human output or `--format ndjson`; `--json` is rejected before target lookup.
+NDJSON uses ordered `progress` events with `data.kind`: `watch-ready`,
+`build-start`, `build-success`, `build-failure`, `build-skipped`, `sync-start`,
+`sync-progress`, `sync-superseded`, `sync-failure` and `sync-success`. Build events
+carry the revision, successful builds also carry the build ID and content hash.
+Output honors backpressure; buffered progress is bounded. Ctrl+C stops watching,
+cancels active requests, releases snapshots after readers settle, and exits 130
+with the interrupted remote phase when available. It does not roll back writes.
+
+An abnormal worker exit or a filesystem-watcher failure ends the session; fix
+the cause and restart `twenty app dev`. A killed process can leave temporary
+folders in `.twenty/cli/snapshots`. After stopping all dev/apply sessions for that
+app, abandoned snapshot folders can be removed.
+
+## Pull an app
+
+```bash
+twenty app pull --remote dev
+twenty app pull --path ./apps/billing --json
+twenty app pull --universal-identifier <uuid> --verbose
+```
+
+`app pull` reads the app's definition and exports its workspace metadata into the existing project. It uses the selected connection and the server's `APPLICATIONS` permission; the server decides which apps this workspace can export. It does not register an app or change the workspace. When a project has no application definition, provide `--universal-identifier`. A project declaring a different app is refused before writing.
+
+The project must have `twenty-sdk` installed, version `>=1.23.0`, with its public `twenty-sdk/define` and `twenty-sdk/front-component` exports. Pull also checks that the SDK provides the authoring APIs required by the generated files. Missing APIs fail with `SDK_SOURCE_UNSUPPORTED`; install a compatible version (2.40.0 or later). Pull does not require a project TypeScript compiler. Run `twenty app typecheck` afterwards to check the generated definitions against your installed SDK.
+
+Pull compares workspace metadata and local definitions using a baseline saved
+by apply or a previous pull in `.twenty/cli/pull-base.json`. The baseline belongs
+to one API URL, workspace UUID and application UUID.
+
+Pull overwrites local edits to entities that changed on the workspace, without a confirmation prompt. With a matching baseline, unchanged workspace entities keep their local source, and confirmed remote deletions remove their files. Without a matching baseline, local-only definitions stay in place and pull does not infer deletions. Coverage gaps, unreadable definitions and local-only nested entities are preserved and reported; gaps do not require `--force` or an opt-in partial mode. JSON includes `coverage`, `skipped`, `unreadableRelativePaths`, `localOnlyRelativePaths` and `overwrittenLocalChanges`. Without a baseline, overwritten local edits cannot be distinguished from generated source.
+
+Before replacing local files, pull stages the new content and backs up the
+originals. It updates the baseline only after writing the files. Ordinary write
+failures restore the previous files and baseline.
+
+Failures in reconciliation report `error.details.outcome`: `unchanged` after an acknowledged refusal, cancellation before writing or successful rollback; `unknown` if a worker stops without acknowledging completion or rollback fails; `pulled` if writes and baseline completed but temporary-file cleanup failed. An interrupted worker can leave files partially written; inspect the changes and retained `.twenty/cli/pull-backup-*` files before retrying. A failed rollback also reports `backupDirectory`. Ctrl+C exits 130 unless the worker acknowledges a completed commit, in which case pull returns its result.
+
+The current export contains metadata and translations, not application source assets or dependency files. Logic-function/front-component code and unsupported metadata are not regenerated. An export with nonempty `files` is refused before writing. Package files, dependency pins and the installed generated client are left alone; pull never installs dependencies. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.
+
+## Uninstall an app
+
+```bash
+twenty app uninstall --remote dev
+twenty app uninstall --yes --json
+twenty app uninstall --universal-identifier <id> --yes
+```
+
+`app uninstall` builds the app to find its universal identifier, checks that the app is installed on the target and that the workspace allows uninstalling it, then uninstalls it. `--universal-identifier` skips the build, so an app whose source no longer builds can still be uninstalled. It needs the server's `APPLICATIONS` permission.
+
+Uninstalling runs the app's uninstall hook and deletes everything the app owns, including its objects, fields and their data. It always needs `--yes`, or a yes at the prompt in an interactive terminal; otherwise it stops with `CONFIRMATION_REQUIRED` (exit 2) before changing anything. An app that is not installed returns `APP_NOT_INSTALLED` (exit 4), and one the workspace does not allow to uninstall returns `APP_NOT_UNINSTALLABLE` (exit 6).
+
+The app's registration is kept, so `twenty app apply` can install it again without `--create`. Failures report `details.phase`, `details.completedPhases` and `details.outcome`, as for apply: an uninstall request that fails after the server received it, or is interrupted with Ctrl+C, has an `unknown` outcome. Running the command again reports `APP_NOT_INSTALLED` once the app is gone. `--universal-identifier` accepts any UUID casing and sends the canonical lowercase form.
+
+## Execute an app function
+
+```bash
+twenty app exec --name add-numbers --remote dev --payload '{"a":2,"b":3}'
+twenty app exec --universal-identifier <uuid> --payload @payload.json --json
+printf '{"a":4,"b":7}' | twenty app exec --name add-numbers --remote dev --payload - --json
+```
+
+Run from the app folder or pass `--path`. The CLI reads app definitions to find
+its functions, then executes the selected function's deployed code. Sync local
+changes with `app apply` or `app dev` first. Execution does not build bundles,
+typecheck, sync, register or install the app.
+
+Choose exactly one of `--name` (exact deployed name), `--universal-identifier`,
+`--post-install`, `--pre-install` or `--uninstall-hook`. Hook selectors run the
+hook's code and its side effects without installing or uninstalling the app.
+Payloads must be JSON objects, supplied inline, through `@file`, or through `-`
+for stdin; the default is `{}`. The selected function must belong to both the
+local app manifest and the installed app on the target workspace.
+
+The current server requires a signed-in user and the `APPLICATIONS` and
+`WORKFLOWS` settings permissions. Sign in with `twenty auth login --url <url>
+--name dev`, then pass `--remote dev`. API keys, including environment API-key
+targets, cannot execute logic functions. The server additionally restricts
+which functions the user may run on demand.
+
+Human output shows status, duration, returned data, error and logs. `--json`
+returns those fields in the standard envelope; NDJSON is not supported. A
+function returning a non-SUCCESS status exits 1 with `EXECUTION_FAILED`, keeping
+its data, logs and error in `error.details` with `outcome: "completed"`.
+
+There are no automatic retries. The request deadline uses the deployed
+function's timeout plus 60 seconds. A lost response or Ctrl+C can leave the
+function running on the server; the error reports `outcome: "unknown"` and asks
+you to check its effects before retrying. An acknowledged execution rejection
+reports `"not-started"`. Ctrl+C exits 130, without rolling back side effects.
+See the [execution implementation](../src/app/exec/README.md) for compatibility details.
+
+## Watch app logs
+
+```bash
+twenty app logs --remote dev
+twenty app logs --name add-numbers --remote dev
+twenty app logs --universal-identifier <uuid> --format ndjson
+```
+
+Run from the app folder or pass `--path`. This watches newly published execution
+output from every logic function in that app. Output arrives when an execution
+finishes, not line by line while it runs. It does not fetch historical logs,
+watch other apps, or build, sync, register or install anything.
+
+Names are not unique: `--name` matches every function with that exact name in the
+app. Use `--universal-identifier` to isolate one function. The two filters are
+mutually exclusive. Human output labels each execution with its function name
+and identifier; NDJSON records contain `applicationUniversalIdentifier`,
+`functionName`, `functionUniversalIdentifier` and `logs`.
+
+Some server schemas expose only log text. If the identity fields are unsupported,
+the CLI warns and subscribes once requesting only `logs`. An explicit filter
+supplies that name or identifier; unknown identities are `null` in NDJSON and
+omitted from human labels. With neither filter, those schemas cannot attribute
+mixed output to individual functions.
+
+The stream supports human output and `--format ndjson`; finite `--json` is
+rejected. Ctrl+C closes it and exits 130. A server completion exits 0. A dropped
+or stalled connection exits with an error and the emitted record count, with no
+automatic reconnect because missed logs cannot be replayed. Slow output applies
+backpressure; each SSE frame is limited to 16 MiB, with no session-size cap.
+Connection setup and gaps between received body chunks each have a 60-second
+deadline; server heartbeat comments keep quiet subscriptions alive.
+
+This uses the existing app-log subscription and its `WORKFLOWS` permission and
+application access checks. API keys and browser-login remotes are supported.
+It does not require the paid audit-log entitlement, ClickHouse history or the
+workspace-wide Settings logs API. See the [log subscription implementation](../src/app/function-logs/README.md).
+
+## Expired browser sessions
+
+For commands that use a workspace, interactive OAuth sessions are checked before
+the command starts. If a session is rejected or cannot be refreshed, the CLI
+offers to sign in again once, validates the new session, and saves its credentials
+without changing the remote's URL, default selection or other settings.
+
+API keys, JSON/NDJSON output, `--no-input`, redirected stdin and CI never trigger
+this prompt. Permission errors do not trigger sign-in either. If authentication
+fails after a command starts, the CLI stops with the login hint; it does not
+replay requests or restart an app apply. A remote changed during sign-in is left
+as-is, and the command stops with `CONFLICT`.
+
+## Output
+
+`twenty version` (or `--version`) reports the running executable's version.
+`twenty version --json` also includes Node, platform and architecture.
+`twenty commands --json` lists command arguments, flags, output modes and
+project/target requirements for scripts that discover the command surface.
+
+Commands print readable text by default. With `--json`, a command prints exactly one JSON document on stdout, including when it fails:
+
+```json
+{
+ "schemaVersion": 1,
+ "ok": true,
+ "command": "version",
+ "data": {
+ "version": "0.3.0",
+ "node": "24.9.0",
+ "platform": "darwin",
+ "arch": "arm64"
+ },
+ "warnings": []
+}
+```
+
+A failure has `"ok": false` and an `error` object with a stable `code`, a `message`, and sometimes a `hint` and `details`.
+
+Exit codes:
+
+| Code | Meaning |
+| ---- | ----------------------------------- |
+| 0 | Success |
+| 1 | Failure |
+| 2 | Usage error or missing confirmation |
+| 3 | Authentication or permission denied |
+| 4 | Not found |
+| 5 | Partial failure |
+| 6 | Conflict |
+| 130 | Cancelled |
diff --git a/packages/twenty-cli/package.json b/packages/twenty-cli/package.json
index 834bc6330e4..74bfac2380d 100644
--- a/packages/twenty-cli/package.json
+++ b/packages/twenty-cli/package.json
@@ -1,7 +1,7 @@
{
"name": "twenty",
"version": "0.3.0",
- "description": "The new command-line interface for Twenty is coming soon.",
+ "description": "The Twenty command line.",
"homepage": "https://twenty.com",
"repository": {
"type": "git",
@@ -11,5 +11,38 @@
"bugs": {
"url": "https://github.com/twentyhq/twenty/issues"
},
- "license": "AGPL-3.0"
+ "license": "AGPL-3.0",
+ "bin": "dist/cli.cjs",
+ "files": [
+ "dist",
+ "docs/commands.md",
+ "CONTRIBUTING.md",
+ "src/app/**/README.md"
+ ],
+ "scripts": {
+ "build": "npx rimraf dist && npx vite build"
+ },
+ "engines": {
+ "node": "^24.5.0"
+ },
+ "devDependencies": {
+ "@sniptt/guards": "^0.2.0",
+ "@types/node": "^24.0.0",
+ "@types/semver": "^7.5.8",
+ "cjs-module-lexer": "^2.2.0",
+ "commander": "^14.0.3",
+ "semver": "7.6.3",
+ "twenty-client-sdk": "workspace:*",
+ "twenty-shared": "workspace:*",
+ "undici": "^7.29.0",
+ "uuid": "^13.0.2",
+ "vite": "^8.0.0",
+ "vitest": "^4.1.0"
+ },
+ "dependencies": {
+ "chokidar": "^3.6.0",
+ "esbuild": "^0.28.1",
+ "tinyglobby": "^0.2.15",
+ "typescript": "^5.9.3"
+ }
}
diff --git a/packages/twenty-cli/project.json b/packages/twenty-cli/project.json
new file mode 100644
index 00000000000..89337b3cb4c
--- /dev/null
+++ b/packages/twenty-cli/project.json
@@ -0,0 +1,31 @@
+{
+ "name": "twenty-cli",
+ "$schema": "../../node_modules/nx/schemas/project-schema.json",
+ "sourceRoot": "packages/twenty-cli/src",
+ "projectType": "application",
+ "tags": ["scope:cli"],
+ "implicitDependencies": ["create-twenty-app"],
+ "targets": {
+ "build": {
+ "dependsOn": ["^build"],
+ "outputs": ["{projectRoot}/dist"]
+ },
+ "start": {
+ "executor": "nx:run-commands",
+ "dependsOn": ["build"],
+ "options": {
+ "cwd": "packages/twenty-cli",
+ "command": "node dist/cli.cjs"
+ }
+ },
+ "typecheck": {},
+ "lint": {},
+ "test": {
+ "executor": "@nx/vitest:test",
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
+ "options": {
+ "config": "{projectRoot}/vitest.config.ts"
+ }
+ }
+ }
+}
diff --git a/packages/twenty-cli/src/__tests__/run-cli.spec.ts b/packages/twenty-cli/src/__tests__/run-cli.spec.ts
new file mode 100644
index 00000000000..c6c528afcd4
--- /dev/null
+++ b/packages/twenty-cli/src/__tests__/run-cli.spec.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+
+const JSON_MODE_INVOCATIONS = [
+ ['version', '--json'],
+ ['commands', '--json'],
+ ['--json'],
+ ['--json', '--version'],
+ ['version', '--help', '--json'],
+ ['versoin', '--json'],
+ ['help', 'versoin', '--json'],
+ ['version', '--jsn', '--json'],
+ ['version', 'extra', '--json'],
+ ['app:publish', '--json'],
+ ['--json', '--format', 'ndjson', 'version'],
+ ['--format', 'xml', '--json', 'version'],
+];
+
+describe('runCli', () => {
+ it.each(JSON_MODE_INVOCATIONS.map((args) => [args]))(
+ 'prints exactly one JSON envelope for %j',
+ async (args) => {
+ const { stdout } = await runCliForTest(args);
+ const envelope = parseSingleJsonLine(stdout);
+
+ expect(envelope).toMatchObject({
+ schemaVersion: 1,
+ ok: expect.any(Boolean),
+ warnings: expect.any(Array),
+ });
+ },
+ );
+
+ it('prints version information', async () => {
+ const { stdout, exitCode } = await runCliForTest(['version', '--json']);
+
+ expect(exitCode).toBe(0);
+ expect(parseSingleJsonLine(stdout)).toMatchObject({
+ ok: true,
+ command: 'version',
+ data: { version: CLI_VERSION, node: process.versions.node },
+ });
+ });
+
+ it('renders --version like the version command', async () => {
+ const { stdout, exitCode } = await runCliForTest(['--version']);
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toMatch(new RegExp(`^twenty ${CLI_VERSION} `));
+ });
+
+ it('lists the available commands', async () => {
+ const { stdout } = await runCliForTest(['commands', '--json']);
+ const names = parseSingleJsonLine(stdout).data.commands.map(
+ (command: { name: string }) => command.name,
+ );
+
+ expect(names).toEqual(expect.arrayContaining(['commands', 'version']));
+ });
+
+ it('shows help without a command and exits successfully', async () => {
+ const { stdout, exitCode } = await runCliForTest(['--json']);
+ const envelope = parseSingleJsonLine(stdout);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.help).toContain('Usage: twenty');
+ });
+
+ it('rejects unknown commands with a suggestion and exit code 2', async () => {
+ const { stdout, exitCode } = await runCliForTest(['versoin', '--json']);
+ const envelope = parseSingleJsonLine(stdout);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.ok).toBe(false);
+ expect(envelope.error.code).toBe('USAGE');
+ expect(envelope.error.message).toContain('Did you mean version?');
+ });
+
+ it('rejects help for an unknown command', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'help',
+ 'versoin',
+ '--json',
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(parseSingleJsonLine(stdout).error).toMatchObject({
+ code: 'USAGE',
+ message: "Unknown command 'versoin'",
+ });
+ });
+
+ it('prints human errors on stderr only', async () => {
+ const { stdout, stderr, exitCode } = await runCliForTest(['versoin']);
+
+ expect(exitCode).toBe(2);
+ expect(stdout).toBe('');
+ expect(stderr).toContain("Unknown command 'versoin'");
+ });
+
+ it('uses the last --format value', async () => {
+ const jsonRun = await runCliForTest([
+ 'version',
+ '--format',
+ 'human',
+ '--format',
+ 'json',
+ ]);
+ const humanRun = await runCliForTest([
+ 'version',
+ '--format=json',
+ '--format=human',
+ ]);
+
+ expect(parseSingleJsonLine(jsonRun.stdout).ok).toBe(true);
+ expect(humanRun.stdout).toMatch(/^twenty /);
+ });
+
+ it('rejects --json combined with --format', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ '--json',
+ '--format',
+ 'ndjson',
+ 'version',
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(parseSingleJsonLine(stdout).error.code).toBe('USAGE');
+ });
+
+ it('refuses NDJSON for commands that do not stream', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'version',
+ '--format',
+ 'ndjson',
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(parseSingleJsonLine(stdout)).toMatchObject({
+ command: 'version',
+ type: 'error',
+ sequence: 1,
+ data: { code: 'USAGE' },
+ });
+ });
+
+ it.each([
+ { args: ['build'], unknownCommand: 'build', helpCommand: 'twenty' },
+ { args: ['dev:build'], unknownCommand: 'dev:build', helpCommand: 'twenty' },
+ {
+ args: ['app:publish'],
+ unknownCommand: 'app:publish',
+ helpCommand: 'twenty',
+ },
+ {
+ args: ['remote:add'],
+ unknownCommand: 'remote:add',
+ helpCommand: 'twenty',
+ },
+ {
+ args: ['remote', 'add'],
+ unknownCommand: 'add',
+ helpCommand: 'twenty remote',
+ },
+ ])(
+ 'rejects $args with normal usage guidance',
+ async ({ args, unknownCommand, helpCommand }) => {
+ const { stdout, exitCode } = await runCliForTest([...args, '--json']);
+ const { error } = parseSingleJsonLine(stdout);
+
+ expect(exitCode).toBe(2);
+ expect(error).toMatchObject({
+ code: 'USAGE',
+ message: expect.stringContaining(`Unknown command '${unknownCommand}'`),
+ hint: `See: ${helpCommand} --help`,
+ });
+ expect(error.details).toBeUndefined();
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/__tests__/utils/create-standard-input-stub.ts b/packages/twenty-cli/src/__tests__/utils/create-standard-input-stub.ts
new file mode 100644
index 00000000000..a552dc2573d
--- /dev/null
+++ b/packages/twenty-cli/src/__tests__/utils/create-standard-input-stub.ts
@@ -0,0 +1,38 @@
+import { Socket } from 'node:net';
+
+import { isDefined } from 'twenty-shared/utils';
+
+class StandardInputStub extends Socket {
+ readonly fd = 0;
+ isRaw = false;
+ isTTY: boolean;
+
+ constructor({
+ content,
+ isTerminal,
+ }: {
+ content?: string;
+ isTerminal: boolean;
+ }) {
+ super();
+ this.isTTY = isTerminal;
+
+ if (isDefined(content)) {
+ this.push(content);
+ }
+
+ this.push(null);
+ }
+
+ setRawMode() {
+ return this;
+ }
+}
+
+export const createStandardInputStub = ({
+ content,
+ isTerminal = false,
+}: {
+ content?: string;
+ isTerminal?: boolean;
+}) => new StandardInputStub({ content, isTerminal });
diff --git a/packages/twenty-cli/src/__tests__/utils/read-graphql-request.ts b/packages/twenty-cli/src/__tests__/utils/read-graphql-request.ts
new file mode 100644
index 00000000000..a60afe28669
--- /dev/null
+++ b/packages/twenty-cli/src/__tests__/utils/read-graphql-request.ts
@@ -0,0 +1,28 @@
+import { isString } from '@sniptt/guards';
+import { Kind, parse, valueFromASTUntyped } from 'graphql';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type RecordedRequest } from '@/__tests__/utils/start-test-server';
+
+export const readGraphqlRequest = (request: Pick<RecordedRequest, 'body'>) => {
+ const body: unknown = JSON.parse(request.body);
+ const query = isPlainObject(body) && isString(body.query) ? body.query : '';
+ const variables =
+ isPlainObject(body) && isPlainObject(body.variables) ? body.variables : {};
+ const operation = parse(query).definitions.find(
+ (definition) => definition.kind === Kind.OPERATION_DEFINITION,
+ );
+ const field = operation?.selectionSet.selections.find(
+ (selection) => selection.kind === Kind.FIELD,
+ );
+
+ return {
+ query,
+ arguments: Object.fromEntries(
+ (field?.arguments ?? []).map((argument) => [
+ argument.name.value,
+ valueFromASTUntyped(argument.value, variables),
+ ]),
+ ) as Record<string, unknown>,
+ };
+};
diff --git a/packages/twenty-cli/src/__tests__/utils/run-cli-for-test.ts b/packages/twenty-cli/src/__tests__/utils/run-cli-for-test.ts
new file mode 100644
index 00000000000..2ed211367b4
--- /dev/null
+++ b/packages/twenty-cli/src/__tests__/utils/run-cli-for-test.ts
@@ -0,0 +1,45 @@
+import { vi } from 'vitest';
+
+import { runCli } from '@/run-cli';
+
+export const runCliForTest = async (args: string[]) => {
+ let stdout = '';
+ let stderr = '';
+ const stdoutSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation((chunk) => {
+ stdout += String(chunk);
+
+ return true;
+ });
+ const stderrSpy = vi
+ .spyOn(process.stderr, 'write')
+ .mockImplementation((chunk) => {
+ stderr += String(chunk);
+
+ return true;
+ });
+ const previousExitCode = process.exitCode;
+
+ process.exitCode = undefined;
+
+ try {
+ await runCli(args);
+
+ return { stdout, stderr, exitCode: Number(process.exitCode ?? 0) };
+ } finally {
+ stdoutSpy.mockRestore();
+ stderrSpy.mockRestore();
+ process.exitCode = previousExitCode;
+ }
+};
+
+export const parseSingleJsonLine = (stdout: string) => {
+ const lines = stdout.trimEnd().split('\n');
+
+ if (lines.length !== 1) {
+ throw new Error(`Expected one JSON line, got ${lines.length}: ${stdout}`);
+ }
+
+ return JSON.parse(lines[0]);
+};
diff --git a/packages/twenty-cli/src/__tests__/utils/start-test-server.ts b/packages/twenty-cli/src/__tests__/utils/start-test-server.ts
new file mode 100644
index 00000000000..6be16fa154e
--- /dev/null
+++ b/packages/twenty-cli/src/__tests__/utils/start-test-server.ts
@@ -0,0 +1,68 @@
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from 'node:http';
+
+import { getListeningPort } from '@/utils/get-listening-port';
+
+export type RecordedRequest = {
+ method: string;
+ path: string;
+ headers: IncomingMessage['headers'];
+ body: string;
+};
+
+type TestServerHandler = (
+ request: RecordedRequest,
+ response: ServerResponse,
+) => void;
+
+export const startTestServer = async (handler: TestServerHandler) => {
+ const requests: RecordedRequest[] = [];
+ const server = createServer((incomingMessage, response) => {
+ let body = '';
+
+ incomingMessage.on('data', (chunk) => {
+ body += String(chunk);
+ });
+ incomingMessage.on('end', () => {
+ const request = {
+ method: incomingMessage.method ?? '',
+ path: incomingMessage.url ?? '',
+ headers: incomingMessage.headers,
+ body,
+ };
+
+ requests.push(request);
+ handler(request, response);
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+
+ const port = getListeningPort(server);
+
+ return {
+ url: `http://127.0.0.1:${port}`,
+ requests,
+ close: () =>
+ new Promise<void>((resolve) => {
+ server.closeAllConnections();
+ server.close(() => resolve());
+ }),
+ };
+};
+
+export const sendJson = (
+ response: ServerResponse,
+ status: number,
+ body: unknown,
+ headers: Record<string, string> = {},
+) => {
+ response.writeHead(status, {
+ 'content-type': 'application/json',
+ ...headers,
+ });
+ response.end(JSON.stringify(body));
+};
diff --git a/packages/twenty-cli/src/app/README.md b/packages/twenty-cli/src/app/README.md
new file mode 100644
index 00000000000..c392b5f07b2
--- /dev/null
+++ b/packages/twenty-cli/src/app/README.md
@@ -0,0 +1,43 @@
+# Application tooling
+
+See [Contributing](../../CONTRIBUTING.md) for package setup and tests, and the
+[command reference](../../docs/commands.md) for user-visible behavior.
+
+The `twenty` CLI owns filesystem operations, source loading, build, typecheck,
+watching, pull and deployment. Apps use `twenty-sdk` to define application
+metadata and runtime behavior. They do not import or depend on the CLI, which
+is normally installed globally.
+
+| Module | Responsibility |
+| ---------------------------------------- | -------------------------------------------------------------------- |
+| `project` | Locate the app and resolve its installed SDK and Node requirements |
+| `deployment` | Preview metadata changes, approve them, upload snapshots and sync |
+| [source](source/README.md) | Discover and evaluate trusted app definitions in a disposable worker |
+| [manifest](manifest/README.md) | Construct and validate metadata, compile translations |
+| [bundles](bundles/README.md) | Build artifacts and hold immutable snapshots for consumers |
+| [typecheck](typecheck/README.md) | Check source and configuration with the app's TypeScript compiler |
+| [client](client/README.md) | Invoke the app's installed client SDK generator |
+| [pull](pull/README.md) | Reconcile remote metadata with source and a target-bound baseline |
+| [add](add/README.md) | Create starter definitions without replacing existing files |
+| [dev](dev/README.md) | Watch build inputs and schedule builds and remote apply |
+| [exec](exec/README.md) | Execute an installed logic function |
+| [function-logs](function-logs/README.md) | Stream application function logs |
+
+The worker isolates process exits, captures bounded output, filters inherited
+CLI credentials and supports cancellation. It runs trusted developer code and
+is not a security sandbox. Configurations containing functions stay inside the
+worker; only serializable requests, results and diagnostics cross IPC.
+
+Snapshots retain files until their consumers finish. Uploads verify containment,
+size and checksums. Pull and scaffolding stage writes before exposing them to
+file watchers. Keep these guarantees when simplifying implementation details.
+
+## Package boundaries
+
+The CLI imports the app's public SDK authoring exports and invokes its installed
+client SDK generator. The [typecheck documentation](typecheck/README.md) describes
+compiler resolution and project requirements.
+
+Parity tests compare generated source, manifests and bundles with the repository
+SDK. Command failure and cancellation tests inject tooling fixtures into a bundle
+of the production worker; real-app tests exercise its compiler and bundler.
diff --git a/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts
new file mode 100644
index 00000000000..6fcbae9fad6
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts
@@ -0,0 +1,95 @@
+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { delimiter, dirname, join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { runTwenty } from '../../../app-template-overlay/src/__tests__/run-twenty';
+
+describe('runTwenty in the app template', () => {
+ let root: string;
+
+ const writeExecutable = async (path: string, source: string) => {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, `#!/usr/bin/env node\n${source}\n`);
+ await chmod(path, 0o755);
+ };
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-run-twenty-'));
+ vi.stubEnv('TWENTY_CLI', undefined);
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('runs the global CLI, skipping the binaries a package manager puts first on PATH', async () => {
+ const packageManagerBin = join(root, 'package-manager-bin');
+ const projectBin = join(root, 'app', 'node_modules', '.bin');
+ const globalBin = join(root, 'global-bin');
+
+ await writeExecutable(
+ join(packageManagerBin, 'twenty'),
+ "console.log('package manager binary');",
+ );
+ await writeExecutable(
+ join(projectBin, 'twenty'),
+ "console.log('project binary');",
+ );
+ await writeExecutable(
+ join(globalBin, 'twenty'),
+ 'console.log(JSON.stringify({ ok: true, data: { args: process.argv.slice(2) } }));',
+ );
+ vi.stubEnv(
+ 'PATH',
+ [packageManagerBin, projectBin, globalBin, process.env.PATH].join(
+ delimiter,
+ ),
+ );
+ vi.stubEnv('BERRY_BIN_FOLDER', packageManagerBin);
+
+ await expect(runTwenty(['app', 'apply', '--create'])).resolves.toEqual({
+ ok: true,
+ data: { args: ['app', 'apply', '--create', '--json'] },
+ });
+ });
+
+ it('returns a CLI failure as a result instead of throwing', async () => {
+ const cliPath = join(root, 'twenty');
+
+ await writeExecutable(
+ cliPath,
+ "console.log(JSON.stringify({ ok: false, error: { code: 'APP_NOT_INSTALLED', message: 'Not installed.' } })); process.exitCode = 4;",
+ );
+ vi.stubEnv('TWENTY_CLI', cliPath);
+
+ await expect(runTwenty(['app', 'uninstall', '--yes'])).resolves.toEqual({
+ ok: false,
+ error: { code: 'APP_NOT_INSTALLED', message: 'Not installed.' },
+ });
+ });
+
+ it('explains how to install the CLI when the executable is missing', async () => {
+ vi.stubEnv('TWENTY_CLI', join(root, 'missing', 'twenty'));
+
+ await expect(runTwenty(['app', 'build'])).rejects.toThrow(
+ 'was not found. Install the Twenty CLI globally, or set TWENTY_CLI to its path.',
+ );
+ });
+
+ it('rejects output that is not a CLI JSON result', async () => {
+ const cliPath = join(root, 'twenty');
+
+ await writeExecutable(
+ cliPath,
+ "console.log('Did you mean apply?'); process.exitCode = 1;",
+ );
+ vi.stubEnv('TWENTY_CLI', cliPath);
+
+ await expect(runTwenty(['app', 'build'])).rejects.toThrow(
+ 'app build exited with code 1 without a JSON result',
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/app/__tests__/create-output-collector.spec.ts b/packages/twenty-cli/src/app/__tests__/create-output-collector.spec.ts
new file mode 100644
index 00000000000..52db8724e3f
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/create-output-collector.spec.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { createOutputCollector } from '@/app/create-output-collector';
+
+describe('createOutputCollector', () => {
+ it('keeps at most the limit and marks the rest as truncated', () => {
+ const collector = createOutputCollector(8);
+
+ for (let index = 0; index < 100; index += 1) {
+ collector.add(Buffer.from('abcdef'));
+ }
+
+ expect(collector.read()).toEqual({ text: 'abcdefab', isTruncated: true });
+ });
+
+ it('copies bytes instead of keeping references to incoming chunks', () => {
+ const collector = createOutputCollector(1024);
+ const chunk = Buffer.from('original output');
+
+ collector.add(chunk);
+ chunk.fill('x');
+
+ expect(collector.read()).toEqual({
+ text: 'original output',
+ isTruncated: false,
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/__tests__/fs-utils.spec.ts b/packages/twenty-cli/src/app/__tests__/fs-utils.spec.ts
new file mode 100644
index 00000000000..ddd1da25ede
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/fs-utils.spec.ts
@@ -0,0 +1,59 @@
+import * as fileSystem from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { emptyDir, pathExists } from '@/app/fs-utils';
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof fileSystem>();
+
+ return { ...actual, access: vi.fn(actual.access) };
+});
+
+const directories: string[] = [];
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((directory) =>
+ fileSystem.rm(directory, { recursive: true, force: true }),
+ ),
+ );
+});
+
+describe('build filesystem operations', () => {
+ it('refuses to empty a linked output directory without deleting its contents', async () => {
+ const root = await fileSystem.mkdtemp(join(tmpdir(), 'cli-output-'));
+ directories.push(root);
+ const external = join(root, 'external');
+ const output = join(root, 'output');
+ await fileSystem.mkdir(external);
+ await fileSystem.writeFile(join(external, 'keep.txt'), 'keep');
+ await fileSystem.symlink(external, output);
+
+ await expect(emptyDir(output)).rejects.toThrow('symbolic link');
+ expect(await fileSystem.readFile(join(external, 'keep.txt'), 'utf8')).toBe(
+ 'keep',
+ );
+ });
+
+ it.each(['EACCES', 'EIO'])(
+ 'does not treat %s as a missing asset',
+ async (code) => {
+ const error = Object.assign(new Error('asset unavailable'), { code });
+ vi.mocked(fileSystem.access).mockRejectedValueOnce(error);
+
+ await expect(pathExists('/asset')).rejects.toBe(error);
+ },
+ );
+
+ it('returns false for a missing asset', async () => {
+ vi.mocked(fileSystem.access).mockRejectedValueOnce(
+ Object.assign(new Error('missing'), { code: 'ENOENT' }),
+ );
+
+ expect(await pathExists('/asset')).toBe(false);
+ });
+});
diff --git a/packages/twenty-cli/src/app/__tests__/get-app-init-next-steps.spec.ts b/packages/twenty-cli/src/app/__tests__/get-app-init-next-steps.spec.ts
new file mode 100644
index 00000000000..09d7f389f01
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/get-app-init-next-steps.spec.ts
@@ -0,0 +1,48 @@
+import { execFile } from 'node:child_process';
+import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { afterEach, expect, it, vi } from 'vitest';
+import { getAppInitNextSteps } from '@/app/get-app-init-next-steps';
+
+it.skipIf(process.platform === 'win32')(
+ 'prints a runnable cd for a leading-dash folder',
+ async () => {
+ const root = await mkdtemp(join(tmpdir(), 'next-step-'));
+ try {
+ await mkdir(join(root, '-app'));
+ const steps = getAppInitNextSteps({
+ displayPath: '-app',
+ isTargetConfigured: true,
+ remoteName: undefined,
+ });
+ const { stdout } = await promisify(execFile)(
+ 'sh',
+ ['-c', steps[0].command + '\npwd -P'],
+ { cwd: root },
+ );
+ expect(stdout.trim()).toBe(await realpath(join(root, '-app')));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+);
+
+afterEach(() => vi.unstubAllGlobals());
+
+it('labels Windows steps as PowerShell and escapes apostrophes literally', () => {
+ vi.stubGlobal('process', { ...process, platform: 'win32' });
+ const steps = getAppInitNextSteps({
+ displayPath: "C:\\apps\\O'Brien app",
+ isTargetConfigured: true,
+ remoteName: "O'Brien workspace",
+ });
+ expect(steps[0].command).toBe("cd 'C:\\apps\\O''Brien app'");
+ expect(steps.at(-1)?.command).toBe(
+ "twenty app apply --create --remote 'O''Brien workspace'",
+ );
+ expect(steps.every((step) => step.description.endsWith('(PowerShell)'))).toBe(
+ true,
+ );
+});
diff --git a/packages/twenty-cli/src/app/__tests__/get-client-generation-skip-reason.spec.ts b/packages/twenty-cli/src/app/__tests__/get-client-generation-skip-reason.spec.ts
new file mode 100644
index 00000000000..0e3056c1d2d
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/get-client-generation-skip-reason.spec.ts
@@ -0,0 +1,46 @@
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getClientGenerationSkipReason } from '@/app/get-client-generation-skip-reason';
+describe('getClientGenerationSkipReason', () => {
+ let appPath: string;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-client-skip-'));
+ });
+
+ afterEach(() => rm(appPath, { recursive: true, force: true }));
+
+ it('skips an app without its own client package', async () => {
+ expect(await getClientGenerationSkipReason({ appPath })).toBe(
+ "twenty-client-sdk is not installed in the app's own node_modules.",
+ );
+ });
+
+ it('generates into an installed client package', async () => {
+ await mkdir(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ });
+
+ expect(await getClientGenerationSkipReason({ appPath })).toBeUndefined();
+ });
+
+ it('leaves a dangling client package link to the client generator', async () => {
+ await mkdir(join(appPath, 'node_modules'));
+ await symlink(
+ join(appPath, 'missing'),
+ join(appPath, 'node_modules', 'twenty-client-sdk'),
+ );
+
+ expect(await getClientGenerationSkipReason({ appPath })).toBeUndefined();
+ });
+
+ it('leaves an unreadable client package path to the client generator', async () => {
+ await writeFile(join(appPath, 'node_modules'), 'not a directory');
+
+ expect(await getClientGenerationSkipReason({ appPath })).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-cli/src/app/__tests__/read-app-identity.spec.ts b/packages/twenty-cli/src/app/__tests__/read-app-identity.spec.ts
new file mode 100644
index 00000000000..dc1516d14aa
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/read-app-identity.spec.ts
@@ -0,0 +1,154 @@
+import { access, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout } from 'node:timers/promises';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { readAppIdentity } from '@/app/read-app-identity';
+import {
+ createSourceTestApp,
+ sourceApplication,
+ SOURCE_TEST_APPLICATION_ID,
+} from '@/app/source/__tests__/utils/create-source-test-app';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+
+describe('isolated CLI source worker', () => {
+ let appPath: string;
+ let workerPath: string;
+ let controller: AbortController;
+
+ beforeAll(async () => {
+ workerPath = await mkdtemp(join(tmpdir(), 'twenty-source-worker-'));
+ launch.modulePath = join(workerPath, 'app-worker.cjs');
+ await buildTestAppWorker(workerPath);
+ });
+ afterAll(async () => rm(workerPath, { recursive: true, force: true }));
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-identity-'));
+ controller = new AbortController();
+ await createSourceTestApp(appPath);
+ });
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('loads with an authoring-only SDK and captures source output separately', async () => {
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication(
+ 'console.log("hello from source"); console.error("source warning");',
+ ),
+ );
+ const result = await readAppIdentity({
+ appPath,
+ signal: controller.signal,
+ });
+
+ expect(result.application?.universalIdentifier).toBe(
+ SOURCE_TEST_APPLICATION_ID,
+ );
+ expect(result.diagnostics).toEqual([
+ expect.objectContaining({
+ code: 'PROJECT_OUTPUT',
+ message: expect.stringContaining('hello from source'),
+ }),
+ expect.objectContaining({
+ code: 'PROJECT_OUTPUT',
+ message: expect.stringContaining('source warning'),
+ }),
+ ]);
+ });
+
+ it('does not pass selected workspace credentials to evaluated source', async () => {
+ vi.stubEnv('TWENTY_API_KEY', 'must-not-reach-app');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'must-not-reach-app');
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication(`
+ if (process.env.TWENTY_API_KEY || process.env.TWENTY_APP_ACCESS_TOKEN) throw new Error('credential leaked');
+ `),
+ );
+ expect(
+ (await readAppIdentity({ appPath, signal: controller.signal }))
+ .application,
+ ).not.toBeNull();
+ });
+
+ it('preserves a typed failure for incompatible SDK definition results', async () => {
+ await writeFile(
+ join(appPath, 'node_modules/twenty-sdk/define.cjs'),
+ 'exports.defineApplication = (config) => config;',
+ );
+ await writeFile(join(appPath, 'app.ts'), sourceApplication());
+ await expect(
+ readAppIdentity({ appPath, signal: controller.signal }),
+ ).rejects.toMatchObject({ code: 'SDK_SOURCE_UNSUPPORTED' });
+ });
+
+ it('contains process.exit in app source', async () => {
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication('process.exit(17);'),
+ );
+ await expect(
+ readAppIdentity({ appPath, signal: controller.signal }),
+ ).rejects.toMatchObject({
+ code: 'WORKER_FAILED',
+ details: { exitCode: 17 },
+ });
+ });
+
+ it('kills a busy source worker when cancelled', async () => {
+ const startedPath = join(appPath, 'started');
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication(`
+ import { writeFileSync } from 'node:fs';
+ writeFileSync(${JSON.stringify(startedPath)}, 'started');
+ while (true) {}
+ `),
+ );
+ const result = readAppIdentity({ appPath, signal: controller.signal }).then(
+ (value) => ({ value }),
+ (error: unknown) => ({ error }),
+ );
+
+ try {
+ const deadline = Date.now() + 5000;
+ while (
+ !(await access(startedPath).then(
+ () => true,
+ () => false,
+ ))
+ ) {
+ if (Date.now() > deadline) {
+ throw new Error('The source worker did not start.');
+ }
+ await setTimeout(20);
+ }
+ } finally {
+ controller.abort();
+ expect(await result).toMatchObject({
+ error: { code: 'CANCELLED', exitCode: 130 },
+ });
+ }
+ }, 10_000);
+});
diff --git a/packages/twenty-cli/src/app/__tests__/utils/build-test-app-worker.ts b/packages/twenty-cli/src/app/__tests__/utils/build-test-app-worker.ts
new file mode 100644
index 00000000000..c5944197aa2
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/build-test-app-worker.ts
@@ -0,0 +1,91 @@
+import { mkdir, symlink } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { isDefined } from 'twenty-shared/utils';
+import { build, loadConfigFromFile } from 'vite';
+import { vi } from 'vitest';
+
+export const buildTestAppWorker = async (
+ workerPath: string,
+ {
+ useToolingFixture = false,
+ aliases = {},
+ }: { useToolingFixture?: boolean; aliases?: Record<string, string> } = {},
+) => {
+ const cliRoot = fileURLToPath(new URL('../../../../', import.meta.url));
+
+ const loaded = await loadConfigFromFile(
+ { command: 'build', mode: 'production' },
+ join(cliRoot, 'vite.config.ts'),
+ );
+
+ if (!isDefined(loaded)) {
+ throw new Error('Could not load the CLI bundle configuration.');
+ }
+
+ vi.stubEnv('NODE_ENV', 'production');
+
+ try {
+ await build({
+ ...loaded.config,
+ configFile: false,
+ plugins: [],
+ resolve: {
+ ...loaded.config.resolve,
+ alias: {
+ ...aliases,
+ ...(useToolingFixture
+ ? Object.fromEntries(
+ [
+ '@/app/worker/build-source-snapshot',
+ '@/app/typecheck/typecheck-application',
+ '@/app/client/generate-application-client',
+ ].map((specifier) => [
+ specifier,
+ join(
+ cliRoot,
+ 'src/app/__tests__/utils/worker-tooling-fixture.ts',
+ ),
+ ]),
+ )
+ : {}),
+ ...loaded.config.resolve?.alias,
+ },
+ },
+ build: {
+ ...loaded.config.build,
+ rollupOptions: {
+ ...loaded.config.build?.rollupOptions,
+ external: (id, importer, isResolved) => {
+ const external = loaded.config.build?.rollupOptions?.external;
+
+ return (
+ Object.values(aliases).includes(id) ||
+ (typeof external === 'function' &&
+ external(id, importer, isResolved))
+ );
+ },
+ },
+ outDir: workerPath,
+ lib: {
+ entry: {
+ 'app-worker': join(cliRoot, 'src/app/worker/app-worker.ts'),
+ },
+ formats: ['cjs'],
+ },
+ },
+ });
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ await mkdir(join(workerPath, 'node_modules'));
+ const resolve = createRequire(import.meta.url).resolve;
+
+ for (const name of ['esbuild', 'typescript', 'tinyglobby']) {
+ await symlink(
+ dirname(resolve(`${name}/package.json`)),
+ join(workerPath, 'node_modules', name),
+ );
+ }
+};
diff --git a/packages/twenty-cli/src/app/__tests__/utils/fixture-paths.ts b/packages/twenty-cli/src/app/__tests__/utils/fixture-paths.ts
new file mode 100644
index 00000000000..c9688cdf817
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/fixture-paths.ts
@@ -0,0 +1,5 @@
+import { fileURLToPath } from 'node:url';
+
+export const MINIMAL_APP_PATH = fileURLToPath(
+ new URL('../../../../../twenty-apps/fixtures/minimal-app', import.meta.url),
+);
diff --git a/packages/twenty-cli/src/app/__tests__/utils/install-test-client-sdk.ts b/packages/twenty-cli/src/app/__tests__/utils/install-test-client-sdk.ts
new file mode 100644
index 00000000000..4815d4d4a3b
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/install-test-client-sdk.ts
@@ -0,0 +1,29 @@
+import { cp, mkdir, readFile, symlink } from 'node:fs/promises';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const sourceDirectory = fileURLToPath(
+ new URL('../../../../../twenty-client-sdk/', import.meta.url),
+);
+const repositoryModules = fileURLToPath(
+ new URL('../../../../../../node_modules/', import.meta.url),
+);
+
+export const installTestClientSdk = async (packageRoot: string) => {
+ await mkdir(packageRoot, { recursive: true });
+ await cp(
+ join(sourceDirectory, 'package.json'),
+ join(packageRoot, 'package.json'),
+ );
+ await cp(join(sourceDirectory, 'dist'), join(packageRoot, 'dist'), {
+ recursive: true,
+ });
+ const packageJson = JSON.parse(
+ await readFile(join(sourceDirectory, 'package.json'), 'utf8'),
+ );
+ for (const name of Object.keys(packageJson.dependencies)) {
+ const target = join(packageRoot, 'node_modules', name);
+ await mkdir(join(target, '..'), { recursive: true });
+ await symlink(join(repositoryModules, name), target);
+ }
+};
diff --git a/packages/twenty-cli/src/app/__tests__/utils/sorted-glob-plugin.ts b/packages/twenty-cli/src/app/__tests__/utils/sorted-glob-plugin.ts
new file mode 100644
index 00000000000..f1b3f508cef
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/sorted-glob-plugin.ts
@@ -0,0 +1,19 @@
+import { type Plugin } from 'esbuild';
+
+const SORTED_GLOB_NAMESPACE = 'sorted-tinyglobby';
+
+export const SORTED_GLOB_PLUGIN: Plugin = {
+ name: SORTED_GLOB_NAMESPACE,
+ setup(build) {
+ build.onResolve({ filter: /^tinyglobby$/ }, (args) =>
+ args.namespace === SORTED_GLOB_NAMESPACE
+ ? { path: 'tinyglobby', external: true }
+ : { path: 'tinyglobby', namespace: SORTED_GLOB_NAMESPACE },
+ );
+ build.onLoad({ filter: /.*/, namespace: SORTED_GLOB_NAMESPACE }, () => ({
+ contents: `const tinyglobby = require('tinyglobby');
+module.exports = { ...tinyglobby, glob: async (...args) => (await tinyglobby.glob(...args)).sort() };`,
+ loader: 'js',
+ }));
+ },
+};
diff --git a/packages/twenty-cli/src/app/__tests__/utils/worker-tooling-fixture.ts b/packages/twenty-cli/src/app/__tests__/utils/worker-tooling-fixture.ts
new file mode 100644
index 00000000000..084af79352b
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/worker-tooling-fixture.ts
@@ -0,0 +1,46 @@
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+
+type TestTooling = {
+ buildSourceSnapshot: (options: {
+ appPath: string;
+ signal: AbortSignal;
+ }) => Promise<unknown>;
+ releaseSourceSnapshot: (options: { buildId: string }) => Promise<unknown>;
+ typecheckApplication: (options: {
+ appPath: string;
+ signal: AbortSignal;
+ }) => Promise<unknown>;
+ generateApplicationClient: (options: {
+ appPath: string;
+ schema: string;
+ signal: AbortSignal;
+ }) => Promise<unknown>;
+};
+
+const loadTooling = (appPath: string): TestTooling =>
+ createRequire(join(appPath, 'package.json'))(
+ join(appPath, 'test-tooling.cjs'),
+ );
+
+let snapshotTooling: TestTooling;
+
+export const buildSourceSnapshot = async (
+ options: Parameters<TestTooling['buildSourceSnapshot']>[0],
+) => {
+ snapshotTooling = loadTooling(options.appPath);
+
+ return snapshotTooling.buildSourceSnapshot(options);
+};
+
+export const releaseSourceSnapshot = (
+ options: Parameters<TestTooling['releaseSourceSnapshot']>[0],
+) => snapshotTooling.releaseSourceSnapshot(options);
+
+export const typecheckApplication = (
+ options: Parameters<TestTooling['typecheckApplication']>[0],
+) => loadTooling(options.appPath).typecheckApplication(options);
+
+export const generateApplicationClient = (
+ options: Parameters<TestTooling['generateApplicationClient']>[0],
+) => loadTooling(options.appPath).generateApplicationClient(options);
diff --git a/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts b/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts
new file mode 100644
index 00000000000..48731734745
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/utils/write-test-source-sdk.ts
@@ -0,0 +1,32 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+export const writeTestSourceSdk = async ({
+ appPath,
+ version = '9.9.9',
+ requiredNode = '^24.5.0',
+ hasSourceExports = true,
+}: {
+ appPath: string;
+ version?: string;
+ requiredNode?: string;
+ hasSourceExports?: boolean;
+}) => {
+ const sdkPath = join(appPath, 'node_modules', 'twenty-sdk');
+
+ await mkdir(sdkPath, { recursive: true });
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version,
+ engines: { node: requiredNode },
+ exports: hasSourceExports
+ ? { './define': './index.cjs', './front-component': './index.cjs' }
+ : {},
+ }),
+ );
+ await writeFile(join(sdkPath, 'index.cjs'), 'module.exports = {};');
+
+ return sdkPath;
+};
diff --git a/packages/twenty-cli/src/app/add/README.md b/packages/twenty-cli/src/app/add/README.md
new file mode 100644
index 00000000000..aca159241cd
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/README.md
@@ -0,0 +1,50 @@
+# App definition scaffolding
+
+The templates create object, field, logic-function and front-component
+definitions. Filenames and logic-function/front-component names use kebab-case.
+Object and field metadata names keep the entered spelling; display labels use
+the same helper as app init.
+
+## Contract
+
+- `twenty app add [entity]` accepts `object`, `field`, `logic-function` and
+ `front-component`. A human terminal can supply omitted values interactively.
+ JSON, CI, redirected stdin and `--no-input` never prompt; missing required or
+ inapplicable options exit 2. Labels default to the name; fields default to
+ `TEXT`.
+- `--path` selects an app, like the other CLI app commands. Files go under the
+ selected app's `src/objects`, `src/fields`, `src/logic-functions` or
+ `src/front-components`. Custom output directories are not supported.
+- Parent and relation endpoint identifiers must be valid universal UUIDs. No
+ workspace lookup verifies ownership or existence. Relations require reviewing
+ both endpoints; this generator creates only the requested standalone field.
+- Node's `randomUUID` creates version 4 identifiers. The CLI TypeScript printer
+ escapes authored strings, including quotes, backslashes and line breaks.
+- App discovery, SDK compatibility and application identity reuse the CLI's
+ worker boundary. Identity loading evaluates trusted app code in a disposable
+ worker; it is not a security sandbox. The command makes no workspace requests
+ and does not require authentication.
+- Destination paths reuse pull's containment and symlink checks. A fully staged
+ file is linked exclusively into place, so an existing or concurrently created
+ destination is never replaced. Cancellation before that link removes the
+ staged file; a successful link wins over late cancellation. Cleanup failure
+ after success warns and reports the remaining temporary directory. Empty
+ parent directories can remain after failure or cancellation. Exclusive atomic
+ creation requires a filesystem supporting hard links; unsupported filesystems
+ fail instead of falling back to a potentially partial destination write.
+- Path validation rejects existing symbolic links. It cannot prevent another
+ local process from replacing a parent directory between validation and writing.
+- JSON reports app-relative `createdPaths`. There is no overwrite mode and no
+ editing or registration of existing definitions. Object view, layout and menu
+ companions and other entity generators are not supported.
+
+These are starter definitions, not a deployment validator. Review type-specific
+settings, relation endpoints, handlers and components, then build and plan the
+app. Successful generation does not imply the server will accept the metadata.
+
+## Verification
+
+`add-template-parity.spec.ts` compares generated source with the repository SDK,
+normalizing random UUIDs while preserving their reuse. It covers every field type
+and both runtime templates. Additional tests cover escaped strings, invalid
+identifiers, destination conflicts and cancellation.
diff --git a/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts b/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts
new file mode 100644
index 00000000000..650dd49ef77
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts
@@ -0,0 +1,174 @@
+import { mkdtemp, rm, symlink } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build } from 'esbuild';
+import {
+ FieldMetadataType,
+ RelationOnDeleteAction,
+ RelationType,
+} from 'twenty-shared/types';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import { getFieldBaseFile } from '@/app/add/entity-field-template';
+import { getFrontComponentBaseFile } from '@/app/add/entity-front-component-template';
+import { getLogicFunctionBaseFile } from '@/app/add/entity-logic-function-template';
+import { getObjectBaseFile } from '@/app/add/entity-object-template';
+import { kebabCase } from '@/app/pull/kebab-case';
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const UUID_PATTERN =
+ /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/g;
+const normalizeIdentifiers = (content: string) => {
+ const identifiers = new Map<string, number>();
+
+ return content.replace(UUID_PATTERN, (identifier) => {
+ if (!identifiers.has(identifier))
+ identifiers.set(identifier, identifiers.size);
+
+ return `UUID_${identifiers.get(identifier)}`;
+ });
+};
+
+type SdkReference = {
+ getFieldBaseFile: typeof getFieldBaseFile;
+ getFrontComponentBaseFile: typeof getFrontComponentBaseFile;
+ getLogicFunctionBaseFile: typeof getLogicFunctionBaseFile;
+ getObjectBaseFile: typeof getObjectBaseFile;
+ kebabCase: typeof kebabCase;
+};
+
+describe('app add template parity with the repository SDK', () => {
+ let root: string;
+ let sdk: SdkReference;
+
+ beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-add-parity-'));
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules'),
+ join(root, 'node_modules'),
+ );
+ const sdkSource = join(REPOSITORY_ROOT, 'packages/twenty-sdk/src');
+ const oraclePath = join(root, 'sdk.cjs');
+
+ await build({
+ stdin: {
+ contents: [
+ ...['object', 'field', 'logic-function', 'front-component'].map(
+ (entity) =>
+ `export * from './cli/utilities/entity/entity-${entity}-template';`,
+ ),
+ "export * from './cli/utilities/string/kebab-case';",
+ ].join('\n'),
+ resolveDir: sdkSource,
+ },
+ outfile: oraclePath,
+ alias: { '@': sdkSource },
+ bundle: true,
+ packages: 'external',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node24',
+ });
+ sdk = createRequire(import.meta.url)(oraclePath) as SdkReference;
+ });
+
+ afterAll(async () => {
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('preserves the object template and its shared name-field identifier', () => {
+ const input = {
+ name: 'invoice',
+ data: {
+ nameSingular: 'invoice',
+ namePlural: 'invoices',
+ labelSingular: 'Invoice',
+ labelPlural: 'Invoices',
+ },
+ };
+
+ expect(normalizeIdentifiers(getObjectBaseFile(input))).toBe(
+ normalizeIdentifiers(sdk.getObjectBaseFile(input)),
+ );
+ });
+
+ it.each(Object.values(FieldMetadataType))(
+ 'preserves the %s field template',
+ (type) => {
+ const input = {
+ name: 'value',
+ data: {
+ name: 'value',
+ label: 'Value',
+ type,
+ objectUniversalIdentifier: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ description: 'A value',
+ relationTargetObjectMetadataUniversalIdentifier:
+ 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
+ relationTargetFieldMetadataUniversalIdentifier:
+ 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
+ relationType: RelationType.ONE_TO_MANY,
+ onDelete: RelationOnDeleteAction.CASCADE,
+ },
+ };
+
+ expect(normalizeIdentifiers(getFieldBaseFile(input))).toBe(
+ normalizeIdentifiers(sdk.getFieldBaseFile(input)),
+ );
+ },
+ );
+
+ it.each(['SendInvoice', 'hello world', 'HTTPClient2'])(
+ 'preserves runtime templates and SDK filename normalization for %s',
+ (name) => {
+ expect(kebabCase(name)).toBe(sdk.kebabCase(name));
+ expect(normalizeIdentifiers(getLogicFunctionBaseFile({ name }))).toBe(
+ normalizeIdentifiers(sdk.getLogicFunctionBaseFile({ name })),
+ );
+ expect(normalizeIdentifiers(getFrontComponentBaseFile({ name }))).toBe(
+ normalizeIdentifiers(sdk.getFrontComponentBaseFile({ name })),
+ );
+ },
+ );
+
+ it('escapes authored strings instead of emitting invalid TypeScript', async () => {
+ const label = "Customer's \\ invoice\nnext line";
+ const object = getObjectBaseFile({
+ name: 'invoice',
+ data: {
+ nameSingular: 'invoice',
+ namePlural: 'invoices',
+ labelSingular: label,
+ labelPlural: label,
+ },
+ });
+ const field = getFieldBaseFile({
+ name: 'amount',
+ data: {
+ name: 'amount',
+ label,
+ type: FieldMetadataType.NUMBER,
+ objectUniversalIdentifier: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ description: label,
+ },
+ });
+
+ for (const source of [object, field]) {
+ expect(source).toContain("Customer\\'s \\\\ invoice\\nnext line");
+ const result = await build({
+ stdin: { contents: source, loader: 'ts' },
+ write: false,
+ bundle: true,
+ external: ['twenty-sdk/define'],
+ platform: 'node',
+ });
+
+ expect(result.errors).toEqual([]);
+ }
+ });
+});
diff --git a/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.ts b/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.ts
new file mode 100644
index 00000000000..04ecc22a6e2
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.ts
@@ -0,0 +1,139 @@
+import {
+ link,
+ lstat,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import type * as fileSystemPromises from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { writeAppAddFile } from '@/app/add/write-app-add-file';
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof fileSystemPromises>();
+
+ return {
+ ...actual,
+ link: vi.fn(actual.link),
+ lstat: vi.fn(actual.lstat),
+ rm: vi.fn(actual.rm),
+ writeFile: vi.fn(actual.writeFile),
+ };
+});
+
+describe('app add exclusive file creation', () => {
+ let root: string;
+ const file = {
+ path: 'src/objects/invoice.ts',
+ content: 'complete definition',
+ };
+ const actual = vi.importActual<typeof fileSystemPromises>('node:fs/promises');
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-add-write-'));
+ });
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it.each(['EACCES', 'EIO'])(
+ 'preserves %s from path validation',
+ async (code) => {
+ const error = Object.assign(new Error('filesystem failure'), { code });
+ vi.mocked(lstat).mockRejectedValueOnce(error);
+ await expect(
+ writeAppAddFile({
+ appPath: root,
+ file,
+ signal: new AbortController().signal,
+ }),
+ ).rejects.toBe(error);
+ expect(link).not.toHaveBeenCalled();
+ },
+ );
+
+ it('preserves a destination created while the new definition was staged', async () => {
+ vi.mocked(link).mockImplementationOnce(async (source, destination) => {
+ await (await actual).writeFile(destination, 'concurrent user definition');
+
+ return (await actual).link(source, destination);
+ });
+
+ await expect(
+ writeAppAddFile({
+ appPath: root,
+ file,
+ signal: new AbortController().signal,
+ }),
+ ).rejects.toMatchObject({ code: 'APP_PATH_UNAVAILABLE', exitCode: 6 });
+ expect(await readFile(join(root, file.path), 'utf8')).toBe(
+ 'concurrent user definition',
+ );
+ expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);
+ });
+
+ it('removes a partial staged write without exposing an incomplete definition', async () => {
+ vi.mocked(writeFile).mockImplementationOnce(async (path) => {
+ await (await actual).writeFile(path, 'partial');
+ throw new Error('disk full');
+ });
+
+ await expect(
+ writeAppAddFile({
+ appPath: root,
+ file,
+ signal: new AbortController().signal,
+ }),
+ ).rejects.toThrow('disk full');
+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);
+ });
+
+ it('cancels after staging without creating the destination', async () => {
+ const cancellation = new AbortController();
+
+ vi.mocked(writeFile).mockImplementationOnce(async (...args) => {
+ await (await actual).writeFile(...args);
+ cancellation.abort();
+ });
+
+ await expect(
+ writeAppAddFile({ appPath: root, file, signal: cancellation.signal }),
+ ).rejects.toThrow();
+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);
+ });
+
+ it('reports completion when cancellation arrives after the file was committed', async () => {
+ const cancellation = new AbortController();
+
+ vi.mocked(link).mockImplementationOnce(async (...args) => {
+ await (await actual).link(...args);
+ cancellation.abort();
+ });
+
+ await expect(
+ writeAppAddFile({ appPath: root, file, signal: cancellation.signal }),
+ ).resolves.toBeUndefined();
+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);
+ expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);
+ });
+
+ it('returns a cleanup warning path after a successful commit instead of reporting failure', async () => {
+ vi.mocked(rm).mockRejectedValueOnce(new Error('cleanup denied'));
+
+ const cleanupPath = await writeAppAddFile({
+ appPath: root,
+ file,
+ signal: new AbortController().signal,
+ });
+
+ expect(cleanupPath).toContain(join(root, 'src/objects/.twenty-add-'));
+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);
+ });
+});
diff --git a/packages/twenty-cli/src/app/add/constants/app-add-entities.constant.ts b/packages/twenty-cli/src/app/add/constants/app-add-entities.constant.ts
new file mode 100644
index 00000000000..ca08e533aea
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/constants/app-add-entities.constant.ts
@@ -0,0 +1,6 @@
+export const APP_ADD_ENTITIES = [
+ 'object',
+ 'field',
+ 'logic-function',
+ 'front-component',
+] as const;
diff --git a/packages/twenty-cli/src/app/add/entity-field-template.ts b/packages/twenty-cli/src/app/add/entity-field-template.ts
new file mode 100644
index 00000000000..3f6872af476
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/entity-field-template.ts
@@ -0,0 +1,73 @@
+import { randomUUID } from 'node:crypto';
+
+import { printTypescriptValue } from '@/app/pull/print-typescript-value';
+import {
+ FieldMetadataType,
+ type RelationOnDeleteAction,
+ type RelationType,
+} from 'twenty-shared/types';
+
+export const getFieldBaseFile = ({
+ data,
+}: {
+ data: {
+ name: string;
+ label: string;
+ type: FieldMetadataType;
+ objectUniversalIdentifier: string;
+ description?: string;
+ relationTargetObjectMetadataUniversalIdentifier?: string;
+ relationTargetFieldMetadataUniversalIdentifier?: string;
+ relationType?: RelationType;
+ onDelete?: RelationOnDeleteAction | 'None';
+ };
+ name: string;
+}) => {
+ const universalIdentifier = randomUUID();
+ const descriptionLine = data.description
+ ? `\n description: ${printTypescriptValue({ value: data.description })},`
+ : '';
+
+ const isRelation =
+ data.type === FieldMetadataType.RELATION ||
+ data.type === FieldMetadataType.MORPH_RELATION;
+
+ if (isRelation) {
+ const hasOnDelete = data.onDelete && data.onDelete !== 'None';
+ const importLine = `import { defineField, FieldType, RelationType${
+ hasOnDelete ? ', OnDeleteAction' : ''
+ } } from 'twenty-sdk/define';`;
+ const onDeleteSetting = hasOnDelete
+ ? `, onDelete: OnDeleteAction.${data.onDelete}`
+ : '';
+ const morphIdLine =
+ data.type === FieldMetadataType.MORPH_RELATION
+ ? `\n morphId: '${randomUUID()}',`
+ : '';
+
+ return `${importLine}
+
+export default defineField({
+ universalIdentifier: '${universalIdentifier}',
+ name: ${printTypescriptValue({ value: data.name })},
+ label: ${printTypescriptValue({ value: data.label })},
+ type: FieldType.${data.type},
+ objectUniversalIdentifier: ${printTypescriptValue({ value: data.objectUniversalIdentifier })},
+ relationTargetObjectMetadataUniversalIdentifier: ${printTypescriptValue({ value: data.relationTargetObjectMetadataUniversalIdentifier })},
+ relationTargetFieldMetadataUniversalIdentifier: ${printTypescriptValue({ value: data.relationTargetFieldMetadataUniversalIdentifier })},
+ universalSettings: { relationType: RelationType.${data.relationType}${onDeleteSetting} },${morphIdLine}${descriptionLine}
+});
+`;
+ }
+
+ return `import { defineField, FieldType } from 'twenty-sdk/define';
+
+export default defineField({
+ universalIdentifier: '${universalIdentifier}',
+ name: ${printTypescriptValue({ value: data.name })},
+ label: ${printTypescriptValue({ value: data.label })},
+ type: FieldType.${data.type},
+ objectUniversalIdentifier: ${printTypescriptValue({ value: data.objectUniversalIdentifier })},${descriptionLine}
+});
+`;
+};
diff --git a/packages/twenty-cli/src/app/add/entity-front-component-template.ts b/packages/twenty-cli/src/app/add/entity-front-component-template.ts
new file mode 100644
index 00000000000..ddea210848e
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/entity-front-component-template.ts
@@ -0,0 +1,33 @@
+import { randomUUID } from 'node:crypto';
+
+import { kebabCase } from '@/app/pull/kebab-case';
+
+export const getFrontComponentBaseFile = ({
+ name,
+ universalIdentifier = randomUUID(),
+}: {
+ name: string;
+ universalIdentifier?: string;
+}) => {
+ const kebabCaseName = kebabCase(name);
+
+ return `import { defineFrontComponent } from 'twenty-sdk/define';
+
+// React component - implement your UI here
+const Component = () => {
+ return (
+ <div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
+ <h1>My new component!</h1>
+ <p>This is your front component: ${kebabCaseName}</p>
+ </div>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: '${universalIdentifier}',
+ name: '${kebabCaseName}',
+ description: 'Add a description for your front component',
+ component: Component,
+});
+`;
+};
diff --git a/packages/twenty-cli/src/app/add/entity-logic-function-template.ts b/packages/twenty-cli/src/app/add/entity-logic-function-template.ts
new file mode 100644
index 00000000000..7f3043415ac
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/entity-logic-function-template.ts
@@ -0,0 +1,55 @@
+import { randomUUID } from 'node:crypto';
+
+import { kebabCase } from '@/app/pull/kebab-case';
+
+export const getLogicFunctionBaseFile = ({
+ name,
+ universalIdentifier = randomUUID(),
+}: {
+ name: string;
+ universalIdentifier?: string;
+}) => {
+ const kebabCaseName = kebabCase(name);
+
+ return `import { defineLogicFunction } from 'twenty-sdk/define';
+
+// Logic function handler - rename and implement your logic
+const handler = async (params: {
+ a: string;
+ b: number;
+}): Promise<{ message: string }> => {
+ const { a, b } = params;
+
+ // Replace with your own logic
+ const message = \`Hello, input: \${a} and \${b}\`;
+
+ return { message };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: '${universalIdentifier}',
+ name: '${kebabCaseName}',
+ description: 'Add a description for your logic function',
+ timeoutSeconds: 5,
+ handler,
+ // Add your trigger here
+ // Route trigger example:
+ // httpRouteTriggerSettings: {
+ // path: '/${kebabCaseName}',
+ // httpMethod: 'POST',
+ // isAuthRequired: true,
+ // },
+ // Cron trigger example:
+ // cronTriggerSettings: {
+ // pattern: '0 0 * * *', // Daily at midnight
+ // },
+ // Database event trigger example:
+ // databaseEventTriggerSettings: {
+ // eventName: 'objectName.created',
+ // // Optional: receive one call per batch of events instead of one per event,
+ // // the handler payload then becomes { ...eventInfo, events: [...] }
+ // batchMode: true,
+ // },
+});
+`;
+};
diff --git a/packages/twenty-cli/src/app/add/entity-object-template.ts b/packages/twenty-cli/src/app/add/entity-object-template.ts
new file mode 100644
index 00000000000..053f4513a22
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/entity-object-template.ts
@@ -0,0 +1,45 @@
+import { randomUUID } from 'node:crypto';
+
+import { printTypescriptValue } from '@/app/pull/print-typescript-value';
+
+export const getObjectBaseFile = ({
+ data,
+ universalIdentifier = randomUUID(),
+ nameFieldUniversalIdentifier = randomUUID(),
+}: {
+ data: {
+ nameSingular: string;
+ namePlural: string;
+ labelSingular: string;
+ labelPlural: string;
+ };
+ name: string;
+ universalIdentifier?: string;
+ nameFieldUniversalIdentifier?: string;
+}) => {
+ return `import { defineObject, FieldType } from 'twenty-sdk/define';
+
+export const NAME_FIELD_UNIVERSAL_IDENTIFIER =
+ '${nameFieldUniversalIdentifier}';
+
+export default defineObject({
+ universalIdentifier: '${universalIdentifier}',
+ nameSingular: ${printTypescriptValue({ value: data.nameSingular })},
+ namePlural: ${printTypescriptValue({ value: data.namePlural })},
+ labelSingular: ${printTypescriptValue({ value: data.labelSingular })},
+ labelPlural: ${printTypescriptValue({ value: data.labelPlural })},
+ icon: 'IconBox',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UNIVERSAL_IDENTIFIER,
+ fields: [
+ {
+ universalIdentifier: NAME_FIELD_UNIVERSAL_IDENTIFIER,
+ type: FieldType.TEXT,
+ name: 'name',
+ label: 'Name',
+ description: ${printTypescriptValue({ value: `Name of the ${data.nameSingular}` })},
+ icon: 'IconAbc',
+ },
+ ],
+});
+`;
+};
diff --git a/packages/twenty-cli/src/app/add/prepare-app-add-file.ts b/packages/twenty-cli/src/app/add/prepare-app-add-file.ts
new file mode 100644
index 00000000000..6d667bad00b
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/prepare-app-add-file.ts
@@ -0,0 +1,251 @@
+import { convertToLabel } from '@create-twenty-app/utils/convert-to-label';
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ RelationOnDeleteAction,
+ RelationType,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { APP_ADD_ENTITIES } from '@/app/add/constants/app-add-entities.constant';
+import { getFieldBaseFile } from '@/app/add/entity-field-template';
+import { getFrontComponentBaseFile } from '@/app/add/entity-front-component-template';
+import { getLogicFunctionBaseFile } from '@/app/add/entity-logic-function-template';
+import { getObjectBaseFile } from '@/app/add/entity-object-template';
+import { promptForAppAddValue } from '@/app/add/prompt-for-app-add-value';
+import { kebabCase } from '@/app/pull/kebab-case';
+import {
+ readStringArgument,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+
+const invalidInput = (message: string) =>
+ new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message,
+ hint: 'Run twenty app add --help for options and examples.',
+ });
+
+export const prepareAppAddFile = async (context: CommandContext) => {
+ const { options, signal } = context;
+ const interactive = isInteractionAllowed(context);
+ const readValue = async ({
+ option,
+ label,
+ value = readStringOption(options, option),
+ defaultValue,
+ choices,
+ }: {
+ option: string;
+ label: string;
+ value?: string;
+ defaultValue?: string;
+ choices?: readonly string[];
+ }): Promise<string> => {
+ signal.throwIfAborted();
+
+ if (!isDefined(value) && interactive) {
+ const choiceHint = choices ? ` (${choices.join(', ')})` : '';
+ const defaultHint = isDefined(defaultValue) ? ` [${defaultValue}]` : '';
+
+ value = await promptForAppAddValue({
+ question: `${label}${choiceHint}${defaultHint}: `,
+ signal,
+ });
+ value = value.trim() || defaultValue;
+ } else {
+ value = value?.trim() ?? defaultValue;
+ }
+
+ if (!isDefined(value) || (value.length === 0 && defaultValue !== '')) {
+ throw invalidInput(
+ `Missing ${label.toLowerCase()}. Provide ${option === 'entity' ? 'an entity argument' : `--${kebabCase(option)}`}.`,
+ );
+ }
+
+ if (choices && !choices.includes(value)) {
+ throw invalidInput(
+ `Invalid ${label.toLowerCase()}: ${value}. Expected ${choices.join(', ')}.`,
+ );
+ }
+
+ return value;
+ };
+ const readIdentifier = async (option: string, label: string) => {
+ const value = await readValue({ option, label });
+
+ if (!isValidUniversalIdentifier(value)) {
+ throw invalidInput(`${label} must be a UUID (version 4 or later).`);
+ }
+
+ return value;
+ };
+ const entity = await readValue({
+ option: 'entity',
+ label: 'Entity',
+ value: readStringArgument(context.arguments, 0),
+ choices: APP_ADD_ENTITIES,
+ });
+ const objectOptions = ['namePlural', 'labelPlural'];
+ const fieldOptions = ['type', 'object', 'description'];
+ const relationOptions = [
+ 'targetObject',
+ 'targetField',
+ 'relationType',
+ 'onDelete',
+ ];
+ const rejectOptions = (names: string[]) => {
+ const supplied = names.filter((option) =>
+ isDefined(readStringOption(options, option)),
+ );
+
+ if (supplied.length > 0) {
+ throw invalidInput(
+ `Options do not apply to this definition: ${supplied.map((option) => `--${kebabCase(option)}`).join(', ')}.`,
+ );
+ }
+ };
+
+ if (entity !== 'object') rejectOptions(objectOptions);
+ if (entity !== 'field') rejectOptions([...fieldOptions, ...relationOptions]);
+ if (entity !== 'object' && entity !== 'field') rejectOptions(['label']);
+
+ const name = await readValue({ option: 'name', label: 'Name' });
+ const fileName = kebabCase(name);
+
+ if (!/[a-z0-9]/.test(fileName)) {
+ throw invalidInput('Name must contain at least one ASCII letter or digit.');
+ }
+
+ let content: string;
+
+ switch (entity) {
+ case 'object': {
+ const namePlural = await readValue({
+ option: 'namePlural',
+ label: 'Plural name',
+ });
+
+ if (namePlural === name) {
+ throw invalidInput('Singular and plural object names must differ.');
+ }
+
+ const labelSingular = await readValue({
+ option: 'label',
+ label: 'Singular label',
+ defaultValue: convertToLabel(name),
+ });
+ const labelPlural = await readValue({
+ option: 'labelPlural',
+ label: 'Plural label',
+ defaultValue: convertToLabel(namePlural),
+ });
+
+ content = getObjectBaseFile({
+ name,
+ data: { nameSingular: name, namePlural, labelSingular, labelPlural },
+ });
+ break;
+ }
+ case 'field': {
+ const label = await readValue({
+ option: 'label',
+ label: 'Label',
+ defaultValue: convertToLabel(name),
+ });
+ const typeValue = await readValue({
+ option: 'type',
+ label: 'Field type',
+ defaultValue: FieldMetadataType.TEXT,
+ choices: Object.values(FieldMetadataType),
+ });
+ const type = Object.values(FieldMetadataType).find(
+ (candidate) => candidate === typeValue,
+ );
+
+ if (!isDefined(type)) {
+ throw invalidInput(`Invalid field type: ${typeValue}.`);
+ }
+
+ const objectUniversalIdentifier = await readIdentifier(
+ 'object',
+ 'Parent object universal identifier',
+ );
+ const description = await readValue({
+ option: 'description',
+ label: 'Description',
+ defaultValue: '',
+ });
+ const data: Parameters<typeof getFieldBaseFile>[0]['data'] = {
+ name,
+ label,
+ type,
+ objectUniversalIdentifier,
+ description,
+ };
+
+ if (
+ type === FieldMetadataType.RELATION ||
+ type === FieldMetadataType.MORPH_RELATION
+ ) {
+ data.relationTargetObjectMetadataUniversalIdentifier =
+ await readIdentifier(
+ 'targetObject',
+ 'Target object universal identifier',
+ );
+ data.relationTargetFieldMetadataUniversalIdentifier =
+ await readIdentifier(
+ 'targetField',
+ 'Target field universal identifier',
+ );
+ const relationType = await readValue({
+ option: 'relationType',
+ label: 'Relation type',
+ defaultValue: RelationType.ONE_TO_MANY,
+ choices: Object.values(RelationType),
+ });
+ const onDelete = await readValue({
+ option: 'onDelete',
+ label: 'On delete',
+ defaultValue: RelationOnDeleteAction.CASCADE,
+ choices: [...Object.values(RelationOnDeleteAction), 'None'],
+ });
+
+ data.relationType = Object.values(RelationType).find(
+ (candidate) => candidate === relationType,
+ );
+ data.onDelete =
+ onDelete === 'None'
+ ? 'None'
+ : Object.values(RelationOnDeleteAction).find(
+ (candidate) => candidate === onDelete,
+ );
+ } else {
+ rejectOptions(relationOptions);
+ }
+
+ content = getFieldBaseFile({ name, data });
+ break;
+ }
+ case 'logic-function':
+ content = getLogicFunctionBaseFile({ name });
+ break;
+ case 'front-component':
+ content = getFrontComponentBaseFile({ name });
+ break;
+ default:
+ throw invalidInput(`Unsupported entity: ${entity}.`);
+ }
+
+ return {
+ entity,
+ name,
+ path: `src/${entity}s/${fileName}.${entity === 'front-component' ? 'tsx' : 'ts'}`,
+ content,
+ };
+};
diff --git a/packages/twenty-cli/src/app/add/prompt-for-app-add-value.ts b/packages/twenty-cli/src/app/add/prompt-for-app-add-value.ts
new file mode 100644
index 00000000000..4e91d4d8e10
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/prompt-for-app-add-value.ts
@@ -0,0 +1,37 @@
+import { createInterface } from 'node:readline/promises';
+
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+export const promptForAppAddValue = async ({
+ question,
+ signal,
+}: {
+ question: string;
+ signal: AbortSignal;
+}): Promise<string> => {
+ signal.throwIfAborted();
+
+ const terminal = createInterface({
+ input: process.stdin,
+ output: process.stderr,
+ });
+ const cancellation = new AbortController();
+ const cancel = () => cancellation.abort();
+
+ terminal.on('SIGINT', cancel);
+ terminal.on('close', cancel);
+
+ try {
+ return await terminal.question(question, {
+ signal: AbortSignal.any([signal, cancellation.signal]),
+ });
+ } catch (error) {
+ if (signal.aborted || cancellation.signal.aborted) {
+ throw createCancelledError();
+ }
+
+ throw error;
+ } finally {
+ terminal.close();
+ }
+};
diff --git a/packages/twenty-cli/src/app/add/write-app-add-file.ts b/packages/twenty-cli/src/app/add/write-app-add-file.ts
new file mode 100644
index 00000000000..0d73f45f481
--- /dev/null
+++ b/packages/twenty-cli/src/app/add/write-app-add-file.ts
@@ -0,0 +1,66 @@
+import { link, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+
+import { AppPathError } from '@/app/pull/app-path-error';
+import { assertPullPaths } from '@/app/pull/assert-pull-paths';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const writeAppAddFile = async ({
+ appPath,
+ file,
+ signal,
+}: {
+ appPath: string;
+ file: { path: string; content: string };
+ signal: AbortSignal;
+}) => {
+ signal.throwIfAborted();
+
+ try {
+ await assertPullPaths({ appPath, relativePaths: [file.path] });
+ } catch (error) {
+ if (!(error instanceof AppPathError)) throw error;
+
+ throw new CliError({
+ code: 'APP_PATH_UNAVAILABLE',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `Cannot create ${file.path}: the destination must stay inside the app and cannot contain symbolic links.`,
+ });
+ }
+
+ const destination = join(appPath, file.path);
+
+ await mkdir(dirname(destination), { recursive: true });
+ signal.throwIfAborted();
+
+ const temporaryDirectory = await mkdtemp(
+ join(dirname(destination), '.twenty-add-'),
+ );
+ const temporaryPath = join(temporaryDirectory, 'definition');
+ let cleanupFailed = false;
+
+ try {
+ await writeFile(temporaryPath, file.content, { flag: 'wx' });
+ signal.throwIfAborted();
+ await link(temporaryPath, destination);
+ } catch (error) {
+ if (hasErrorCode(error, 'EEXIST')) {
+ throw new CliError({
+ code: 'APP_PATH_UNAVAILABLE',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `${file.path} already exists. No files were changed.`,
+ hint: 'Choose a different name, or edit the existing definition.',
+ });
+ }
+
+ throw error;
+ } finally {
+ await rm(temporaryDirectory, { recursive: true, force: true }).catch(() => {
+ cleanupFailed = true;
+ });
+ }
+
+ return cleanupFailed ? temporaryDirectory : undefined;
+};
diff --git a/packages/twenty-cli/src/app/bundles/README.md b/packages/twenty-cli/src/app/bundles/README.md
new file mode 100644
index 00000000000..1e36f021916
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/README.md
@@ -0,0 +1,85 @@
+# Bundles and snapshots
+
+The CLI owns application bundling and immutable snapshot lifecycle. The internal
+`bundleSnapshot` worker request builds and holds or releases a snapshot under
+`.twenty/cli/snapshots/build-*`. The [typechecker](../typecheck/README.md) uses the
+app's own TypeScript compiler. Build, plan, apply and uninstall use this pipeline.
+Worker requests are internal, not a public API or a way to bypass build checks.
+
+See the [app tooling overview](../README.md) for package ownership.
+
+## Contract
+
+Logic functions use an ESM/CJS banner, external modules and define stubs.
+Front components use JSX wrappers, remote-DOM transformation, optional
+preact aliases, bundled CSS injection, static shared-dependency export discovery
+and live-binding shims. The app's translation catalogs are embedded in the bundles.
+Dependency discovery does not execute package initialization code. CommonJS
+named exports must be statically detectable; packages that compute export names
+at runtime can be consumed through their default export.
+
+The bundler collects source and dependency files, public and generated assets,
+and the README, and updates the manifest's artifact checksums. Snapshot copies
+dereference symlinks. Each upload artifact records its role, byte size and
+SHA-256 hash. README and source maps are included in the snapshot but are not
+upload artifacts. The content hash combines the sorted artifact paths, roles and
+hashes with the exact manifest bytes.
+
+Each build has its own directory and lease. Release removes only a snapshot held
+by that worker. Failed and cooperatively cancelled builds remove their temporary
+directory. Forced worker termination can leave a snapshot behind. Cleanup only
+removes snapshots owned by the current build.
+
+## Implementation
+
+- Source loading, manifest generation, translations and filesystem helpers are
+ shared with the other CLI app operations. The [dev session](../dev/README.md)
+ observes the build's inputs and retains immutable copies for remote apply.
+- The define stub reads `twenty-sdk/define` from the app's installed SDK. Factories
+ become no-op validators, plain-data exports retain their values, and other
+ exports use proxy stubs. Runtime constants match the SDK the app uses.
+- `sharp` is optional and resolved from the app. It is not a CLI dependency.
+ When unavailable, cover generation warns and the build continues. Vite embeds
+ the backdrop PNG as a data URI so it works in the standalone package.
+- `compileApplication` runs the CLI typecheck after bundling, using the compiler
+ resolved from the app.
+- Workers run from the selected app directory, so invoking the CLI from a
+ parent or nested directory produces the same bundle paths, bytes and hashes.
+ SDK parity references run from the app root as well.
+- Upload validation accepts only snapshots inside the selected app's
+ `.twenty/cli/snapshots`, with path containment and per-file hash checks.
+- The internal worker reuses the source SDK gate, credential filtering, output
+ capture, cancellation and held-snapshot release flow, and stops esbuild after
+ building. Public app commands share this worker lifecycle and its
+ `ToolingResult` contract.
+
+## Verification
+
+After building shared, SDK and UI dependencies, from `packages/twenty-cli`:
+
+```bash
+node ../../node_modules/vitest/vitest.mjs run --config vitest.config.ts --maxWorkers=1 src/app/snapshots src/app/bundles src/app/__tests__/resolve-snapshot-directory.spec.ts src/commands/app/__tests__/app-real-sdk.spec.ts
+```
+
+The parity suite builds all five repository fixtures and a fresh CLI-created app
+through the SDK reference and the production CLI worker. The app has a copy of
+the real authoring SDK without its build/CLI exports or implementation files.
+Successful builds preserve manifest configuration and artifact paths/roles.
+Non-frontend files are compared byte for byte, except for `manifest.json` and
+source maps. Frontend bundle bytes and checksums are allowed to differ: dedicated tests verify preserved
+string literals, resolved CSS assets and live shared-dependency bindings. Every
+CLI artifact's size/checksum and the snapshot content hash are checked against
+the actual bytes. Tests also verify the manifest references for function, component
+and shared-dependency bundles, and compare the serialized manifest with the
+worker's manifest result. The invalid fixture fails in both
+pipelines. The fresh CLI template's test setup typechecks with an authoring-only SDK.
+
+Source-map comparisons for unchanged bundles resolve paths against each map's
+directory and exclude the define stub's generator banner from `sourcesContent`.
+
+Additional tests cover optional covers, project SDK constants, baked translations
+and CSS, README selection, immutable symlink copies, concurrent snapshots,
+release ownership, failed/cancelled builds and failed snapshot consumers. The
+build/apply contract runs CLI snapshots against a local HTTP fixture, including
+uploads, sync, pull-base recording, release and client generation. It does not contact
+a live Twenty workspace.
diff --git a/packages/twenty-cli/src/app/bundles/__tests__/build-inputs.spec.ts b/packages/twenty-cli/src/app/bundles/__tests__/build-inputs.spec.ts
new file mode 100644
index 00000000000..e407cd426ab
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/__tests__/build-inputs.spec.ts
@@ -0,0 +1,52 @@
+import {
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { expect, it, vi } from 'vitest';
+import { FileFolder } from 'twenty-shared/types';
+import { copyReadmeToOutput } from '@/app/bundles/copy-readme-to-output';
+import { esbuildOneShotBuild } from '@/app/bundles/esbuild-one-shot-build';
+import { collectWatchInputs } from '@/app/dev/collect-watch-inputs';
+import { readWatchInputStamp } from '@/app/dev/read-watch-input-stamp';
+
+it('tracks the real README target so edits invalidate a build', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'readme-watch-'));
+ try {
+ const appPath = join(root, 'app');
+ const readme = join(root, 'README.md');
+ await mkdir(appPath);
+ await writeFile(readme, 'before');
+ await symlink(readme, join(appPath, 'README.md'));
+ const { watchInputs } = await collectWatchInputs(() =>
+ copyReadmeToOutput({ appPath, dereferenceSymlinks: true }),
+ );
+ const canonicalReadme = await realpath(readme);
+ const input = watchInputs.find((entry) => entry.path === canonicalReadme);
+ expect(input?.path).toBe(await realpath(readme));
+ if (!input) throw new Error('README was not watched');
+ await writeFile(readme, 'after with new content');
+ expect(readWatchInputStamp(input)).not.toBe(input.stamp);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+it('rejects colliding TypeScript entry points before building', async () => {
+ const onFileBuilt = vi.fn();
+ await expect(
+ esbuildOneShotBuild({
+ appPath: '/app',
+ sourcePaths: ['src/example.ts', 'src/example.tsx'],
+ fileFolder: FileFolder.BuiltLogicFunction,
+ buildOptions: {},
+ onFileBuilt,
+ }),
+ ).rejects.toThrow('produce the same build output');
+ expect(onFileBuilt).not.toHaveBeenCalled();
+});
diff --git a/packages/twenty-cli/src/app/bundles/build-application.ts b/packages/twenty-cli/src/app/bundles/build-application.ts
new file mode 100644
index 00000000000..df3269b5bd2
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/build-application.ts
@@ -0,0 +1,271 @@
+import { recordWatchFile } from '@/app/dev/collect-watch-inputs';
+import crypto from 'crypto';
+import { readFile, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'path';
+import {
+ NODE_ESM_CJS_BANNER,
+ OUTPUT_DIR,
+ type Manifest,
+} from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { copyBuildFile } from '@/app/bundles/copy-build-file';
+import { copyReadmeToOutput } from '@/app/bundles/copy-readme-to-output';
+import { type GeneratedAsset } from '@/app/bundles/cover/generated-asset.type';
+import { esbuildOneShotBuild } from '@/app/bundles/esbuild-one-shot-build';
+import { LOGIC_FUNCTION_EXTERNAL_MODULES } from '@/app/bundles/constants/logic-function-external-modules';
+import { getBaseFrontComponentBuildOptions } from '@/app/bundles/front-component-build/utils/get-base-front-component-build-options';
+import { getFrontComponentBuildPlugins } from '@/app/bundles/front-component-build/utils/get-front-component-build-plugins';
+import { createStubTwentySdkDefinePlugin } from '@/app/bundles/plugins/stub-twenty-sdk-define.plugin';
+import { type OnFileBuiltCallback } from '@/app/bundles/types/on-file-built-callback.type';
+import { buildSharedDependenciesBundle } from '@/app/bundles/front-component-build/shared-dependencies-build/build-shared-dependencies-bundle';
+import { type SharedDependenciesBuildContext } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type';
+import { type EntityFilePaths } from '@/app/manifest/types/entity-file-paths.type';
+import { loadFrontComponentTranslationCatalogs } from '@/app/translations/load-front-component-translation-catalogs';
+import {
+ emptyDir,
+ ensureDir,
+ pathExists,
+ pathExistsSync,
+} from '@/app/fs-utils';
+import { FRONT_COMPONENT_TRANSLATIONS_KEY } from '@/app/bundles/constants/front-component-translations-key';
+
+export type AppBuildOptions = {
+ appPath: string;
+ manifest: Manifest;
+ filePaths: EntityFilePaths;
+ generatedAssets?: GeneratedAsset[];
+ outputDir?: string;
+ dereferenceSymlinks?: boolean;
+};
+
+export type BuiltFileInfo = {
+ checksum: string;
+ builtPath: string;
+ sourcePath: string;
+ fileFolder: FileFolder;
+ usesSdkClient?: boolean;
+};
+
+export type AppBuildResult = {
+ builtFileInfos: Map<string, BuiltFileInfo>;
+};
+
+export const buildApplication = async (
+ options: AppBuildOptions,
+): Promise<AppBuildResult> => {
+ const relativeOutputDir = options.outputDir ?? OUTPUT_DIR;
+ const outputDir = join(options.appPath, relativeOutputDir);
+
+ await ensureDir(outputDir);
+ await emptyDir(outputDir);
+
+ const builtFileInfos = new Map<string, BuiltFileInfo>();
+
+ const collectFileBuilt: OnFileBuiltCallback = (event) => {
+ builtFileInfos.set(event.builtPath, {
+ checksum: event.checksum,
+ builtPath: event.builtPath,
+ sourcePath: event.sourcePath,
+ fileFolder: event.fileFolder,
+ usesSdkClient: event.usesSdkClient,
+ });
+ };
+
+ const { logicFunctions, frontComponents } = options.filePaths;
+ const sharedDependencies =
+ options.manifest.application.frontComponentSharedDependencies;
+
+ const frontComponentTranslationCatalogs =
+ await loadFrontComponentTranslationCatalogs(options.appPath);
+
+ const frontComponentTranslationsBanner = Object.keys(
+ frontComponentTranslationCatalogs,
+ ).length
+ ? {
+ js: `globalThis[${JSON.stringify(FRONT_COMPONENT_TRANSLATIONS_KEY)}]=${JSON.stringify(
+ frontComponentTranslationCatalogs,
+ )};`,
+ }
+ : undefined;
+
+ await esbuildOneShotBuild({
+ appPath: options.appPath,
+ sourcePaths: logicFunctions,
+ fileFolder: FileFolder.BuiltLogicFunction,
+ buildOptions: {
+ bundle: true,
+ splitting: false,
+ format: 'esm',
+ platform: 'node',
+ outdir: outputDir,
+ outExtension: { '.js': '.mjs' },
+ external: LOGIC_FUNCTION_EXTERNAL_MODULES,
+ tsconfig: join(options.appPath, 'tsconfig.json'),
+ sourcemap: true,
+ metafile: true,
+ logLevel: 'silent',
+ banner: NODE_ESM_CJS_BANNER,
+ plugins: [createStubTwentySdkDefinePlugin(options.appPath)],
+ },
+ onFileBuilt: collectFileBuilt,
+ });
+
+ const sharedDependenciesBuildContext: SharedDependenciesBuildContext | null =
+ isDefined(sharedDependencies)
+ ? await buildSharedDependenciesBundle({
+ appPath: options.appPath,
+ outputDir: relativeOutputDir,
+ sharedDependencies,
+ onFileBuilt: collectFileBuilt,
+ })
+ : null;
+
+ await esbuildOneShotBuild({
+ appPath: options.appPath,
+ sourcePaths: frontComponents,
+ fileFolder: FileFolder.BuiltFrontComponent,
+ buildOptions: {
+ ...getBaseFrontComponentBuildOptions(),
+ outdir: outputDir,
+ tsconfig: join(options.appPath, 'tsconfig.json'),
+ jsx: 'automatic',
+ sourcemap: true,
+ metafile: true,
+ logLevel: 'silent',
+ ...(frontComponentTranslationsBanner !== undefined
+ ? { banner: frontComponentTranslationsBanner }
+ : {}),
+ plugins: [
+ ...getFrontComponentBuildPlugins({
+ getSharedDependenciesBuildContext: () =>
+ sharedDependenciesBuildContext,
+ }),
+ createStubTwentySdkDefinePlugin(options.appPath),
+ ],
+ },
+ onFileBuilt: collectFileBuilt,
+ });
+
+ await copyStaticFiles({
+ appPath: options.appPath,
+ fileFolder: FileFolder.Source,
+ filePaths: [...new Set([...logicFunctions, ...frontComponents])],
+ collectFileBuilt,
+ outputDir: relativeOutputDir,
+ dereferenceSymlinks: options.dereferenceSymlinks,
+ });
+
+ await copyStaticFiles({
+ appPath: options.appPath,
+ fileFolder: FileFolder.PublicAsset,
+ filePaths: options.filePaths.publicAssets,
+ collectFileBuilt,
+ outputDir: relativeOutputDir,
+ dereferenceSymlinks: options.dereferenceSymlinks,
+ });
+
+ await copyStaticFiles({
+ appPath: options.appPath,
+ fileFolder: FileFolder.Dependencies,
+ filePaths: ['package.json', 'yarn.lock'].filter((filePath) =>
+ pathExistsSync(join(options.appPath, filePath)),
+ ),
+ collectFileBuilt,
+ outputDir: relativeOutputDir,
+ dereferenceSymlinks: options.dereferenceSymlinks,
+ });
+
+ for (const generatedAsset of options.generatedAssets ?? []) {
+ await writeGeneratedAsset({
+ appPath: options.appPath,
+ generatedAsset,
+ outputDir: relativeOutputDir,
+ collectFileBuilt,
+ });
+ }
+
+ await copyReadmeToOutput({
+ appPath: options.appPath,
+ relativeOutputDir,
+ dereferenceSymlinks: options.dereferenceSymlinks,
+ });
+
+ return { builtFileInfos };
+};
+
+const writeGeneratedAsset = async ({
+ appPath,
+ generatedAsset,
+ outputDir,
+ collectFileBuilt,
+}: {
+ appPath: string;
+ generatedAsset: GeneratedAsset;
+ outputDir: string;
+ collectFileBuilt: OnFileBuiltCallback;
+}) => {
+ const builtPath = join(outputDir, generatedAsset.relativePath);
+ const absoluteBuiltPath = join(appPath, builtPath);
+
+ await ensureDir(dirname(absoluteBuiltPath));
+ await writeFile(absoluteBuiltPath, generatedAsset.content);
+
+ const checksum = crypto
+ .createHash('md5')
+ .update(generatedAsset.content)
+ .digest('hex');
+
+ await collectFileBuilt({
+ fileFolder: FileFolder.PublicAsset,
+ builtPath,
+ sourcePath: generatedAsset.relativePath,
+ checksum,
+ });
+};
+
+const copyStaticFiles = async ({
+ appPath,
+ fileFolder,
+ filePaths,
+ outputDir,
+ dereferenceSymlinks = false,
+ collectFileBuilt,
+}: {
+ appPath: string;
+ fileFolder: FileFolder;
+ filePaths: string[];
+ outputDir: string;
+ dereferenceSymlinks?: boolean;
+ collectFileBuilt: OnFileBuiltCallback;
+}) => {
+ for (const sourcePath of filePaths) {
+ const absoluteSourcePath = join(appPath, sourcePath);
+ recordWatchFile(absoluteSourcePath);
+
+ if (!(await pathExists(absoluteSourcePath))) {
+ continue;
+ }
+
+ const builtPath = join(outputDir, sourcePath);
+ const absoluteBuiltPath = join(appPath, builtPath);
+
+ await ensureDir(dirname(absoluteBuiltPath));
+ await copyBuildFile({
+ sourcePath: absoluteSourcePath,
+ destinationPath: absoluteBuiltPath,
+ dereferenceSymlinks,
+ });
+
+ const content = await readFile(absoluteBuiltPath);
+ const checksum = crypto.createHash('md5').update(content).digest('hex');
+
+ await collectFileBuilt({
+ fileFolder,
+ builtPath,
+ sourcePath,
+ checksum,
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/bundles/compile-application.ts b/packages/twenty-cli/src/app/bundles/compile-application.ts
new file mode 100644
index 00000000000..ce131db4182
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/compile-application.ts
@@ -0,0 +1,135 @@
+import { OUTPUT_DIR, type Manifest } from 'twenty-shared/application';
+
+import {
+ type ToolingDiagnostic,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import {
+ buildApplication,
+ type BuiltFileInfo,
+} from '@/app/bundles/build-application';
+import { applyGeneratedCover } from '@/app/bundles/cover/apply-generated-cover';
+import { buildAndValidateManifest } from '@/app/manifest/build-and-validate-manifest';
+import { manifestUpdateChecksums } from '@/app/manifest/manifest-update-checksums';
+import { writeManifestToOutput } from '@/app/manifest/manifest-writer';
+import { typecheckApplication } from '@/app/typecheck/typecheck-application';
+import { compileApplicationTranslations } from '@/app/translations/compile-application-translations';
+
+export const compileApplication = async ({
+ appPath,
+ outputDir = OUTPUT_DIR,
+ dereferenceSymlinks = false,
+ onProgress,
+ onTranslationWarning,
+ signal,
+ typecheck = typecheckApplication,
+}: {
+ appPath: string;
+ outputDir?: string;
+ dereferenceSymlinks?: boolean;
+ onProgress?: (message: string) => void;
+ onTranslationWarning?: (message: string) => void;
+ signal?: AbortSignal;
+ typecheck?: typeof typecheckApplication;
+}): Promise<
+ ToolingResult<{
+ manifest: Manifest;
+ builtFileInfos: Map<string, BuiltFileInfo>;
+ }>
+> => {
+ const diagnostics: ToolingDiagnostic[] = [];
+ const warn = (message: string) => {
+ diagnostics.push({ severity: 'warning', code: 'BUILD_WARNING', message });
+ onProgress?.(`⚠ ${message}`);
+ };
+
+ signal?.throwIfAborted();
+ onProgress?.('Building manifest...');
+ const manifestResult = await buildAndValidateManifest(appPath);
+
+ if (!manifestResult.success) {
+ return {
+ success: false,
+ error: {
+ code: 'MANIFEST_BUILD_FAILED',
+ message: manifestResult.errors.join('\n'),
+ },
+ diagnostics: manifestResult.errors.map((message) => ({
+ severity: 'error',
+ code: 'MANIFEST_BUILD_FAILED',
+ message,
+ })),
+ };
+ }
+
+ manifestResult.warnings.forEach(warn);
+
+ signal?.throwIfAborted();
+ const { manifest, generatedAssets } = await applyGeneratedCover({
+ appPath,
+ manifest: manifestResult.manifest,
+ }).catch((error) => {
+ warn(
+ `Skipped cover image generation: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ return { manifest: manifestResult.manifest, generatedAssets: [] };
+ });
+
+ if (generatedAssets.length > 0) {
+ onProgress?.('Generated cover image from logo');
+ }
+
+ const translations = await compileApplicationTranslations({
+ appPath,
+ onWarning: (message) => {
+ if (onTranslationWarning) {
+ diagnostics.push({
+ severity: 'warning',
+ code: 'BUILD_WARNING',
+ message,
+ });
+ onTranslationWarning(message);
+ } else {
+ warn(message);
+ }
+ },
+ });
+
+ signal?.throwIfAborted();
+ onProgress?.('Building application files...');
+ const { builtFileInfos } = await buildApplication({
+ appPath,
+ manifest,
+ filePaths: manifestResult.filePaths,
+ generatedAssets,
+ outputDir,
+ dereferenceSymlinks,
+ });
+
+ onProgress?.('Running typecheck...');
+ const typecheckResult = await typecheck({ appPath, signal });
+
+ diagnostics.push(...typecheckResult.diagnostics);
+
+ if (!typecheckResult.success) {
+ return { ...typecheckResult, diagnostics };
+ }
+
+ const updatedManifest = {
+ ...manifestUpdateChecksums({ manifest, builtFileInfos, outputDir }),
+ translations,
+ };
+
+ await writeManifestToOutput({
+ appPath,
+ manifest: updatedManifest,
+ relativeOutputDir: outputDir,
+ });
+
+ return {
+ success: true,
+ data: { manifest: updatedManifest, builtFileInfos },
+ diagnostics,
+ };
+};
diff --git a/packages/twenty-cli/src/app/bundles/constants/front-component-translations-key.ts b/packages/twenty-cli/src/app/bundles/constants/front-component-translations-key.ts
new file mode 100644
index 00000000000..6a73d994dbb
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/constants/front-component-translations-key.ts
@@ -0,0 +1,2 @@
+export const FRONT_COMPONENT_TRANSLATIONS_KEY =
+ '__twentySdkFrontComponentTranslations__';
diff --git a/packages/twenty-cli/src/app/bundles/constants/logic-function-external-modules.ts b/packages/twenty-cli/src/app/bundles/constants/logic-function-external-modules.ts
new file mode 100644
index 00000000000..117a8e94a76
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/constants/logic-function-external-modules.ts
@@ -0,0 +1,22 @@
+export const LOGIC_FUNCTION_EXTERNAL_MODULES: string[] = [
+ 'twenty-client-sdk/core',
+ 'twenty-client-sdk/metadata',
+ 'path',
+ 'fs',
+ 'crypto',
+ 'stream',
+ 'util',
+ 'os',
+ 'url',
+ 'http',
+ 'https',
+ 'events',
+ 'buffer',
+ 'querystring',
+ 'assert',
+ 'zlib',
+ 'net',
+ 'tls',
+ 'child_process',
+ 'worker_threads',
+];
diff --git a/packages/twenty-cli/src/app/bundles/copy-build-file.ts b/packages/twenty-cli/src/app/bundles/copy-build-file.ts
new file mode 100644
index 00000000000..c1739d900c6
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/copy-build-file.ts
@@ -0,0 +1,19 @@
+import { copyFile } from 'node:fs/promises';
+
+import { copy } from '@/app/fs-utils';
+
+export const copyBuildFile = ({
+ sourcePath,
+ destinationPath,
+ dereferenceSymlinks = false,
+}: {
+ sourcePath: string;
+ destinationPath: string;
+ dereferenceSymlinks?: boolean;
+}): Promise<void> => {
+ if (dereferenceSymlinks) {
+ return copyFile(sourcePath, destinationPath);
+ }
+
+ return copy(sourcePath, destinationPath);
+};
diff --git a/packages/twenty-cli/src/app/bundles/copy-readme-to-output.ts b/packages/twenty-cli/src/app/bundles/copy-readme-to-output.ts
new file mode 100644
index 00000000000..434b545867a
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/copy-readme-to-output.ts
@@ -0,0 +1,45 @@
+import { readdir } from 'node:fs/promises';
+import { join } from 'node:path';
+import { OUTPUT_DIR } from 'twenty-shared/application';
+
+import { copyBuildFile } from '@/app/bundles/copy-build-file';
+import { recordWatchFile } from '@/app/dev/collect-watch-inputs';
+import { ensureDir } from '@/app/fs-utils';
+
+const README_FILE_NAME_REGEX = /^readme(\.[^.]+)?$/i;
+
+export const findReadmeFileName = (entries: string[]): string | undefined => {
+ const readmeFileNames = entries.filter((entry) =>
+ README_FILE_NAME_REGEX.test(entry),
+ );
+
+ return (
+ readmeFileNames.find((entry) => /\.md$/i.test(entry)) ?? readmeFileNames[0]
+ );
+};
+
+export const copyReadmeToOutput = async ({
+ appPath,
+ relativeOutputDir = OUTPUT_DIR,
+ dereferenceSymlinks = false,
+}: {
+ appPath: string;
+ relativeOutputDir?: string;
+ dereferenceSymlinks?: boolean;
+}): Promise<void> => {
+ const readmeFileName = findReadmeFileName(await readdir(appPath));
+
+ if (readmeFileName === undefined) {
+ return;
+ }
+
+ const outputDir = join(appPath, relativeOutputDir);
+
+ await ensureDir(outputDir);
+ const sourcePath = join(appPath, readmeFileName);
+ const destinationPath = join(outputDir, readmeFileName);
+
+ recordWatchFile(sourcePath);
+
+ await copyBuildFile({ sourcePath, destinationPath, dereferenceSymlinks });
+};
diff --git a/packages/twenty-cli/src/app/bundles/cover/apply-generated-cover.ts b/packages/twenty-cli/src/app/bundles/cover/apply-generated-cover.ts
new file mode 100644
index 00000000000..6d1e2481534
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/apply-generated-cover.ts
@@ -0,0 +1,67 @@
+import { readFile } from 'node:fs/promises';
+import { basename, extname, join } from 'path';
+import { type AssetManifest, type Manifest } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { generateCoverImage } from '@/app/bundles/cover/generate-cover-image';
+import { type GeneratedAsset } from '@/app/bundles/cover/generated-asset.type';
+import { GENERATED_COVER_PATH } from '@/app/bundles/cover/generated-cover-path';
+import { pathExists } from '@/app/fs-utils';
+
+const isAbsoluteUrl = (url: string): boolean =>
+ url.startsWith('http://') || url.startsWith('https://');
+
+export const applyGeneratedCover = async ({
+ appPath,
+ manifest,
+}: {
+ appPath: string;
+ manifest: Manifest;
+}): Promise<{ manifest: Manifest; generatedAssets: GeneratedAsset[] }> => {
+ const { logo, galleryImages } = manifest.application;
+
+ if (!isDefined(logo) || isAbsoluteUrl(logo)) {
+ return { manifest, generatedAssets: [] };
+ }
+
+ if ((galleryImages ?? []).length > 0) {
+ return { manifest, generatedAssets: [] };
+ }
+
+ const logoAbsolutePath = join(appPath, logo);
+
+ if (!(await pathExists(logoAbsolutePath))) {
+ return { manifest, generatedAssets: [] };
+ }
+
+ const logoBuffer = await readFile(logoAbsolutePath);
+ const coverBuffer = await generateCoverImage({ logoBuffer, appPath });
+
+ const coverAsset: AssetManifest = {
+ filePath: GENERATED_COVER_PATH,
+ fileName: basename(GENERATED_COVER_PATH),
+ fileType: extname(GENERATED_COVER_PATH).replace(/^\./, ''),
+ checksum: null,
+ };
+
+ const publicAssets = [
+ ...manifest.publicAssets.filter(
+ (asset) => asset.filePath !== GENERATED_COVER_PATH,
+ ),
+ coverAsset,
+ ];
+
+ return {
+ manifest: {
+ ...manifest,
+ application: {
+ ...manifest.application,
+ galleryImages: [GENERATED_COVER_PATH],
+ },
+ publicAssets,
+ },
+ generatedAssets: [
+ { relativePath: GENERATED_COVER_PATH, content: coverBuffer },
+ ],
+ };
+};
diff --git a/packages/twenty-cli/src/app/bundles/cover/assets/halftone-backdrop.png b/packages/twenty-cli/src/app/bundles/cover/assets/halftone-backdrop.png
new file mode 100644
index 00000000000..7b994a6e964
Binary files /dev/null and b/packages/twenty-cli/src/app/bundles/cover/assets/halftone-backdrop.png differ
diff --git a/packages/twenty-cli/src/app/bundles/cover/assets/image.d.ts b/packages/twenty-cli/src/app/bundles/cover/assets/image.d.ts
new file mode 100644
index 00000000000..26481999f7c
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/assets/image.d.ts
@@ -0,0 +1,4 @@
+declare module '*.png?inline' {
+ const dataUri: string;
+ export default dataUri;
+}
diff --git a/packages/twenty-cli/src/app/bundles/cover/assets/twenty-logo-mark-path.ts b/packages/twenty-cli/src/app/bundles/cover/assets/twenty-logo-mark-path.ts
new file mode 100644
index 00000000000..d4ba4a71ac7
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/assets/twenty-logo-mark-path.ts
@@ -0,0 +1,2 @@
+export const TWENTY_LOGO_MARK_PATH =
+ 'M6.822 14.174c0-2.435 1.996-4.411 4.456-4.411h8.574c.125 0 .241.075.293.19a.31.31 0 0 1-.056.344l-1.88 2.023c-.326.35-.787.552-1.27.552H11.3c-.738 0-1.338.594-1.338 1.325v3.336a.78.78 0 0 1-.783.777H7.61a.78.78 0 0 1-.783-.777v-3.36zM33.5 25.553c0 2.434-1.996 4.411-4.456 4.411h-3.642c-2.46 0-4.454-1.977-4.454-4.411v-6.315c0-.43.16-.842.456-1.16l2.124-2.285a.33.33 0 0 1 .355-.081.32.32 0 0 1 .205.295v9.527c0 .73.598 1.322 1.337 1.322h3.6a1.33 1.33 0 0 0 1.337-1.322V14.197c0-.73-.599-1.325-1.337-1.325H24.84c-.481 0-.938.201-1.265.547L11.088 26.856h7.503a.78.78 0 0 1 .784.778v1.552a.78.78 0 0 1-.784.778H8.481a1.655 1.655 0 0 1-1.662-1.644v-.824c0-.412.156-.809.44-1.114l13.999-15.06a4.9 4.9 0 0 1 3.594-1.56h4.189c2.46 0 4.454 1.977 4.454 4.412v11.379z';
diff --git a/packages/twenty-cli/src/app/bundles/cover/generate-cover-image.ts b/packages/twenty-cli/src/app/bundles/cover/generate-cover-image.ts
new file mode 100644
index 00000000000..06c2bdf523b
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/generate-cover-image.ts
@@ -0,0 +1,74 @@
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import halftoneBackdropDataUri from './assets/halftone-backdrop.png?inline';
+
+import { TWENTY_LOGO_MARK_PATH } from '@/app/bundles/cover/assets/twenty-logo-mark-path';
+
+const CANVAS_WIDTH = 1388;
+const CANVAS_HEIGHT = 858;
+const TILE_SIZE = 156;
+const TILE_RADIUS = 16;
+const TILE_Y = 351;
+const LEFT_TILE_X = 434;
+const RIGHT_TILE_X = 798;
+const CENTER_X = CANVAS_WIDTH / 2;
+const CENTER_Y = CANVAS_HEIGHT / 2;
+const CROSS_ARM = 19;
+const CROSS_STROKE = 8;
+const CROSS_COLOR = '#b3b3b3';
+const TWENTY_MARK_VIEWBOX = 40;
+const TWENTY_MARK_SCALE = TILE_SIZE / TWENTY_MARK_VIEWBOX;
+
+type ImageProcessor = {
+ resize: (
+ width: number,
+ height: number,
+ options: { fit: 'cover'; position: 'centre' },
+ ) => ImageProcessor;
+ png: () => ImageProcessor;
+ toBuffer: () => Promise<Buffer>;
+};
+
+type GenerateCoverImageOptions = {
+ appPath: string;
+ logoBuffer: Buffer;
+};
+
+export const generateCoverImage = async ({
+ logoBuffer,
+ appPath,
+}: GenerateCoverImageOptions): Promise<Buffer> => {
+ const sharp: (input: Buffer) => ImageProcessor = createRequire(
+ join(appPath, 'package.json'),
+ )('sharp');
+ const logoPngBuffer = await sharp(logoBuffer)
+ .resize(TILE_SIZE, TILE_SIZE, { fit: 'cover', position: 'centre' })
+ .png()
+ .toBuffer();
+ const logoDataUri = `data:image/png;base64,${logoPngBuffer.toString('base64')}`;
+
+ const backdropDataUri = halftoneBackdropDataUri;
+
+ const svg = [
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${CANVAS_WIDTH}" height="${CANVAS_HEIGHT}" viewBox="0 0 ${CANVAS_WIDTH} ${CANVAS_HEIGHT}">`,
+ `<image href="${backdropDataUri}" x="0" y="0" width="${CANVAS_WIDTH}" height="${CANVAS_HEIGHT}" preserveAspectRatio="none" />`,
+ '<defs>',
+ '<filter id="tileShadow" x="-40%" y="-40%" width="180%" height="180%">',
+ '<feDropShadow dx="0" dy="6" stdDeviation="10" flood-color="#0b0b0f" flood-opacity="0.14" />',
+ '</filter>',
+ `<clipPath id="leftLogoClip"><rect x="${LEFT_TILE_X}" y="${TILE_Y}" width="${TILE_SIZE}" height="${TILE_SIZE}" rx="${TILE_RADIUS}" /></clipPath>`,
+ '</defs>',
+ '<g filter="url(#tileShadow)">',
+ `<rect x="${LEFT_TILE_X}" y="${TILE_Y}" width="${TILE_SIZE}" height="${TILE_SIZE}" rx="${TILE_RADIUS}" fill="#ffffff" />`,
+ `<rect x="${RIGHT_TILE_X}" y="${TILE_Y}" width="${TILE_SIZE}" height="${TILE_SIZE}" rx="${TILE_RADIUS}" fill="#000000" />`,
+ '</g>',
+ `<image href="${logoDataUri}" x="${LEFT_TILE_X}" y="${TILE_Y}" width="${TILE_SIZE}" height="${TILE_SIZE}" preserveAspectRatio="xMidYMid slice" clip-path="url(#leftLogoClip)" />`,
+ `<rect x="${LEFT_TILE_X}" y="${TILE_Y}" width="${TILE_SIZE}" height="${TILE_SIZE}" rx="${TILE_RADIUS}" fill="none" stroke="#000000" stroke-opacity="0.08" stroke-width="1" />`,
+ `<g transform="translate(${RIGHT_TILE_X} ${TILE_Y}) scale(${TWENTY_MARK_SCALE})"><path d="${TWENTY_LOGO_MARK_PATH}" fill="#ffffff" /></g>`,
+ `<line x1="${CENTER_X - CROSS_ARM}" y1="${CENTER_Y - CROSS_ARM}" x2="${CENTER_X + CROSS_ARM}" y2="${CENTER_Y + CROSS_ARM}" stroke="${CROSS_COLOR}" stroke-width="${CROSS_STROKE}" stroke-linecap="round" />`,
+ `<line x1="${CENTER_X - CROSS_ARM}" y1="${CENTER_Y + CROSS_ARM}" x2="${CENTER_X + CROSS_ARM}" y2="${CENTER_Y - CROSS_ARM}" stroke="${CROSS_COLOR}" stroke-width="${CROSS_STROKE}" stroke-linecap="round" />`,
+ '</svg>',
+ ].join('');
+
+ return sharp(Buffer.from(svg)).png().toBuffer();
+};
diff --git a/packages/twenty-cli/src/app/bundles/cover/generated-asset.type.ts b/packages/twenty-cli/src/app/bundles/cover/generated-asset.type.ts
new file mode 100644
index 00000000000..2222092a7e1
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/generated-asset.type.ts
@@ -0,0 +1,4 @@
+export type GeneratedAsset = {
+ relativePath: string;
+ content: Buffer;
+};
diff --git a/packages/twenty-cli/src/app/bundles/cover/generated-cover-path.ts b/packages/twenty-cli/src/app/bundles/cover/generated-cover-path.ts
new file mode 100644
index 00000000000..df63407d2a4
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/cover/generated-cover-path.ts
@@ -0,0 +1,3 @@
+import { ASSETS_DIR } from 'twenty-shared/application';
+
+export const GENERATED_COVER_PATH = `${ASSETS_DIR}/cover.generated.png`;
diff --git a/packages/twenty-cli/src/app/bundles/esbuild-one-shot-build.ts b/packages/twenty-cli/src/app/bundles/esbuild-one-shot-build.ts
new file mode 100644
index 00000000000..325a4c0dd86
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/esbuild-one-shot-build.ts
@@ -0,0 +1,54 @@
+import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';
+import { processEsbuildResult } from '@/app/bundles/esbuild-result-processor';
+import { type OnFileBuiltCallback } from '@/app/bundles/types/on-file-built-callback.type';
+import * as esbuild from 'esbuild';
+import path from 'path';
+import { type FileFolder } from 'twenty-shared/types';
+
+export type EsbuildOneShotBuildOptions = {
+ appPath: string;
+ sourcePaths: string[];
+ fileFolder: FileFolder;
+ buildOptions: esbuild.BuildOptions;
+ onFileBuilt: OnFileBuiltCallback;
+};
+
+export const esbuildOneShotBuild = async ({
+ appPath,
+ sourcePaths,
+ fileFolder,
+ buildOptions,
+ onFileBuilt,
+}: EsbuildOneShotBuildOptions): Promise<void> => {
+ if (sourcePaths.length === 0) {
+ return;
+ }
+
+ const entryPoints: Record<string, string> = {};
+
+ for (const sourcePath of sourcePaths) {
+ const entryName = sourcePath.replace(/\.tsx?$/, '');
+
+ if (Object.hasOwn(entryPoints, entryName)) {
+ throw new Error(
+ `Application sources ${path.relative(appPath, entryPoints[entryName])} and ${sourcePath} produce the same build output. Rename one of them.`,
+ );
+ }
+
+ entryPoints[entryName] = path.join(appPath, sourcePath);
+ }
+
+ const result = await esbuild.build({
+ ...buildOptions,
+ entryPoints,
+ plugins: [...getWatchInputPlugins(), ...(buildOptions.plugins ?? [])],
+ });
+
+ await processEsbuildResult({
+ result,
+ appPath,
+ fileFolder,
+ lastChecksums: new Map(),
+ onFileBuilt,
+ });
+};
diff --git a/packages/twenty-cli/src/app/bundles/esbuild-result-processor.ts b/packages/twenty-cli/src/app/bundles/esbuild-result-processor.ts
new file mode 100644
index 00000000000..de9d6e8b271
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/esbuild-result-processor.ts
@@ -0,0 +1,70 @@
+import { type OnFileBuiltCallback } from '@/app/bundles/types/on-file-built-callback.type';
+import crypto from 'crypto';
+import type * as esbuild from 'esbuild';
+import { readFile } from 'node:fs/promises';
+import path from 'path';
+import { FileFolder } from 'twenty-shared/types';
+
+const SDK_CLIENT_IMPORT_PREFIX = 'twenty-client-sdk';
+
+export type ProcessEsbuildResultParams = {
+ result: esbuild.BuildResult;
+ appPath: string;
+ fileFolder: FileFolder;
+ lastChecksums: Map<string, string>;
+ onFileBuilt?: OnFileBuiltCallback;
+};
+
+export const processEsbuildResult = async ({
+ result,
+ appPath,
+ fileFolder,
+ lastChecksums,
+ onFileBuilt,
+}: ProcessEsbuildResultParams) => {
+ const outputFiles = Object.keys(result.metafile?.outputs ?? {}).filter(
+ (file) => file.endsWith('.mjs'),
+ );
+
+ for (const outputFile of outputFiles) {
+ const absoluteBuiltFile = path.resolve(outputFile);
+ const relativeBuiltPath = path.relative(appPath, absoluteBuiltFile);
+ const absoluteSourcePath =
+ result.metafile?.outputs?.[outputFile]?.entryPoint || '';
+ const relativeSourcePath = path.relative(appPath, absoluteSourcePath);
+
+ const content = await readFile(absoluteBuiltFile);
+
+ const checksumAlgorithm =
+ fileFolder === FileFolder.BuiltFrontComponent ? 'sha256' : 'md5';
+ const checksum = crypto
+ .createHash(checksumAlgorithm)
+ .update(content)
+ .digest('hex');
+
+ const lastChecksum = lastChecksums.get(relativeBuiltPath);
+
+ if (lastChecksum === checksum) {
+ continue;
+ }
+
+ lastChecksums.set(relativeBuiltPath, checksum);
+
+ const outputMeta = result.metafile?.outputs?.[outputFile];
+ const usesSdkClient =
+ outputMeta?.imports?.some(
+ (imp) =>
+ imp.external === true &&
+ imp.path.startsWith(SDK_CLIENT_IMPORT_PREFIX),
+ ) ?? false;
+ if (onFileBuilt) {
+ await onFileBuilt({
+ fileFolder,
+ builtPath: relativeBuiltPath,
+ sourcePath: relativeSourcePath,
+ checksum,
+ usesSdkClient,
+ });
+ }
+ }
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/css-injection-plugin.spec.ts b/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/css-injection-plugin.spec.ts
new file mode 100644
index 00000000000..82757e3f2e8
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/css-injection-plugin.spec.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'path';
+
+import * as esbuild from 'esbuild';
+
+import { MINIMAL_APP_PATH } from '@/app/__tests__/utils/fixture-paths';
+import { getBaseFrontComponentBuildOptions } from '@/app/bundles/front-component-build/utils/get-base-front-component-build-options';
+
+describe('front-component build CSS injection', () => {
+ it('bundles relative CSS imports and assets into the injected style', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'css-assets-'));
+
+ try {
+ await writeFile(
+ join(appPath, 'main.js'),
+ "import './main.css'; export const text = `line one\n// keep this text\n/* and this text */`;",
+ );
+ await writeFile(
+ join(appPath, 'main.css'),
+ '@import "./nested.css"; .image { background: url("./icon.svg"); }',
+ );
+ await writeFile(
+ join(appPath, 'nested.css'),
+ '.nested { color: purple; }',
+ );
+ await writeFile(
+ join(appPath, 'icon.svg'),
+ '<svg xmlns="http://www.w3.org/2000/svg"/>',
+ );
+ const result = await esbuild.build({
+ ...getBaseFrontComponentBuildOptions(),
+ entryPoints: [join(appPath, 'main.js')],
+ write: false,
+ sourcemap: false,
+ });
+ const source = result.outputFiles[0].text;
+ const styles: { textContent?: string }[] = [];
+ const document = {
+ createElement: () => ({}),
+ head: {
+ appendChild: (style: { textContent?: string }) => styles.push(style),
+ },
+ };
+ const evaluated = new Function(
+ 'document',
+ source.replace(/export\s*\{[^}]*\};?\s*$/, ''),
+ );
+ evaluated(document);
+
+ expect(styles[0].textContent).toContain('.nested');
+ expect(styles[0].textContent).toContain('data:image/svg+xml');
+ expect(styles[0].textContent).not.toContain('@import');
+ expect(source).toContain('// keep this text');
+ expect(source).toContain('/* and this text */');
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ });
+
+ it('inlines an imported twenty-ui/style.css as a runtime document.head style injection', async () => {
+ const outputDir = await mkdtemp(join(tmpdir(), 'css-injection-'));
+
+ try {
+ await esbuild.build({
+ ...getBaseFrontComponentBuildOptions(),
+ entryPoints: [join(MINIMAL_APP_PATH, 'my.front-component.tsx')],
+ outdir: outputDir,
+ });
+
+ const output = await readFile(
+ join(outputDir, 'my.front-component.mjs'),
+ 'utf-8',
+ );
+
+ expect(output).toContain('document.createElement("style")');
+ expect(output).toContain('document.head.appendChild');
+ expect(output).toContain('box-sizing');
+ } finally {
+ await rm(outputDir, { recursive: true, force: true });
+ }
+ }, 30000);
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/preact-alias-plugin.spec.ts b/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/preact-alias-plugin.spec.ts
new file mode 100644
index 00000000000..1937958ca03
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/__tests__/preact-alias-plugin.spec.ts
@@ -0,0 +1,52 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as esbuild from 'esbuild';
+import { expect, it } from 'vitest';
+import { createPreactAliasPlugin } from '@/app/bundles/front-component-build/preact-alias-plugin';
+
+it('resolves react-dom/client against each importing workspace', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'preact-workspaces-'));
+ try {
+ for (const name of ['first', 'second']) {
+ const workspace = join(root, name);
+ await mkdir(join(workspace, 'node_modules/preact/compat'), {
+ recursive: true,
+ });
+ await writeFile(
+ join(workspace, 'node_modules/preact/package.json'),
+ JSON.stringify({
+ name: 'preact',
+ exports: { './compat/client': './compat/client.js' },
+ }),
+ );
+ await writeFile(
+ join(workspace, 'node_modules/preact/compat/client.js'),
+ `export const version = '${name}';`,
+ );
+ await writeFile(
+ join(workspace, 'index.js'),
+ "export { version } from 'react-dom/client';",
+ );
+ }
+ const outdir = join(root, 'out');
+ await esbuild.build({
+ entryPoints: [
+ join(root, 'first/index.js'),
+ join(root, 'second/index.js'),
+ ],
+ bundle: true,
+ format: 'esm',
+ outdir,
+ plugins: [createPreactAliasPlugin()],
+ });
+ expect(await readFile(join(outdir, 'first/index.js'), 'utf8')).toContain(
+ '"first"',
+ );
+ expect(await readFile(join(outdir, 'second/index.js'), 'utf8')).toContain(
+ '"second"',
+ );
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/constants/front-component-external-modules.ts b/packages/twenty-cli/src/app/bundles/front-component-build/constants/front-component-external-modules.ts
new file mode 100644
index 00000000000..6811916427d
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/constants/front-component-external-modules.ts
@@ -0,0 +1,7 @@
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from 'twenty-shared/application';
+
+export const FRONT_COMPONENT_EXTERNAL_MODULES: string[] = [
+ 'twenty-client-sdk/core',
+ 'twenty-client-sdk/metadata',
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,
+];
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/css-injection-plugin.ts b/packages/twenty-cli/src/app/bundles/front-component-build/css-injection-plugin.ts
new file mode 100644
index 00000000000..f00f226efea
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/css-injection-plugin.ts
@@ -0,0 +1,48 @@
+import * as esbuild from 'esbuild';
+import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';
+
+const buildStyleInjectionModule = (cssText: string): string =>
+ `if (typeof document !== 'undefined') {
+ const styleElement = document.createElement('style');
+ document.head.appendChild(styleElement);
+ styleElement.textContent = ${JSON.stringify(cssText)};
+}`;
+
+export const cssInjectionPlugin: esbuild.Plugin = {
+ name: 'css-injection',
+ setup: (build) => {
+ build.onLoad({ filter: /\.css$/, namespace: 'file' }, async ({ path }) => {
+ const result = await esbuild.build({
+ entryPoints: [path],
+ bundle: true,
+ write: false,
+ outfile: 'injected.css',
+ logLevel: 'silent',
+ plugins: getWatchInputPlugins(),
+ loader: Object.fromEntries(
+ [
+ '.png',
+ '.jpg',
+ '.jpeg',
+ '.gif',
+ '.svg',
+ '.webp',
+ '.avif',
+ '.ico',
+ '.woff',
+ '.woff2',
+ '.ttf',
+ '.eot',
+ '.otf',
+ ].map((extension) => [extension, 'dataurl']),
+ ),
+ });
+ const cssText = result.outputFiles[0].text;
+
+ return {
+ contents: buildStyleInjectionModule(cssText),
+ loader: 'js',
+ };
+ });
+ },
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/jsx-runtime-remote-wrapper-plugin.ts b/packages/twenty-cli/src/app/bundles/front-component-build/jsx-runtime-remote-wrapper-plugin.ts
new file mode 100644
index 00000000000..d5f6b41ad6c
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/jsx-runtime-remote-wrapper-plugin.ts
@@ -0,0 +1,283 @@
+import type * as esbuild from 'esbuild';
+
+const SHARED_HELPERS = `
+export var customElementMap = globalThis.__HTML_TAG_TO_CUSTOM_ELEMENT_TAG__ || {};
+
+var _injectedStyleKeys = {};
+
+export function injectStyleViaHead(cssText) {
+ if (!cssText) return;
+ var hash = 0;
+ for (var i = 0; i < cssText.length; i++) {
+ hash = ((hash << 5) - hash + cssText.charCodeAt(i)) | 0;
+ }
+ var key = 'jsx-style-' + hash;
+ if (_injectedStyleKeys[key]) return;
+ _injectedStyleKeys[key] = true;
+ var el = document.createElement('style');
+ el.setAttribute('data-jsx-style', key);
+ el.textContent = cssText;
+ document.head.appendChild(el);
+}
+
+export function extractCssText(children) {
+ if (typeof children === 'string') return children;
+ if (Array.isArray(children))
+ return children
+ .filter(function (c) { return typeof c === 'string'; })
+ .join('');
+ return '';
+}
+
+var _reactToDomEvent = {
+ ondoubleclick: 'ondblclick',
+};
+
+function _isEventProp(name) {
+ return (
+ name.length > 2 &&
+ name.charCodeAt(0) === 111 &&
+ name.charCodeAt(1) === 110 &&
+ name.charCodeAt(2) >= 65 &&
+ name.charCodeAt(2) <= 90
+ );
+}
+
+export function splitEventProps(props) {
+ if (!props) return { cleanProps: props, events: null };
+ var events = null;
+ var cleanProps = null;
+ for (var k in props) {
+ if (_isEventProp(k) && typeof props[k] === 'function') {
+ if (!events) {
+ events = {};
+ cleanProps = {};
+ for (var j in props) {
+ if (j === k) break;
+ cleanProps[j] = props[j];
+ }
+ }
+ events[k] = props[k];
+ } else if (events) {
+ cleanProps[k] = props[k];
+ }
+ }
+ return { cleanProps: cleanProps || props, events: events };
+}
+
+export function makeEventRef(events, userRef) {
+ return function(el) {
+ if (el) {
+ for (var name in events) {
+ var domName = _reactToDomEvent[name.toLowerCase()] || name.toLowerCase();
+ el[domName] = events[name];
+ }
+ }
+ if (typeof userRef === 'function') userRef(el);
+ else if (userRef != null && typeof userRef === 'object') userRef.current = el;
+ };
+}
+`.trim();
+
+const JSX_RUNTIME_WRAPPER = `
+import {
+ jsx as _originalJsx,
+ jsxs as _originalJsxs,
+ Fragment,
+} from '__real_react_jsx_runtime__';
+
+import {
+ customElementMap,
+ injectStyleViaHead,
+ extractCssText,
+ splitEventProps,
+ makeEventRef,
+} from '__jsx_shared_helpers__';
+
+function _wrapJsxFactory(originalFactory) {
+ return function wrappedJsx(type, props, key) {
+ if (typeof type === 'string') {
+ if (type === 'style') {
+ var css =
+ props && props.dangerouslySetInnerHTML
+ ? props.dangerouslySetInnerHTML.__html || ''
+ : extractCssText(props && props.children);
+ injectStyleViaHead(css);
+ return null;
+ }
+
+ var customTag = customElementMap[type];
+ if (customTag) {
+ var split = splitEventProps(props);
+ if (split.events) {
+ var cp = split.cleanProps;
+ cp.ref = makeEventRef(split.events, cp.ref);
+ return originalFactory(customTag, cp, key);
+ }
+ return originalFactory(customTag, props, key);
+ }
+ }
+ return originalFactory(type, props, key);
+ };
+}
+
+export var jsx = _wrapJsxFactory(_originalJsx);
+export var jsxs = _wrapJsxFactory(_originalJsxs);
+export { Fragment };
+`.trim();
+
+const REACT_WRAPPER = `
+export * from '__real_react__';
+import _React from '__real_react__';
+
+import {
+ customElementMap,
+ injectStyleViaHead,
+ extractCssText,
+ splitEventProps,
+ makeEventRef,
+} from '__jsx_shared_helpers__';
+
+var _originalCreateElement = _React.createElement;
+
+function createElement(type) {
+ var args = arguments;
+ if (typeof type === 'string') {
+ if (type === 'style') {
+ var props = args.length > 1 ? args[1] : null;
+ if (props) {
+ var css = props.dangerouslySetInnerHTML
+ ? props.dangerouslySetInnerHTML.__html || ''
+ : extractCssText(props.children);
+ injectStyleViaHead(css);
+ }
+ return null;
+ }
+
+ var customTag = customElementMap[type];
+ if (customTag) {
+ var ceProps = args.length > 1 ? args[1] : null;
+ var split = splitEventProps(ceProps);
+ if (split.events) {
+ var cp = split.cleanProps || {};
+ cp.ref = makeEventRef(split.events, cp.ref);
+ var newArgs = [customTag, cp];
+ for (var i = 2; i < args.length; i++) newArgs.push(args[i]);
+ return _originalCreateElement.apply(null, newArgs);
+ }
+ var newArgs2 = [customTag];
+ for (var i2 = 1; i2 < args.length; i2++) newArgs2.push(args[i2]);
+ return _originalCreateElement.apply(null, newArgs2);
+ }
+ }
+ return _originalCreateElement.apply(null, args);
+}
+
+export { createElement };
+export default Object.assign({}, _React, { createElement: createElement });
+`.trim();
+
+type JsxRuntimeRemoteWrapperPluginOptions = {
+ usePreact?: boolean;
+};
+
+export const createJsxRuntimeRemoteWrapperPlugin = (
+ options?: JsxRuntimeRemoteWrapperPluginOptions,
+): esbuild.Plugin => {
+ const usePreact = options?.usePreact ?? false;
+
+ const jsxRuntimeModule = usePreact
+ ? 'preact/jsx-runtime'
+ : 'react/jsx-runtime';
+ const reactModule = usePreact ? 'preact/compat' : 'react';
+
+ return {
+ name: 'jsx-runtime-remote-wrapper',
+ setup: (build) => {
+ let realJsxRuntimePath: string | undefined;
+ let realReactPath: string | undefined;
+
+ build.onResolve({ filter: /^__jsx_shared_helpers__$/ }, () => ({
+ path: '__jsx_shared_helpers__',
+ namespace: 'jsx-shared-helpers',
+ }));
+
+ build.onLoad({ filter: /.*/, namespace: 'jsx-shared-helpers' }, () => ({
+ contents: SHARED_HELPERS,
+ loader: 'js' as const,
+ }));
+
+ build.onResolve({ filter: /^react\/jsx-runtime$/ }, async (args) => {
+ if (args.pluginData?.skipJsxWrapper) {
+ return undefined;
+ }
+
+ if (!realJsxRuntimePath) {
+ const resolved = await build.resolve(jsxRuntimeModule, {
+ kind: args.kind,
+ resolveDir: args.resolveDir,
+ pluginData: { skipJsxWrapper: true },
+ });
+
+ realJsxRuntimePath = resolved.path;
+ }
+
+ return {
+ path: 'react/jsx-runtime',
+ namespace: 'jsx-runtime-wrapper',
+ };
+ });
+
+ build.onResolve({ filter: /^__real_react_jsx_runtime__$/ }, () => {
+ if (!realJsxRuntimePath) {
+ throw new Error(
+ 'jsx-runtime-remote-wrapper: real jsx-runtime path not resolved yet',
+ );
+ }
+
+ return { path: realJsxRuntimePath };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'jsx-runtime-wrapper' }, () => ({
+ contents: JSX_RUNTIME_WRAPPER,
+ loader: 'js' as const,
+ }));
+
+ build.onResolve({ filter: /^react$/ }, async (args) => {
+ if (args.pluginData?.skipJsxWrapper) {
+ return undefined;
+ }
+
+ if (!realReactPath) {
+ const resolved = await build.resolve(reactModule, {
+ kind: args.kind,
+ resolveDir: args.resolveDir,
+ pluginData: { skipJsxWrapper: true },
+ });
+
+ realReactPath = resolved.path;
+ }
+
+ return {
+ path: 'react',
+ namespace: 'react-wrapper',
+ };
+ });
+
+ build.onResolve({ filter: /^__real_react__$/ }, () => {
+ if (!realReactPath) {
+ throw new Error(
+ 'jsx-runtime-remote-wrapper: real react path not resolved yet',
+ );
+ }
+
+ return { path: realReactPath };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'react-wrapper' }, () => ({
+ contents: REACT_WRAPPER,
+ loader: 'js' as const,
+ }));
+ },
+ };
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/jsx-transform-to-remote-dom-worker-format-plugin.ts b/packages/twenty-cli/src/app/bundles/front-component-build/jsx-transform-to-remote-dom-worker-format-plugin.ts
new file mode 100644
index 00000000000..3e6dcb07e75
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/jsx-transform-to-remote-dom-worker-format-plugin.ts
@@ -0,0 +1,33 @@
+import type * as esbuild from 'esbuild';
+import { readFile } from 'node:fs/promises';
+
+import { unwrapDefineFrontComponentToDirectExport } from './utils/unwrap-define-front-component-to-direct-export';
+
+export const jsxTransformToRemoteDomWorkerFormatPlugin: esbuild.Plugin = {
+ name: 'jsx-transform-to-remote-dom-worker-format-plugin',
+ setup: (esbuildBuild) => {
+ esbuildBuild.onLoad(
+ { filter: /\.tsx$/ },
+ async ({ path }): Promise<esbuild.OnLoadResult> => {
+ try {
+ const frontComponentSourceCode = await readFile(path, 'utf8');
+
+ const transformedContents = unwrapDefineFrontComponentToDirectExport(
+ frontComponentSourceCode,
+ );
+
+ return { contents: transformedContents, loader: 'tsx' };
+ } catch (transformError) {
+ return {
+ errors: [
+ {
+ text: `Failed to transform front component: ${transformError instanceof Error ? transformError.message : String(transformError)}`,
+ location: { file: path },
+ },
+ ],
+ };
+ }
+ },
+ );
+ },
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/preact-alias-plugin.ts b/packages/twenty-cli/src/app/bundles/front-component-build/preact-alias-plugin.ts
new file mode 100644
index 00000000000..3f4405d9fdc
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/preact-alias-plugin.ts
@@ -0,0 +1,22 @@
+import type * as esbuild from 'esbuild';
+
+export const createPreactAliasPlugin = (): esbuild.Plugin => ({
+ name: 'preact-alias',
+ setup: (build) => {
+ build.onResolve({ filter: /^react-dom\/client$/ }, async (args) => {
+ return build.resolve('preact/compat/client', {
+ kind: args.kind,
+ resolveDir: args.resolveDir,
+ });
+ });
+
+ build.onResolve({ filter: /^react-dom$/ }, async (args) => {
+ const resolved = await build.resolve('preact/compat', {
+ kind: args.kind,
+ resolveDir: args.resolveDir,
+ });
+
+ return { path: resolved.path };
+ });
+ },
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/__tests__/enumerate-shared-dependencies-export-names.spec.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/__tests__/enumerate-shared-dependencies-export-names.spec.ts
new file mode 100644
index 00000000000..1bbcfa87524
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/__tests__/enumerate-shared-dependencies-export-names.spec.ts
@@ -0,0 +1,173 @@
+import { mkdtemp, writeFile, rm, symlink, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import * as esbuild from 'esbuild';
+import { getSharedDependenciesEntrySource } from '../utils/get-shared-dependencies-entry-source';
+import { getSharedDependenciesShimSource } from '../utils/get-shared-dependencies-shim-source';
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from 'twenty-shared/application';
+import { describe, expect, it } from 'vitest';
+
+import { MINIMAL_APP_PATH } from '@/app/__tests__/utils/fixture-paths';
+import { enumerateSharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names';
+
+describe('enumerateSharedDependenciesExportNames', () => {
+ it('discovers browser-only exports without evaluating the dependency', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'browser-dependency-'));
+
+ try {
+ await writeFile(
+ join(appPath, 'browser.mjs'),
+ "export const element = document.createElement('div'); export default window.location;",
+ );
+ expect(
+ await enumerateSharedDependenciesExportNames({
+ appPath,
+ specifier: './browser.mjs',
+ }),
+ ).toEqual({ namedExports: ['element'], hasDefaultExport: true });
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ });
+
+ it.each(['react', 'react/jsx-runtime'])(
+ 'discovers re-exports of %s without treating virtual modules as files',
+ async (dependency) => {
+ const appPath = await mkdtemp(join(tmpdir(), 'react-reexport-'));
+ try {
+ await symlink(
+ join(MINIMAL_APP_PATH, '../../../../node_modules'),
+ join(appPath, 'node_modules'),
+ );
+ await writeFile(
+ join(appPath, 'exports.mjs'),
+ `export * from '${dependency}';`,
+ );
+ const exports = await enumerateSharedDependenciesExportNames({
+ appPath,
+ specifier: './exports.mjs',
+ });
+ expect(exports.namedExports).toContain(
+ dependency === 'react' ? 'useState' : 'jsx',
+ );
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it('evaluates a shared dependency imported only for side effects', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'shared-side-effect-'));
+ const specifier = './effect.mjs';
+ try {
+ const markerPath = join(appPath, 'loaded.txt');
+ await writeFile(
+ join(appPath, specifier),
+ `import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(markerPath)}, 'loaded');`,
+ );
+ const names = { namedExports: [], hasDefaultExport: false };
+ const bundlePath = join(appPath, 'shared.mjs');
+ await esbuild.build({
+ stdin: {
+ contents: getSharedDependenciesEntrySource(
+ new Map([[specifier, names]]),
+ ),
+ resolveDir: appPath,
+ },
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ outfile: bundlePath,
+ });
+ const shim = getSharedDependenciesShimSource({
+ specifier,
+ exportNames: names,
+ }).replaceAll(
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,
+ pathToFileURL(bundlePath).href,
+ );
+ await import(
+ `data:text/javascript;base64,${Buffer.from(shim).toString('base64')}`
+ );
+ expect(await readFile(markerPath, 'utf8')).toBe('loaded');
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ });
+
+ it('preserves live bindings through the built shared bundle and component shim', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'shared-binding-'));
+ const specifier = './counter.mjs';
+
+ try {
+ await writeFile(
+ join(appPath, specifier),
+ 'export let count = 0; export const increment = () => count++;',
+ );
+ const names = await enumerateSharedDependenciesExportNames({
+ appPath,
+ specifier,
+ });
+ const bundlePath = join(appPath, 'shared.mjs');
+
+ await esbuild.build({
+ stdin: {
+ contents: getSharedDependenciesEntrySource(
+ new Map([[specifier, names]]),
+ ),
+ resolveDir: appPath,
+ },
+ bundle: true,
+ format: 'esm',
+ outfile: bundlePath,
+ });
+ const shim = getSharedDependenciesShimSource({
+ specifier,
+ exportNames: names,
+ }).replaceAll(
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,
+ pathToFileURL(bundlePath).href,
+ );
+ const module = await import(
+ `data:text/javascript;base64,${Buffer.from(shim).toString('base64')}`
+ );
+
+ expect(module.count).toBe(0);
+ module.increment();
+ expect(module.count).toBe(1);
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ });
+
+ it('reports the named exports and the default of a commonjs dependency', async () => {
+ const exportNames = await enumerateSharedDependenciesExportNames({
+ appPath: MINIMAL_APP_PATH,
+ specifier: 'react',
+ });
+
+ expect(exportNames.namedExports).toContain('useState');
+ expect(exportNames.namedExports).not.toContain('default');
+ expect(exportNames.hasDefaultExport).toBe(true);
+ }, 60000);
+
+ it('reports no default for an es module without one', async () => {
+ const exportNames = await enumerateSharedDependenciesExportNames({
+ appPath: MINIMAL_APP_PATH,
+ specifier: '@remote-dom/core',
+ });
+
+ expect(exportNames.namedExports).toContain('ROOT_ID');
+ expect(exportNames.hasDefaultExport).toBe(false);
+ }, 60000);
+
+ it('throws for a dependency the application cannot resolve', async () => {
+ await expect(
+ enumerateSharedDependenciesExportNames({
+ appPath: MINIMAL_APP_PATH,
+ specifier: 'this-package-does-not-exist',
+ }),
+ ).rejects.toThrow('Unable to determine the exports');
+ }, 60000);
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/build-shared-dependencies-bundle.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/build-shared-dependencies-bundle.ts
new file mode 100644
index 00000000000..547df97ed45
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/build-shared-dependencies-bundle.ts
@@ -0,0 +1,91 @@
+import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';
+import { getBaseFrontComponentBuildOptions } from '@/app/bundles/front-component-build/utils/get-base-front-component-build-options';
+import { type OnFileBuiltCallback } from '@/app/bundles/types/on-file-built-callback.type';
+import { type SharedDependenciesBuildContext } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type';
+import { enumerateSharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names';
+import { getSharedDependenciesEntrySource } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-entry-source';
+import { getSharedDependenciesNamespaceCollisions } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-namespace-collisions';
+import { ensureDir } from '@/app/fs-utils';
+import crypto from 'crypto';
+import * as esbuild from 'esbuild';
+import { readFile } from 'node:fs/promises';
+import { dirname, join } from 'path';
+import {
+ OUTPUT_DIR,
+ type FrontComponentSharedDependenciesManifest,
+} from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isNonEmptyArray } from '@sniptt/guards';
+
+export const buildSharedDependenciesBundle = async ({
+ appPath,
+ sharedDependencies,
+ outputDir = OUTPUT_DIR,
+ onFileBuilt,
+}: {
+ appPath: string;
+ outputDir?: string;
+ sharedDependencies: FrontComponentSharedDependenciesManifest;
+ onFileBuilt: OnFileBuiltCallback;
+}): Promise<SharedDependenciesBuildContext> => {
+ const namespaceCollisions = getSharedDependenciesNamespaceCollisions(
+ sharedDependencies.dependencies,
+ );
+
+ if (isNonEmptyArray(namespaceCollisions)) {
+ throw new Error(
+ `Shared dependencies map to the same bundle namespace: ${namespaceCollisions
+ .map((specifiers) => specifiers.join(' and '))
+ .join(', ')}`,
+ );
+ }
+
+ const exportNamesBySpecifier = new Map(
+ await Promise.all(
+ sharedDependencies.dependencies.map(
+ async (specifier) =>
+ [
+ specifier,
+ await enumerateSharedDependenciesExportNames({
+ appPath,
+ specifier,
+ }),
+ ] as const,
+ ),
+ ),
+ );
+
+ const builtPath = join(outputDir, sharedDependencies.builtPath);
+ const absoluteBuiltPath = join(appPath, builtPath);
+
+ await ensureDir(dirname(absoluteBuiltPath));
+
+ await esbuild.build({
+ ...getBaseFrontComponentBuildOptions(),
+ plugins: [
+ ...getWatchInputPlugins(),
+ ...(getBaseFrontComponentBuildOptions().plugins ?? []),
+ ],
+ stdin: {
+ contents: getSharedDependenciesEntrySource(exportNamesBySpecifier),
+ resolveDir: appPath,
+ sourcefile: 'twenty-shared-dependencies-entry.js',
+ loader: 'js',
+ },
+ outfile: absoluteBuiltPath,
+ outExtension: undefined,
+ external: [],
+ });
+
+ const content = await readFile(absoluteBuiltPath);
+ const checksum = crypto.createHash('sha256').update(content).digest('hex');
+
+ await onFileBuilt({
+ fileFolder: FileFolder.BuiltFrontComponent,
+ builtPath,
+ sourcePath: 'package.json',
+ checksum,
+ });
+
+ return { exportNamesBySpecifier };
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/create-shared-dependencies-shim-plugin.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/create-shared-dependencies-shim-plugin.ts
new file mode 100644
index 00000000000..cf5dff1376f
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/create-shared-dependencies-shim-plugin.ts
@@ -0,0 +1,49 @@
+import { type SharedDependenciesBuildContext } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type';
+import { getSharedDependenciesShimSource } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-shim-source';
+import type * as esbuild from 'esbuild';
+import { isDefined } from 'twenty-shared/utils';
+
+const SHARED_DEPENDENCIES_SHIM_NAMESPACE = 'twenty-shared-dependencies-shim';
+
+export const createSharedDependenciesShimPlugin = (
+ getSharedDependenciesBuildContext: () => SharedDependenciesBuildContext | null,
+): esbuild.Plugin => ({
+ name: 'twenty-shared-dependencies-shim',
+ setup: (build) => {
+ build.onResolve({ filter: /.*/ }, ({ path: specifier }) => {
+ const sharedDependenciesBuildContext =
+ getSharedDependenciesBuildContext();
+
+ if (!isDefined(sharedDependenciesBuildContext)) {
+ return undefined;
+ }
+
+ if (
+ !sharedDependenciesBuildContext.exportNamesBySpecifier.has(specifier)
+ ) {
+ return undefined;
+ }
+
+ return { path: specifier, namespace: SHARED_DEPENDENCIES_SHIM_NAMESPACE };
+ });
+
+ build.onLoad(
+ { filter: /.*/, namespace: SHARED_DEPENDENCIES_SHIM_NAMESPACE },
+ ({ path: specifier }) => {
+ const exportNames =
+ getSharedDependenciesBuildContext()?.exportNamesBySpecifier.get(
+ specifier,
+ );
+
+ if (!isDefined(exportNames)) {
+ return undefined;
+ }
+
+ return {
+ contents: getSharedDependenciesShimSource({ specifier, exportNames }),
+ loader: 'js' as const,
+ };
+ },
+ );
+ },
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type.ts
new file mode 100644
index 00000000000..af7c97c295d
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type.ts
@@ -0,0 +1,5 @@
+import { type SharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type';
+
+export type SharedDependenciesBuildContext = {
+ exportNamesBySpecifier: Map<string, SharedDependenciesExportNames>;
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type.ts
new file mode 100644
index 00000000000..ece061905cc
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type.ts
@@ -0,0 +1,4 @@
+export type SharedDependenciesExportNames = {
+ namedExports: string[];
+ hasDefaultExport: boolean;
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts
new file mode 100644
index 00000000000..da9ee4206af
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts
@@ -0,0 +1,111 @@
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { init, parse } from 'cjs-module-lexer';
+import * as esbuild from 'esbuild';
+import ts from 'typescript';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';
+import { getBaseFrontComponentBuildOptions } from '@/app/bundles/front-component-build/utils/get-base-front-component-build-options';
+import { type SharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type';
+
+export const enumerateSharedDependenciesExportNames = async ({
+ appPath,
+ specifier,
+}: {
+ appPath: string;
+ specifier: string;
+}): Promise<SharedDependenciesExportNames> => {
+ try {
+ const options = getBaseFrontComponentBuildOptions();
+ const isWrappedJsxRuntime = specifier === 'react/jsx-runtime';
+ const result = await esbuild.build({
+ ...options,
+ absWorkingDir: appPath,
+ plugins: [
+ ...getWatchInputPlugins(),
+ ...(options.plugins ?? []).filter(
+ (plugin) =>
+ isWrappedJsxRuntime || plugin.name !== 'jsx-runtime-remote-wrapper',
+ ),
+ ],
+ entryPoints: [specifier],
+ write: false,
+ outfile: 'shared-dependency-probe.js',
+ outExtension: undefined,
+ external: [],
+ sourcemap: false,
+ metafile: true,
+ });
+ const output = Object.values(result.metafile.outputs).find((entry) =>
+ isDefined(entry.entryPoint),
+ );
+
+ if (!isDefined(output?.entryPoint))
+ throw new Error('Missing dependency entry point.');
+
+ const exports = new Set(output.exports);
+ const visited = new Set<string>();
+ const collectReexportedNames = async (path: string): Promise<void> => {
+ if (visited.has(path)) return;
+ visited.add(path);
+
+ const input = result.metafile.inputs[path];
+
+ if (!isDefined(input)) return;
+ const source = await readFile(resolve(appPath, path), 'utf8');
+ let reexports: string[];
+
+ if (input.format === 'cjs') {
+ await init();
+ const transformed = await esbuild.transform(source, {
+ define: options.define,
+ minifySyntax: true,
+ loader: 'js',
+ });
+ const parsed = parse(transformed.code);
+
+ for (const name of parsed.exports) {
+ if (name !== '__esModule') exports.add(name);
+ }
+ reexports = parsed.reexports;
+ } else {
+ const sourceFile = ts.createSourceFile(
+ path,
+ source,
+ ts.ScriptTarget.Latest,
+ );
+ reexports = sourceFile.statements.flatMap((statement) =>
+ ts.isExportDeclaration(statement) &&
+ !isDefined(statement.exportClause) &&
+ isDefined(statement.moduleSpecifier) &&
+ ts.isStringLiteral(statement.moduleSpecifier)
+ ? [statement.moduleSpecifier.text]
+ : [],
+ );
+ }
+
+ for (const reexport of reexports) {
+ const imported = input.imports.find(
+ (entry) => entry.original === reexport && !entry.external,
+ );
+
+ if (isDefined(imported)) await collectReexportedNames(imported.path);
+ }
+ };
+
+ // The virtual JSX wrapper declares all of its exports in the build metadata.
+ if (!isWrappedJsxRuntime) await collectReexportedNames(output.entryPoint);
+
+ return {
+ namedExports: [...exports].filter((name) => name !== 'default').sort(),
+ hasDefaultExport: exports.has('default'),
+ };
+ } catch (cause) {
+ throw new Error(
+ `Unable to determine the exports of shared dependency "${specifier}". Check that it is installed and importable from the application.`,
+ { cause },
+ );
+ }
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-entry-source.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-entry-source.ts
new file mode 100644
index 00000000000..f853989b96a
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-entry-source.ts
@@ -0,0 +1,24 @@
+import { type SharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type';
+import { toSharedDependenciesNamespaceIdentifier } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier';
+
+export const getSharedDependenciesEntrySource = (
+ exportNamesBySpecifier: Map<string, SharedDependenciesExportNames>,
+): string =>
+ [...exportNamesBySpecifier]
+ .map(([specifier, exportNames]) => {
+ const namespaceIdentifier =
+ toSharedDependenciesNamespaceIdentifier(specifier);
+ const names = [
+ ...exportNames.namedExports,
+ ...(exportNames.hasDefaultExport ? ['default'] : []),
+ ];
+
+ return [
+ `export * as ${namespaceIdentifier} from ${JSON.stringify(specifier)};`,
+ ...names.map(
+ (name, index) =>
+ `export { ${JSON.stringify(name)} as ${namespaceIdentifier}_${index} } from ${JSON.stringify(specifier)};`,
+ ),
+ ].join('\n');
+ })
+ .join('\n');
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-namespace-collisions.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-namespace-collisions.ts
new file mode 100644
index 00000000000..675e4823f27
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-namespace-collisions.ts
@@ -0,0 +1,21 @@
+import { toSharedDependenciesNamespaceIdentifier } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier';
+
+export const getSharedDependenciesNamespaceCollisions = (
+ dependencies: string[],
+): string[][] => {
+ const specifiersByNamespaceIdentifier = new Map<string, string[]>();
+
+ for (const specifier of dependencies) {
+ const namespaceIdentifier =
+ toSharedDependenciesNamespaceIdentifier(specifier);
+ const specifiers =
+ specifiersByNamespaceIdentifier.get(namespaceIdentifier) ?? [];
+
+ specifiers.push(specifier);
+ specifiersByNamespaceIdentifier.set(namespaceIdentifier, specifiers);
+ }
+
+ return [...specifiersByNamespaceIdentifier.values()].filter(
+ (specifiers) => specifiers.length > 1,
+ );
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-shim-source.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-shim-source.ts
new file mode 100644
index 00000000000..e1ba81986fb
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/get-shared-dependencies-shim-source.ts
@@ -0,0 +1,29 @@
+import { type SharedDependenciesExportNames } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-export-names.type';
+import { toSharedDependenciesNamespaceIdentifier } from '@/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier';
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from 'twenty-shared/application';
+
+export const getSharedDependenciesShimSource = ({
+ specifier,
+ exportNames,
+}: {
+ specifier: string;
+ exportNames: SharedDependenciesExportNames;
+}): string => {
+ const namespaceIdentifier =
+ toSharedDependenciesNamespaceIdentifier(specifier);
+ const names = [
+ ...exportNames.namedExports,
+ ...(exportNames.hasDefaultExport ? ['default'] : []),
+ ];
+
+ if (names.length === 0) {
+ return `import ${JSON.stringify(FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER)};`;
+ }
+
+ return names
+ .map(
+ (name, index) =>
+ `export { ${namespaceIdentifier}_${index} as ${JSON.stringify(name)} } from ${JSON.stringify(FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER)};`,
+ )
+ .join('\n');
+};
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier.ts
new file mode 100644
index 00000000000..055d6f064ec
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/to-shared-dependencies-namespace-identifier.ts
@@ -0,0 +1,4 @@
+export const toSharedDependenciesNamespaceIdentifier = (
+ specifier: string,
+): string =>
+ `__shared_dependencies_${specifier.replace(/[^A-Za-z0-9]/g, '_')}__`;
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/utils/__tests__/unwrap-define-front-component-to-direct-export.spec.ts b/packages/twenty-cli/src/app/bundles/front-component-build/utils/__tests__/unwrap-define-front-component-to-direct-export.spec.ts
new file mode 100644
index 00000000000..88b5922414e
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/utils/__tests__/unwrap-define-front-component-to-direct-export.spec.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it } from 'vitest';
+
+import { unwrapDefineFrontComponentToDirectExport } from '@/app/bundles/front-component-build/utils/unwrap-define-front-component-to-direct-export';
+
+const INLINE_EXPRESSION_COMPONENT_SOURCE = `import { defineFrontComponent } from 'twenty-sdk/define';
+
+import { SUMMARIZE_COMPANY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { createSummarizeRecordEffect } from 'src/front-components/utils/create-summarize-record-effect';
+import { SUMMARIZE_TARGETS } from 'src/front-components/utils/summarize-target';
+
+const SummarizeRecordEffect = createSummarizeRecordEffect(SUMMARIZE_TARGETS.company)
+
+export default defineFrontComponent({
+ universalIdentifier: SUMMARIZE_COMPANY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ name: 'Summarize Company',
+ description: 'Asks AI to summarize the selected company',
+ isHeadless: true,
+ component: createSummarizeRecordEffect(SUMMARIZE_TARGETS.company),
+});
+`;
+
+const IDENTIFIER_COMPONENT_SOURCE = `import { defineFrontComponent } from 'twenty-sdk/define';
+
+import { SUMMARIZE_COMPANY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { createSummarizeRecordEffect } from 'src/front-components/utils/create-summarize-record-effect';
+import { SUMMARIZE_TARGETS } from 'src/front-components/utils/summarize-target';
+
+const SummarizeRecordEffect = createSummarizeRecordEffect(SUMMARIZE_TARGETS.company)
+
+export default defineFrontComponent({
+ universalIdentifier: SUMMARIZE_COMPANY_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ name: 'Summarize Company',
+ description: 'Asks AI to summarize the selected company',
+ isHeadless: true,
+ component: SummarizeRecordEffect,
+});
+`;
+
+const SETTINGS_COMPONENT_SOURCE = `import { defineSettingsFrontComponent } from 'twenty-sdk/define';
+
+import { APP_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { AppSettings } from 'src/front-components/components/AppSettings';
+
+export default defineSettingsFrontComponent({
+ universalIdentifier: APP_SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,
+ name: 'app-settings',
+ description: 'Custom settings tab',
+ component: AppSettings,
+});
+`;
+
+describe('unwrapDefineFrontComponentToDirectExport', () => {
+ it('renders the component when component is an inline factory call', () => {
+ const output = unwrapDefineFrontComponentToDirectExport(
+ INLINE_EXPRESSION_COMPONENT_SOURCE,
+ );
+
+ expect(output).toContain(
+ 'component: createSummarizeRecordEffect(SUMMARIZE_TARGETS.company),',
+ );
+ expect(output).toContain(
+ '__frontComponentJsx(__frontComponentDefinition.component, {})',
+ );
+ expect(output).not.toContain('defineFrontComponent');
+ });
+
+ it('renders the component when component is a bare identifier', () => {
+ const output = unwrapDefineFrontComponentToDirectExport(
+ IDENTIFIER_COMPONENT_SOURCE,
+ );
+
+ expect(output).toContain('component: SummarizeRecordEffect,');
+ expect(output).toContain(
+ '__frontComponentJsx(__frontComponentDefinition.component, {})',
+ );
+ expect(output).not.toContain('defineFrontComponent');
+ });
+
+ it('produces an equivalent renderer for the inline and identifier forms', () => {
+ const inlineOutput = unwrapDefineFrontComponentToDirectExport(
+ INLINE_EXPRESSION_COMPONENT_SOURCE,
+ );
+ const identifierOutput = unwrapDefineFrontComponentToDirectExport(
+ IDENTIFIER_COMPONENT_SOURCE,
+ );
+
+ const renderer =
+ '\nexport default function __renderFrontComponent(__container) { __createRoot(__container).render(__frontComponentJsx(__frontComponentDefinition.component, {})); }\n';
+
+ expect(inlineOutput).toContain(renderer);
+ expect(identifierOutput).toContain(renderer);
+ });
+
+ it('renders the component when defined with defineSettingsFrontComponent', () => {
+ const output = unwrapDefineFrontComponentToDirectExport(
+ SETTINGS_COMPONENT_SOURCE,
+ );
+
+ expect(output).toContain('component: AppSettings,');
+ expect(output).toContain(
+ '__frontComponentJsx(__frontComponentDefinition.component, {})',
+ );
+ expect(output).not.toContain('defineSettingsFrontComponent');
+ });
+
+ it('leaves a source without a defineFrontComponent default export untouched', () => {
+ const source = `import { useEffect } from 'react';
+
+export const createSummarizeRecordEffect = () => () => null;
+`;
+
+ expect(unwrapDefineFrontComponentToDirectExport(source)).toBe(source);
+ });
+ it('keeps imports used by a non-default definition', () => {
+ const source =
+ "import { defineFrontComponent } from 'twenty-sdk/define';\nexport const definition = defineFrontComponent({ component: () => null });";
+ expect(unwrapDefineFrontComponentToDirectExport(source)).toBe(source);
+ });
+
+ it('unwraps a multiline import with a trailing comma', () => {
+ const source = IDENTIFIER_COMPONENT_SOURCE.replace(
+ 'import { defineFrontComponent }',
+ 'import {\n defineFrontComponent,\n}',
+ );
+ const output = unwrapDefineFrontComponentToDirectExport(source);
+
+ expect(output).not.toContain('defineFrontComponent');
+ expect(output).toContain('__frontComponentDefinition.component');
+ });
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-base-front-component-build-options.ts b/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-base-front-component-build-options.ts
new file mode 100644
index 00000000000..9a5f9976d7b
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-base-front-component-build-options.ts
@@ -0,0 +1,19 @@
+import type * as esbuild from 'esbuild';
+
+import { FRONT_COMPONENT_EXTERNAL_MODULES } from '../constants/front-component-external-modules';
+import { getFrontComponentBuildPlugins } from './get-front-component-build-plugins';
+
+export const getBaseFrontComponentBuildOptions = (): esbuild.BuildOptions => ({
+ bundle: true,
+ splitting: false,
+ format: 'esm',
+ outExtension: { '.js': '.mjs' },
+ external: FRONT_COMPONENT_EXTERNAL_MODULES,
+ jsx: 'automatic',
+ sourcemap: true,
+ metafile: true,
+ logLevel: 'silent',
+ minify: true,
+ define: { 'process.env.NODE_ENV': '"production"' },
+ plugins: [...getFrontComponentBuildPlugins()],
+});
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-front-component-build-plugins.ts b/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-front-component-build-plugins.ts
new file mode 100644
index 00000000000..f42e4df31ce
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/utils/get-front-component-build-plugins.ts
@@ -0,0 +1,32 @@
+import type * as esbuild from 'esbuild';
+import { isDefined } from 'twenty-shared/utils';
+
+import { createSharedDependenciesShimPlugin } from '@/app/bundles/front-component-build/shared-dependencies-build/create-shared-dependencies-shim-plugin';
+import { type SharedDependenciesBuildContext } from '@/app/bundles/front-component-build/shared-dependencies-build/types/shared-dependencies-build-context.type';
+import { cssInjectionPlugin } from '../css-injection-plugin';
+import { createJsxRuntimeRemoteWrapperPlugin } from '../jsx-runtime-remote-wrapper-plugin';
+import { jsxTransformToRemoteDomWorkerFormatPlugin } from '../jsx-transform-to-remote-dom-worker-format-plugin';
+import { createPreactAliasPlugin } from '../preact-alias-plugin';
+
+type GetFrontComponentBuildPluginsOptions = {
+ usePreact?: boolean;
+ getSharedDependenciesBuildContext?: () => SharedDependenciesBuildContext | null;
+};
+
+export const getFrontComponentBuildPlugins = (
+ options?: GetFrontComponentBuildPluginsOptions,
+): esbuild.Plugin[] => [
+ ...(isDefined(options?.getSharedDependenciesBuildContext)
+ ? [
+ createSharedDependenciesShimPlugin(
+ options.getSharedDependenciesBuildContext,
+ ),
+ ]
+ : []),
+ createJsxRuntimeRemoteWrapperPlugin(
+ options?.usePreact ? { usePreact: true } : undefined,
+ ),
+ ...(options?.usePreact ? [createPreactAliasPlugin()] : []),
+ jsxTransformToRemoteDomWorkerFormatPlugin,
+ cssInjectionPlugin,
+];
diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/utils/unwrap-define-front-component-to-direct-export.ts b/packages/twenty-cli/src/app/bundles/front-component-build/utils/unwrap-define-front-component-to-direct-export.ts
new file mode 100644
index 00000000000..78a18af46ba
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/front-component-build/utils/unwrap-define-front-component-to-direct-export.ts
@@ -0,0 +1,48 @@
+const DEFINE_FRONT_COMPONENT_IMPORT_PATTERN =
+ /import\s*\{\s*define(?:Settings)?FrontComponent\s*,?\s*\}\s*from\s*['"][^'"]+['"];?\n?/g;
+
+const DEFINE_FRONT_COMPONENT_EXPORT_OPENING_PATTERN =
+ /export\s+default\s+define(?:Settings)?FrontComponent\s*\(/;
+
+const IDENTIFIER_COMPONENT_VALUE_PATTERN =
+ /component\s*:\s*([A-Za-z_$][\w$]*)\s*[,}]/;
+
+const FRONT_COMPONENT_DEFINITION_NAME = '__frontComponentDefinition';
+
+export const unwrapDefineFrontComponentToDirectExport = (
+ sourceCode: string,
+): string => {
+ if (!DEFINE_FRONT_COMPONENT_EXPORT_OPENING_PATTERN.test(sourceCode)) {
+ return sourceCode;
+ }
+
+ let transformedSource = sourceCode.replace(
+ DEFINE_FRONT_COMPONENT_IMPORT_PATTERN,
+ '',
+ );
+
+ transformedSource = transformedSource.replace(
+ DEFINE_FRONT_COMPONENT_EXPORT_OPENING_PATTERN,
+ `const ${FRONT_COMPONENT_DEFINITION_NAME} = (`,
+ );
+
+ const identifierComponentMatch = transformedSource.match(
+ IDENTIFIER_COMPONENT_VALUE_PATTERN,
+ );
+
+ if (identifierComponentMatch) {
+ const wrappedComponentName = identifierComponentMatch[1];
+
+ transformedSource = transformedSource.replace(
+ new RegExp(`export\\s+(const|function)\\s+${wrappedComponentName}\\b`),
+ `$1 ${wrappedComponentName}`,
+ );
+ }
+
+ return (
+ `import { createRoot as __createRoot } from 'react-dom/client';\n` +
+ `import { jsx as __frontComponentJsx } from 'react/jsx-runtime';\n` +
+ transformedSource +
+ `\nexport default function __renderFrontComponent(__container) { __createRoot(__container).render(__frontComponentJsx(${FRONT_COMPONENT_DEFINITION_NAME}.component, {})); }\n`
+ );
+};
diff --git a/packages/twenty-cli/src/app/bundles/plugins/stub-twenty-sdk-define.plugin.ts b/packages/twenty-cli/src/app/bundles/plugins/stub-twenty-sdk-define.plugin.ts
new file mode 100644
index 00000000000..0c74dec143b
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/plugins/stub-twenty-sdk-define.plugin.ts
@@ -0,0 +1,109 @@
+import type * as esbuild from 'esbuild';
+
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+
+export const isDefineFactoryExportName = (name: string): boolean =>
+ /^define[A-Z]/.test(name) || name === 'createValidationResult';
+
+const isPrimitive = (value: unknown): boolean =>
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'boolean';
+
+export const isPlainDataExport = (value: unknown): boolean =>
+ isPrimitive(value) ||
+ (isPlainObject(value) && Object.values(value).every(isPrimitive));
+
+const partitionDefineExports = (
+ mod: Record<string, unknown>,
+): {
+ factories: readonly string[];
+ plainData: readonly string[];
+ any: readonly string[];
+} => {
+ const factories: string[] = [];
+ const plainData: string[] = [];
+ const any: string[] = [];
+
+ for (const name of Object.keys(mod).sort()) {
+ if (isDefineFactoryExportName(name)) {
+ factories.push(name);
+ } else if (isPlainDataExport(mod[name])) {
+ plainData.push(name);
+ } else {
+ any.push(name);
+ }
+ }
+
+ return { factories, plainData, any };
+};
+
+const VIRTUAL_NAMESPACE = 'twenty-sdk-define-stub';
+const STUB_RESOLVED_PATH = '__twenty-sdk-define-stub__';
+
+const STUB_PRELUDE = `
+// Auto-generated stub for twenty-sdk/define injected by the Twenty CLI.
+// Real implementations would pull in zod, twenty-shared and ~1MB of code; at
+// runtime only \`default.config.handler\` is consumed, so tiny no-ops suffice.
+const __defineFactoryStub = (config) => ({
+ success: true,
+ config,
+ errors: [],
+});
+
+const __anyHandler = {
+ get(_target, prop) {
+ if (prop === '__esModule') return true;
+ if (prop === Symbol.toPrimitive) return () => '';
+ if (typeof prop === 'symbol') return undefined;
+ return new Proxy(() => undefined, __anyHandler);
+ },
+ apply() {
+ return new Proxy(() => undefined, __anyHandler);
+ },
+};
+const __anyStub = new Proxy(() => undefined, __anyHandler);
+`;
+
+export const buildStubModuleSource = (
+ twentySdkDefine: Record<string, unknown>,
+): string => {
+ const stubbedExports = partitionDefineExports(twentySdkDefine);
+ const exportLines: string[] = [];
+
+ for (const name of stubbedExports.factories) {
+ exportLines.push(`export const ${name} = __defineFactoryStub;`);
+ }
+ for (const name of stubbedExports.plainData) {
+ const value = twentySdkDefine[name];
+
+ exportLines.push(`export const ${name} = ${JSON.stringify(value)};`);
+ }
+ for (const name of stubbedExports.any) {
+ exportLines.push(`export const ${name} = __anyStub;`);
+ }
+
+ return `${STUB_PRELUDE}\n${exportLines.join('\n')}\n`;
+};
+
+export const createStubTwentySdkDefinePlugin = (
+ appPath: string,
+): esbuild.Plugin => ({
+ name: 'twenty-sdk-define-stub',
+ setup(build) {
+ build.onResolve({ filter: /^twenty-sdk\/define$/ }, () => ({
+ path: STUB_RESOLVED_PATH,
+ namespace: VIRTUAL_NAMESPACE,
+ }));
+
+ build.onLoad({ filter: /.*/, namespace: VIRTUAL_NAMESPACE }, () => ({
+ contents: buildStubModuleSource(
+ createRequire(join(appPath, 'package.json'))('twenty-sdk/define'),
+ ),
+ loader: 'js',
+ }));
+ },
+});
diff --git a/packages/twenty-cli/src/app/bundles/types/on-file-built-callback.type.ts b/packages/twenty-cli/src/app/bundles/types/on-file-built-callback.type.ts
new file mode 100644
index 00000000000..d6aabf360c3
--- /dev/null
+++ b/packages/twenty-cli/src/app/bundles/types/on-file-built-callback.type.ts
@@ -0,0 +1,9 @@
+import { type FileFolder } from 'twenty-shared/types';
+
+export type OnFileBuiltCallback = (options: {
+ fileFolder: FileFolder;
+ builtPath: string;
+ sourcePath: string;
+ checksum: string;
+ usesSdkClient?: boolean;
+}) => void | Promise<void>;
diff --git a/packages/twenty-cli/src/app/client/README.md b/packages/twenty-cli/src/app/client/README.md
new file mode 100644
index 00000000000..28dad5aa4e4
--- /dev/null
+++ b/packages/twenty-cli/src/app/client/README.md
@@ -0,0 +1,62 @@
+# Application client generation
+
+The CLI calls `replaceCoreClient` from the app's installed
+`twenty-client-sdk/generate`. See the [app tooling overview](../README.md) for
+package boundaries. The package manifest is read through `readJsonObject`;
+missing or malformed JSON and incorrect package names produce an expected-package
+`CLIENT_GENERATION_FAILED` error.
+
+Public `app apply` invokes the generator through the internal
+`generateSourceClient` worker request.
+
+## Package and output ownership
+
+The app must have `node_modules/twenty-client-sdk/package.json` with the expected
+package name. Resolution does not search workspace ancestors, avoiding writes
+to a hoisted-only installation shared by other apps. Package-manager symlinks
+are followed, so a linked installation can still be shared.
+
+Resolve `twenty-client-sdk/generate` from this package and require the entry to
+belong to the same real package directory. It must export a callable
+`replaceCoreClient`. This keeps the generator and the client it writes into on
+the same installed version, with no fallback to the CLI's own client SDK.
+
+The output layout is `dist/core/generated`, `dist/core.mjs` and
+`dist/core.cjs` inside that installation. Source files and the metadata client
+remain unchanged. Neither apps nor SDK packages depend on the CLI. The client
+SDK's generator dependencies remain part of the app's installed client package.
+
+## Failure and cancellation
+
+The worker requires a non-empty schema and an absolute app path. Failures use
+`CLIENT_GENERATION_FAILED` / `CANCELLED` results. Missing or incompatible local
+packages fail before invoking the generator. The generator rejects
+invalid schemas without replacing the installed bundles.
+
+Generation is not transactional. A generator failure can leave partial changes;
+the wrapper reports that failure even if cancellation was requested meanwhile.
+The generator has no cancellation parameter, so the wrapper waits for it to
+settle and then checks the signal. Forced worker termination can interrupt file
+writes. The operation does not roll back partial writes.
+
+## Verification
+
+From `packages/twenty-cli`, after building the shared, SDK and client SDK:
+
+```sh
+node ../../node_modules/vitest/vitest.mjs run --config vitest.config.ts src/app/client src/commands/app/__tests__/app-real-sdk.spec.ts --maxWorkers=1
+```
+
+Parity runs the SDK reference and the production CLI worker against
+the same schema and app path, comparing every generated source file and both
+compiled bundles byte for byte. Reusing the path keeps esbuild's source-path
+comments identical without normalizing file contents. The app has its own client
+SDK and no application SDK. The generated CommonJS client is loaded to verify
+its `CoreApiClient` export.
+
+Other cases cover a missing or hoisted-only package, invalid manifests and
+schemas, missing exports, a non-callable API, selection of the app's generator,
+pre-cancellation, in-flight cancellation and preserved failures/partial writes.
+The local HTTP apply contract exercises CLI client
+generation, along with snapshot upload, synchronization, pull-base recording
+and release. No live workspace is contacted.
diff --git a/packages/twenty-cli/src/app/client/__tests__/generate-application-client.spec.ts b/packages/twenty-cli/src/app/client/__tests__/generate-application-client.spec.ts
new file mode 100644
index 00000000000..8bcefca77b9
--- /dev/null
+++ b/packages/twenty-cli/src/app/client/__tests__/generate-application-client.spec.ts
@@ -0,0 +1,386 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build, stop } from 'esbuild';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { installTestClientSdk } from '@/app/__tests__/utils/install-test-client-sdk';
+import { generateApplicationClient } from '@/app/client/generate-application-client';
+import { parseNullData, parseToolingResult } from '@/app/parse-tooling-result';
+import { runAppWorker } from '@/app/run-app-worker';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const SCHEMA = 'type Query { greeting: String }';
+const require = createRequire(import.meta.url);
+
+describe('CLI client generation uses the app generator', () => {
+ let root: string;
+ let appPath: string;
+ let packageRoot: string;
+ let sdkEntryPath: string;
+
+ const readGeneratedClient = async () => {
+ const directory = join(packageRoot, 'dist/core/generated');
+ const entries = await readdir(directory, {
+ recursive: true,
+ withFileTypes: true,
+ });
+ const paths = [
+ 'core.cjs',
+ 'core.mjs',
+ ...entries
+ .filter((entry) => entry.isFile())
+ .map((entry) =>
+ join(entry.parentPath, entry.name).slice(
+ join(packageRoot, 'dist').length + 1,
+ ),
+ ),
+ ].sort();
+ return Promise.all(
+ paths.map(async (path) => [
+ path,
+ await readFile(join(packageRoot, 'dist', path), 'utf8'),
+ ]),
+ );
+ };
+
+ const runGeneration = async (schema = SCHEMA) => {
+ const response = await runAppWorker({
+ request: { type: 'generateSourceClient', appPath, schema },
+ signal: new AbortController().signal,
+ });
+ expect(response.isSnapshotHeld).toBe(false);
+ return parseToolingResult({
+ value: response.result,
+ parseData: parseNullData,
+ });
+ };
+
+ const installGenerator = async (contents: string) => {
+ const manifest = JSON.parse(
+ await readFile(join(packageRoot, 'package.json'), 'utf8'),
+ );
+ manifest.exports['./generate'] = './custom-generator.cjs';
+ await writeFile(
+ join(packageRoot, 'package.json'),
+ JSON.stringify(manifest),
+ );
+ await writeFile(join(packageRoot, 'custom-generator.cjs'), contents);
+ return join(packageRoot, 'custom-generator.cjs');
+ };
+
+ beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-cli-client-parity-'));
+ await mkdir(join(root, 'node_modules'));
+ for (const name of ['@sniptt', 'twenty-client-sdk', 'twenty-shared']) {
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules', name),
+ join(root, 'node_modules', name),
+ );
+ }
+ const sdkSource = join(REPOSITORY_ROOT, 'packages/twenty-sdk/src');
+ sdkEntryPath = join(root, 'sdk-reference.cjs');
+ await build({
+ stdin: {
+ contents: `export { generateApplicationClient } from './application-build/generate-application-client';`,
+ resolveDir: sdkSource,
+ },
+ outfile: sdkEntryPath,
+ alias: { '@': sdkSource },
+ bundle: true,
+ packages: 'external',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node24',
+ });
+ await buildTestAppWorker(join(root, 'reference'), {
+ aliases: { '@/app/client/generate-application-client': sdkEntryPath },
+ });
+ await buildTestAppWorker(join(root, 'cli'));
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ }, 60000);
+
+ afterAll(async () => {
+ await stop();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-client-app-'));
+ packageRoot = join(appPath, 'node_modules/twenty-client-sdk');
+ await installTestClientSdk(packageRoot);
+ await writeFile(join(packageRoot, 'dist/core.cjs'), 'old core client');
+ await writeFile(join(packageRoot, 'dist/core.mjs'), 'old core client');
+ await writeFile(join(packageRoot, 'dist/metadata.cjs'), 'metadata client');
+ await writeFile(join(appPath, 'source.ts'), 'export const source = true;');
+ });
+
+ afterEach(async () => {
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('matches SDK-generated source and bundles byte for byte without an application SDK', async () => {
+ launch.modulePath = join(root, 'reference/app-worker.cjs');
+ const result = await runGeneration();
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ expect(result).toEqual({
+ success: true,
+ data: null,
+ diagnostics: [],
+ });
+ const expected = await readGeneratedClient();
+ expect(await runGeneration()).toEqual({
+ success: true,
+ data: null,
+ diagnostics: [],
+ });
+ expect(await readGeneratedClient()).toEqual(expected);
+ expect(require(join(packageRoot, 'dist/core.cjs'))).toHaveProperty(
+ 'CoreApiClient',
+ );
+ expect(await readFile(join(packageRoot, 'dist/metadata.cjs'), 'utf8')).toBe(
+ 'metadata client',
+ );
+ expect(await readFile(join(appPath, 'source.ts'), 'utf8')).toBe(
+ 'export const source = true;',
+ );
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'node_modules',
+ 'source.ts',
+ ]);
+ }, 15000);
+
+ it.each(['not a schema', '', ' '])(
+ 'preserves the installed client for invalid schema %j',
+ async (schema) => {
+ expect(await runGeneration(schema)).toMatchObject({
+ success: false,
+ error: { code: 'CLIENT_GENERATION_FAILED' },
+ });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ expect(await readFile(join(packageRoot, 'dist/core.mjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ },
+ );
+
+ it.each([null, {}, []])(
+ 'rejects a non-string schema from JavaScript callers: %j',
+ async (schema) => {
+ expect(
+ await Reflect.apply(generateApplicationClient, undefined, [
+ { appPath, schema },
+ ]),
+ ).toMatchObject({
+ success: false,
+ error: { code: 'CLIENT_GENERATION_FAILED' },
+ });
+ },
+ );
+
+ it('does not create a package when the dependency is missing', async () => {
+ await rm(join(appPath, 'node_modules'), { recursive: true });
+ expect(await runGeneration()).toMatchObject({
+ success: false,
+ error: { code: 'CLIENT_GENERATION_FAILED' },
+ });
+ expect(await readdir(appPath)).toEqual(['source.ts']);
+ });
+
+ it('does not write into a hoisted-only installation', async () => {
+ const workspacePath = appPath;
+ appPath = join(workspacePath, 'packages/app');
+ try {
+ await mkdir(appPath, { recursive: true });
+ expect(await runGeneration()).toMatchObject({
+ success: false,
+ error: { code: 'CLIENT_GENERATION_FAILED' },
+ });
+ expect(await readdir(appPath)).toEqual([]);
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ } finally {
+ appPath = workspacePath;
+ }
+ });
+
+ it.each(['null', '{"name":"other-package"}', '{'])(
+ 'rejects an invalid package manifest: %s',
+ async (manifest) => {
+ await writeFile(join(packageRoot, 'package.json'), manifest);
+ expect(await runGeneration()).toMatchObject({
+ success: false,
+ error: { code: 'CLIENT_GENERATION_FAILED' },
+ });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ },
+ );
+
+ it('requires the generate export of the same installed package', async () => {
+ const manifest = JSON.parse(
+ await readFile(join(packageRoot, 'package.json'), 'utf8'),
+ );
+ delete manifest.exports['./generate'];
+ await writeFile(
+ join(packageRoot, 'package.json'),
+ JSON.stringify(manifest),
+ );
+ expect(await runGeneration()).toMatchObject({
+ success: false,
+ error: {
+ code: 'CLIENT_GENERATION_FAILED',
+ message: expect.stringContaining('own generate entry point'),
+ },
+ });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ });
+
+ it('requires replaceCoreClient to be callable', async () => {
+ await installGenerator('module.exports = { replaceCoreClient: false };');
+ expect(await runGeneration()).toMatchObject({
+ success: false,
+ error: {
+ code: 'CLIENT_GENERATION_FAILED',
+ message: expect.stringContaining('must export replaceCoreClient'),
+ },
+ });
+ });
+
+ it('runs the app generator instead of the repository generator', async () => {
+ await installGenerator(
+ "exports.replaceCoreClient = async ({ packageRoot, schema }) => require('node:fs/promises').writeFile(require('node:path').join(packageRoot, 'dist/core.cjs'), schema);",
+ );
+ expect(await runGeneration()).toMatchObject({ success: true });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ SCHEMA,
+ );
+ });
+
+ it('rejects a relative app path', async () => {
+ expect(
+ await generateApplicationClient({ appPath: '.', schema: SCHEMA }),
+ ).toMatchObject({ success: false, error: { code: 'INVALID_APP_PATH' } });
+ });
+
+ it.each([undefined, 'Stopped by caller', Number.NaN])(
+ 'does not write when already cancelled with reason %s',
+ async (reason) => {
+ expect(
+ await generateApplicationClient({
+ appPath,
+ schema: SCHEMA,
+ signal: AbortSignal.abort(reason),
+ }),
+ ).toMatchObject({ success: false, error: { code: 'CANCELLED' } });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'old core client',
+ );
+ },
+ );
+
+ it('waits for an in-flight generator to settle before reporting cancellation', async () => {
+ const entry = await installGenerator(`
+ let begin, finish;
+ exports.started = new Promise(resolve => { begin = resolve; });
+ const completed = new Promise(resolve => { finish = resolve; });
+ exports.finish = () => finish();
+ exports.replaceCoreClient = async ({ packageRoot }) => {
+ begin(); await completed;
+ await require('node:fs/promises').writeFile(require('node:path').join(packageRoot, 'dist/core.cjs'), 'finished client');
+ };
+ `);
+ const generator = require(entry) as {
+ started: Promise<void>;
+ finish: () => void;
+ };
+ const controller = new AbortController();
+ let settled = false;
+ const operation = generateApplicationClient({
+ appPath,
+ schema: SCHEMA,
+ signal: controller.signal,
+ }).then((result) => {
+ settled = true;
+ return result;
+ });
+ await generator.started;
+ controller.abort();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(settled).toBe(false);
+ generator.finish();
+ expect(await operation).toMatchObject({
+ success: false,
+ error: { code: 'CANCELLED' },
+ });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'finished client',
+ );
+ });
+
+ it.each([false, true])(
+ 'preserves generator failures and partial writes with cancellation %s',
+ async (shouldCancel) => {
+ const entry = await installGenerator(`
+ exports.cancel = () => {};
+ exports.replaceCoreClient = async ({ packageRoot }) => {
+ exports.cancel();
+ await require('node:fs/promises').writeFile(require('node:path').join(packageRoot, 'dist/core.cjs'), 'partially replaced');
+ throw new Error('Client compilation failed');
+ };
+ `);
+ const generator = require(entry) as { cancel: () => void };
+ const controller = new AbortController();
+ if (shouldCancel) generator.cancel = () => controller.abort();
+ expect(
+ await generateApplicationClient({
+ appPath,
+ schema: SCHEMA,
+ signal: controller.signal,
+ }),
+ ).toMatchObject({
+ success: false,
+ error: {
+ code: 'CLIENT_GENERATION_FAILED',
+ message: 'Client compilation failed',
+ },
+ });
+ expect(await readFile(join(packageRoot, 'dist/core.cjs'), 'utf8')).toBe(
+ 'partially replaced',
+ );
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/app/client/generate-application-client.ts b/packages/twenty-cli/src/app/client/generate-application-client.ts
new file mode 100644
index 00000000000..0e56a668c7f
--- /dev/null
+++ b/packages/twenty-cli/src/app/client/generate-application-client.ts
@@ -0,0 +1,83 @@
+import { realpath } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { isFunction, isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type ToolingResult } from '@/app/types/tooling-result.type';
+import { readJsonObject } from '@/app/read-json-object';
+import { resolveInsideSdk } from '@/app/project/resolve-inside-sdk';
+import { validateAppPath } from '@/app/snapshots/validate-app-path';
+
+export const generateApplicationClient = async ({
+ appPath,
+ schema,
+ signal,
+}: {
+ appPath: string;
+ schema: string;
+ signal?: AbortSignal;
+}): Promise<ToolingResult<null>> => {
+ const validation = await validateAppPath(appPath);
+
+ if (!validation.success) {
+ return validation;
+ }
+
+ try {
+ signal?.throwIfAborted();
+
+ if (!isNonEmptyString(schema)) {
+ throw new Error('schema must be a non-empty GraphQL schema string.');
+ }
+
+ const packageRoot = join(appPath, 'node_modules', 'twenty-client-sdk');
+ const packageJson = await readJsonObject(join(packageRoot, 'package.json'));
+
+ if (packageJson?.name !== 'twenty-client-sdk') {
+ throw new Error(
+ 'Expected twenty-client-sdk in the app node_modules directory.',
+ );
+ }
+
+ const requireFromClient = createRequire(join(packageRoot, 'package.json'));
+ const generatorPath = resolveInsideSdk({
+ resolveFromApp: requireFromClient.resolve,
+ specifier: 'twenty-client-sdk/generate',
+ sdkPath: await realpath(packageRoot),
+ });
+
+ if (!isDefined(generatorPath)) {
+ throw new Error(
+ "The app's twenty-client-sdk does not provide its own generate entry point. Install a compatible twenty-client-sdk version in this app.",
+ );
+ }
+
+ signal?.throwIfAborted();
+ const generator: unknown = requireFromClient(generatorPath);
+
+ if (!isPlainObject(generator) || !isFunction(generator.replaceCoreClient)) {
+ throw new Error(
+ "The app's twenty-client-sdk/generate must export replaceCoreClient.",
+ );
+ }
+
+ signal?.throwIfAborted();
+ await generator.replaceCoreClient({ packageRoot, schema });
+ signal?.throwIfAborted();
+
+ return { success: true, data: null, diagnostics: [] };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code:
+ signal?.aborted && Object.is(error, signal.reason)
+ ? 'CANCELLED'
+ : 'CLIENT_GENERATION_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ diagnostics: [],
+ };
+ }
+};
diff --git a/packages/twenty-cli/src/app/constants/app-worker.constant.ts b/packages/twenty-cli/src/app/constants/app-worker.constant.ts
new file mode 100644
index 00000000000..7d3afbe1d87
--- /dev/null
+++ b/packages/twenty-cli/src/app/constants/app-worker.constant.ts
@@ -0,0 +1,4 @@
+export const APP_WORKER = {
+ CANCEL_GRACE_MILLISECONDS: 3000,
+ OUTPUT_LIMIT_BYTES: 64 * 1024,
+} as const;
diff --git a/packages/twenty-cli/src/app/constants/pull-base-file-path.constant.ts b/packages/twenty-cli/src/app/constants/pull-base-file-path.constant.ts
new file mode 100644
index 00000000000..51d32f24b06
--- /dev/null
+++ b/packages/twenty-cli/src/app/constants/pull-base-file-path.constant.ts
@@ -0,0 +1 @@
+export const PULL_BASE_FILE_PATH = '.twenty/cli/pull-base.json';
diff --git a/packages/twenty-cli/src/app/create-app-not-installed-error.ts b/packages/twenty-cli/src/app/create-app-not-installed-error.ts
new file mode 100644
index 00000000000..05a31395a3c
--- /dev/null
+++ b/packages/twenty-cli/src/app/create-app-not-installed-error.ts
@@ -0,0 +1,16 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const createAppNotInstalledError = ({
+ universalIdentifier,
+ apiUrl,
+}: {
+ universalIdentifier: string;
+ apiUrl: string;
+}) =>
+ new CliError({
+ code: 'APP_NOT_INSTALLED',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: `No app with universal identifier ${universalIdentifier} is installed on ${apiUrl}.`,
+ details: { universalIdentifier },
+ });
diff --git a/packages/twenty-cli/src/app/create-app-project.ts b/packages/twenty-cli/src/app/create-app-project.ts
new file mode 100644
index 00000000000..04968c0bc57
--- /dev/null
+++ b/packages/twenty-cli/src/app/create-app-project.ts
@@ -0,0 +1,219 @@
+import { constants } from 'node:fs';
+import {
+ copyFile,
+ cp,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rename,
+ rm,
+ rmdir,
+ stat,
+ unlink,
+ writeFile,
+} from 'node:fs/promises';
+import { basename, dirname, join, relative } from 'node:path';
+
+import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';
+import { copyBaseApplicationProject } from '@create-twenty-app/utils/app-template';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { getAppTemplateDirectory } from '@/app/get-app-template-directory';
+import { getAppTemplateOverlayDirectory } from '@/app/get-app-template-overlay-directory';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+const TEMPLATE_PLACEHOLDER = 'TO-BE-GENERATED';
+
+const createAppPathUnavailableError = ({
+ appDirectory,
+ reason,
+}: {
+ appDirectory: string;
+ reason: string;
+}) =>
+ new CliError({
+ code: 'APP_PATH_UNAVAILABLE',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `${appDirectory} already exists and ${reason}.`,
+ hint: 'Choose another app name, or pass --path with a new or empty directory.',
+ details: { path: appDirectory },
+ });
+
+const readAvailableAppDirectory = async (
+ appDirectory: string,
+): Promise<'missing' | 'empty'> => {
+ const stats = await stat(appDirectory).catch((error: unknown) => {
+ if (hasErrorCode(error, 'ENOENT')) {
+ return undefined;
+ }
+
+ throw error;
+ });
+
+ if (!isDefined(stats)) {
+ return 'missing';
+ }
+
+ if (!stats.isDirectory()) {
+ throw createAppPathUnavailableError({
+ appDirectory,
+ reason: 'is not a directory',
+ });
+ }
+
+ if (isNonEmptyArray(await readdir(appDirectory))) {
+ throw createAppPathUnavailableError({
+ appDirectory,
+ reason: 'is not empty',
+ });
+ }
+
+ return 'empty';
+};
+
+const findUnrenderedFiles = async (directory: string) => {
+ const entries = await readdir(directory, {
+ recursive: true,
+ withFileTypes: true,
+ });
+ const unrenderedFiles: string[] = [];
+
+ for (const entry of entries) {
+ const filePath = join(entry.parentPath, entry.name);
+
+ if (
+ entry.isFile() &&
+ (await readFile(filePath, 'utf8')).includes(TEMPLATE_PLACEHOLDER)
+ ) {
+ unrenderedFiles.push(relative(directory, filePath));
+ }
+ }
+
+ return unrenderedFiles;
+};
+
+const copyIntoEmptyDirectory = async ({
+ stagingDirectory,
+ appDirectory,
+}: {
+ stagingDirectory: string;
+ appDirectory: string;
+}) => {
+ const createdEntries: { createdPath: string; isDirectory: boolean }[] = [];
+
+ try {
+ for (const entry of await readdir(stagingDirectory, {
+ recursive: true,
+ withFileTypes: true,
+ })) {
+ const sourcePath = join(entry.parentPath, entry.name);
+ const createdPath = join(
+ appDirectory,
+ relative(stagingDirectory, sourcePath),
+ );
+
+ if (entry.isDirectory()) {
+ await mkdir(createdPath);
+ } else {
+ await copyFile(sourcePath, createdPath, constants.COPYFILE_EXCL);
+ }
+
+ createdEntries.push({ createdPath, isDirectory: entry.isDirectory() });
+ }
+ } catch (error) {
+ for (const { createdPath, isDirectory } of createdEntries.reverse()) {
+ await (isDirectory ? rmdir(createdPath) : unlink(createdPath)).catch(
+ () => undefined,
+ );
+ }
+
+ throw error;
+ }
+
+ await rm(stagingDirectory, { recursive: true, force: true });
+};
+
+export const createAppProject = async ({
+ appDirectory,
+ appName,
+ appDisplayName,
+ appDescription,
+ signal,
+}: {
+ appDirectory: string;
+ appName: string;
+ appDisplayName: string;
+ appDescription: string;
+ signal: AbortSignal;
+}) => {
+ await readAvailableAppDirectory(appDirectory);
+
+ const parentDirectory = dirname(appDirectory);
+
+ await mkdir(parentDirectory, { recursive: true });
+
+ const stagingDirectory = await mkdtemp(
+ join(parentDirectory, `.${basename(appDirectory)}-`),
+ );
+
+ try {
+ await copyBaseApplicationProject({
+ appName,
+ appDisplayName,
+ appDescription,
+ appDirectory: stagingDirectory,
+ templateDirectory: getAppTemplateDirectory(),
+ });
+ signal.throwIfAborted();
+
+ const packageJsonPath = join(stagingDirectory, 'package.json');
+ const packageJson: { engines: Record<string, string> } = JSON.parse(
+ await readFile(packageJsonPath, 'utf8'),
+ );
+
+ packageJson.engines = {
+ ...packageJson.engines,
+ twenty: `>=${TEMPLATE_PACKAGE_VERSION}`,
+ };
+
+ await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
+ await cp(getAppTemplateOverlayDirectory(), stagingDirectory, {
+ recursive: true,
+ });
+
+ const unrenderedFiles = await findUnrenderedFiles(stagingDirectory);
+
+ if (isNonEmptyArray(unrenderedFiles)) {
+ throw new CliError({
+ code: 'APP_INIT_FAILED',
+ message: `The app template still has placeholders in ${unrenderedFiles.join(', ')}.`,
+ hint: 'This CLI ships an app template it cannot render. Upgrade the twenty CLI.',
+ details: { unrenderedFiles },
+ });
+ }
+
+ signal.throwIfAborted();
+
+ if ((await readAvailableAppDirectory(appDirectory)) === 'empty') {
+ await copyIntoEmptyDirectory({ stagingDirectory, appDirectory });
+ } else {
+ await rename(stagingDirectory, appDirectory);
+ }
+ } catch (error) {
+ await rm(stagingDirectory, { recursive: true, force: true });
+
+ if (error instanceof CliError || signal.aborted) {
+ throw error;
+ }
+
+ throw new CliError({
+ code: 'APP_INIT_FAILED',
+ message: `Could not create ${appDirectory}: ${error instanceof Error ? error.message : String(error)}`,
+ hint: 'Files this command had written there were removed. Fix the cause, then run the command again.',
+ details: { path: appDirectory },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/create-app-worker-environment.ts b/packages/twenty-cli/src/app/create-app-worker-environment.ts
new file mode 100644
index 00000000000..203ae30bfde
--- /dev/null
+++ b/packages/twenty-cli/src/app/create-app-worker-environment.ts
@@ -0,0 +1,21 @@
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+
+const SCRUBBED_ENVIRONMENT_VARIABLES = new Set<string>([
+ ...Object.values(TARGET_ENVIRONMENT_VARIABLE),
+ 'TWENTY_APP_ACCESS_TOKEN',
+ 'TWENTY_APP_APPLICATION_ACCESS_TOKEN',
+]);
+
+const CREDENTIAL_ENVIRONMENT_VARIABLE_PATTERN =
+ /^TWENTY_.*(TOKEN|KEY|SECRET|PASSWORD)$/;
+
+export const createAppWorkerEnvironment = (
+ environment: NodeJS.ProcessEnv,
+): NodeJS.ProcessEnv =>
+ Object.fromEntries(
+ Object.entries(environment).filter(
+ ([name]) =>
+ !SCRUBBED_ENVIRONMENT_VARIABLES.has(name) &&
+ !CREDENTIAL_ENVIRONMENT_VARIABLE_PATTERN.test(name),
+ ),
+ );
diff --git a/packages/twenty-cli/src/app/create-output-collector.ts b/packages/twenty-cli/src/app/create-output-collector.ts
new file mode 100644
index 00000000000..27f0f070700
--- /dev/null
+++ b/packages/twenty-cli/src/app/create-output-collector.ts
@@ -0,0 +1,18 @@
+export const createOutputCollector = (limitBytes: number) => {
+ const collected = Buffer.alloc(limitBytes);
+ let size = 0;
+ let isTruncated = false;
+
+ return {
+ add: (chunk: Buffer) => {
+ const copied = chunk.copy(collected, size, 0, limitBytes - size);
+
+ size += copied;
+ isTruncated ||= copied < chunk.length;
+ },
+ read: () => ({
+ text: collected.toString('utf8', 0, size),
+ isTruncated,
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/app/create-tooling-failure.ts b/packages/twenty-cli/src/app/create-tooling-failure.ts
new file mode 100644
index 00000000000..e7116d1c872
--- /dev/null
+++ b/packages/twenty-cli/src/app/create-tooling-failure.ts
@@ -0,0 +1,73 @@
+import { type ToolingDiagnostic } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+export const createToolingFailure = ({
+ error,
+ diagnostics,
+ sdkVersion,
+ operation = 'build',
+}: {
+ error: {
+ code: string;
+ message: string;
+ hint?: string;
+ details?: Record<string, unknown>;
+ };
+ diagnostics: ToolingDiagnostic[];
+ sdkVersion: string;
+ operation?: 'build' | 'generateClient';
+}) => {
+ if (error.code === 'CANCELLED') {
+ return createCancelledError();
+ }
+
+ const errorCount = diagnostics.filter(
+ (diagnostic) => diagnostic.severity === 'error',
+ ).length;
+ const errorLabel = errorCount === 1 ? 'error' : 'errors';
+ const details = {
+ ...error.details,
+ toolingErrorCode: error.code,
+ sdkVersion,
+ diagnostics,
+ };
+
+ switch (error.code) {
+ case 'SDK_SOURCE_UNSUPPORTED':
+ case 'TYPESCRIPT_NOT_INSTALLED':
+ case 'TOOLING_UNSUPPORTED':
+ case 'NODE_VERSION_UNSUPPORTED':
+ return new CliError({
+ code: error.code,
+ message: error.message,
+ hint: error.hint,
+ details,
+ });
+ }
+
+ if (error.code === 'TYPECHECK_FAILED') {
+ return new CliError({
+ code: 'TYPECHECK_FAILED',
+ message:
+ errorCount > 0
+ ? `Typecheck failed with ${errorCount} ${errorLabel}.`
+ : `Typecheck failed: ${error.message}`,
+ hint: error.hint,
+ details,
+ });
+ }
+
+ return new CliError({
+ code:
+ operation === 'generateClient'
+ ? 'CLIENT_GENERATION_FAILED'
+ : 'BUILD_FAILED',
+ message:
+ operation === 'generateClient'
+ ? error.message
+ : `The build failed: ${error.message}`,
+ hint: error.hint,
+ details,
+ });
+};
diff --git a/packages/twenty-cli/src/app/deployment/__tests__/read-snapshot-file.spec.ts b/packages/twenty-cli/src/app/deployment/__tests__/read-snapshot-file.spec.ts
new file mode 100644
index 00000000000..991355a6f59
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/__tests__/read-snapshot-file.spec.ts
@@ -0,0 +1,69 @@
+import { openAsBlob } from 'node:fs';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+import { readSnapshotFile } from '@/app/deployment/read-snapshot-file';
+import { hashContent } from '@/utils/hash-content';
+
+vi.mock('node:fs', { spy: true });
+
+describe('snapshot upload contents', () => {
+ it('reports a file changing during verification as an invalid snapshot', async () => {
+ const blob = new Blob(['content']);
+ vi.spyOn(blob, 'stream').mockReturnValue(
+ new ReadableStream({
+ pull(controller) {
+ controller.error(
+ new DOMException('The blob could not be read', 'NotReadableError'),
+ );
+ },
+ }),
+ );
+ vi.mocked(openAsBlob).mockResolvedValueOnce(blob);
+ await expect(
+ readSnapshotFile({
+ snapshotDirectory: tmpdir(),
+ artifact: {
+ path: 'function.mjs',
+ size: 7,
+ sha256: hashContent('content'),
+ role: 'logic-function',
+ sourcePath: 'function.ts',
+ },
+ }),
+ ).rejects.toMatchObject({
+ code: 'SNAPSHOT_INVALID',
+ hint: expect.stringContaining('Build again'),
+ });
+ });
+ it('returns file-backed content and refuses changed artifacts before upload', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'snapshot-stream-'));
+ const content = Buffer.alloc(1024 * 1024, 'x');
+ const artifact = {
+ path: 'function.mjs',
+ size: content.length,
+ sha256: hashContent(content),
+ role: 'logic-function',
+ sourcePath: 'function.ts',
+ };
+
+ try {
+ await writeFile(join(directory, artifact.path), content);
+ const blob = await readSnapshotFile({
+ snapshotDirectory: directory,
+ artifact,
+ });
+ expect(blob).toBeInstanceOf(Blob);
+ expect(blob.size).toBe(content.length);
+ expect(Buffer.from(await blob.arrayBuffer())).toEqual(content);
+ await writeFile(join(directory, artifact.path), 'changed');
+ await expect(
+ readSnapshotFile({ snapshotDirectory: directory, artifact }),
+ ).rejects.toMatchObject({ code: 'SNAPSHOT_INVALID' });
+ await expect(blob.arrayBuffer()).rejects.toThrow();
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/twenty-cli/src/app/deployment/__tests__/resolve-snapshot-directory.spec.ts b/packages/twenty-cli/src/app/deployment/__tests__/resolve-snapshot-directory.spec.ts
new file mode 100644
index 00000000000..8ae68373cbb
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/__tests__/resolve-snapshot-directory.spec.ts
@@ -0,0 +1,52 @@
+import { join } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { resolveSnapshotDirectory } from '@/app/deployment/resolve-snapshot-directory';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+
+const appPath = '/app';
+const build: ToolingBuild = {
+ buildId: 'build-id',
+ contentHash: 'hash',
+ application: {
+ universalIdentifier: 'app-id',
+ name: 'app',
+ displayName: 'App',
+ },
+ manifestFormat: 'twenty-application',
+ manifest: {},
+ files: [],
+};
+
+describe('resolveSnapshotDirectory', () => {
+ it.each(['.twenty/cli/snapshots/build-cli/files'])(
+ 'accepts the snapshot inside %s',
+ (path) => {
+ const directory = join(appPath, path);
+ expect(
+ resolveSnapshotDirectory({
+ build: { ...build, directory },
+ appPath,
+ }),
+ ).toBe(directory);
+ },
+ );
+ it.each([
+ '.twenty/snapshots/build-sdk/files',
+ '.twenty/cli/pull-base.json',
+ '.twenty/output',
+ '.twenty/cli/snapshots',
+ '.twenty/snapshots',
+ '.twenty/cli/snapshots-other/files',
+ '.twenty/cli/snapshots/../../../outside',
+ '../other/.twenty/cli/snapshots/build/files',
+ ])('rejects %s outside the CLI snapshot directory', (path) => {
+ expect(() =>
+ resolveSnapshotDirectory({
+ build: { ...build, directory: join(appPath, path) },
+ appPath,
+ }),
+ ).toThrow(expect.objectContaining({ code: 'SNAPSHOT_INVALID' }));
+ });
+});
diff --git a/packages/twenty-cli/src/app/deployment/apply-app-build.ts b/packages/twenty-cli/src/app/deployment/apply-app-build.ts
new file mode 100644
index 00000000000..e66d279b7f6
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/apply-app-build.ts
@@ -0,0 +1,232 @@
+import { createApplyFailure } from '@/app/deployment/create-apply-failure';
+import { fetchAppPlan } from '@/app/deployment/fetch-app-plan';
+import { formatAppPlanActions } from '@/app/deployment/format-app-plan';
+import { getAppPlanSummary } from '@/app/deployment/get-app-plan-summary';
+import { installDevelopmentApp } from '@/app/deployment/install-development-app';
+import { registerApp } from '@/app/deployment/register-app';
+import { requireApproval } from '@/app/deployment/require-approval';
+import { resolveSnapshotDirectory } from '@/app/deployment/resolve-snapshot-directory';
+import { syncAppManifest } from '@/app/deployment/sync-app-manifest';
+import { type AppApplyPhase } from '@/app/deployment/types/app-apply-phase.type';
+import { type AppPlanAction } from '@/app/deployment/types/app-plan.type';
+import { type AppUploadProgress } from '@/app/deployment/types/app-upload-progress.type';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { uploadAppFiles } from '@/app/deployment/upload-app-files';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { CliError } from '@/output/cli-error';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+
+export type AppApplyResult = {
+ completedPhases: AppApplyPhase[];
+ isRegistrationCreated: boolean;
+ appliedActions: AppPlanAction[] | undefined;
+ acknowledgedUniversalIdentifier: string;
+ upload: AppUploadProgress;
+};
+
+const isPlanUnavailable = (error: unknown) =>
+ error instanceof CliError && error.code === 'PLAN_UNAVAILABLE';
+
+export const applyAppBuild = async ({
+ build,
+ appPath,
+ context: { target, signal, output, outputMode, options },
+ inferDeletionFromMissingEntities,
+ isCreationApproved,
+ isDeletionApproved,
+ approvalSignal,
+ beforeWrite,
+ flushProgress,
+}: {
+ build: ToolingBuild;
+ appPath: string;
+ context: TargetCommandContext;
+ inferDeletionFromMissingEntities: boolean;
+ isCreationApproved: boolean;
+ isDeletionApproved: boolean;
+ approvalSignal?: AbortSignal;
+ beforeWrite?: () => void;
+ flushProgress?: () => Promise<void>;
+}): Promise<AppApplyResult> => {
+ const completedPhases: AppApplyPhase[] = ['build'];
+ const upload: AppUploadProgress = {
+ fileCount: 0,
+ byteCount: 0,
+ hasCreatedTargets: false,
+ };
+ const canPrompt = isInteractionAllowed({ options, outputMode });
+ const application = build.application;
+
+ const fail = (error: unknown, phase: AppApplyPhase) =>
+ createApplyFailure({
+ error,
+ phase,
+ completedPhases,
+ upload,
+ signal,
+ });
+
+ const runPhase = async <TResult>(
+ phase: AppApplyPhase,
+ run: () => Promise<TResult>,
+ ) => {
+ await flushProgress?.().catch((error: unknown) => {
+ throw fail(error, 'confirmation');
+ });
+
+ if (['registration', 'installation', 'upload', 'sync'].includes(phase)) {
+ try {
+ beforeWrite?.();
+ } catch (error) {
+ throw fail(error, 'confirmation');
+ }
+ }
+
+ try {
+ const result = await run();
+
+ completedPhases.push(phase);
+
+ return result;
+ } catch (error) {
+ throw fail(error, phase);
+ }
+ };
+
+ const approve = async (approval: {
+ isApproved: boolean;
+ question: string;
+ code: CliErrorCode;
+ message: string;
+ hint: string;
+ }) => {
+ await flushProgress?.().catch((error: unknown) => {
+ throw fail(error, 'confirmation');
+ });
+ return requireApproval({
+ ...approval,
+ canPrompt,
+ declinedMessage: 'Apply stopped at the confirmation prompt.',
+ signal: approvalSignal ?? signal,
+ })
+ .then(() => approvalSignal?.throwIfAborted())
+ .catch((error: unknown) => {
+ throw fail(error, 'confirmation');
+ });
+ };
+
+ const preview = () =>
+ fetchAppPlan({ build, inferDeletionFromMissingEntities, target, signal });
+
+ const previewOrBootstrap = async () => {
+ try {
+ const actions = await preview();
+
+ completedPhases.push('preview');
+
+ return { actions, isRegistrationCreated: false };
+ } catch (error) {
+ if (!isPlanUnavailable(error)) {
+ throw fail(error, 'preview');
+ }
+ }
+
+ await approve({
+ isApproved: isCreationApproved,
+ question: `${application.displayName} is not registered. Register it and install it on ${target.apiUrl}?`,
+ code: 'CREATE_REQUIRED',
+ message: `${application.displayName} has no registration yet. Applying it would create one.`,
+ hint: 'Run twenty app apply --create to register it and install it in this workspace.',
+ });
+
+ output.progress('Registering the app…');
+ await runPhase('registration', () =>
+ registerApp({ application, target, signal }),
+ );
+ output.progress('Installing the development app…');
+ await runPhase('installation', () =>
+ installDevelopmentApp({ application, target, signal }),
+ );
+ output.progress('Requesting a preview…');
+
+ return {
+ actions: await runPhase('preview', preview),
+ isRegistrationCreated: true,
+ };
+ };
+
+ const snapshotDirectory = resolveSnapshotDirectory({
+ build,
+ appPath,
+ });
+
+ output.progress(`Requesting a fresh preview from ${target.apiUrl}…`);
+
+ const { actions, isRegistrationCreated } = await previewOrBootstrap();
+ const summary = getAppPlanSummary(actions);
+
+ if (outputMode === 'human') {
+ output.progress(
+ formatAppPlanActions({
+ actions,
+ summary,
+ inferDeletionFromMissingEntities,
+ stream: process.stderr,
+ }),
+ );
+ }
+
+ if (summary.destructive > 0) {
+ const deletionLabel =
+ summary.destructive === 1
+ ? 'object or field deletion that permanently deletes'
+ : 'object or field deletions that permanently delete';
+
+ await approve({
+ isApproved: isDeletionApproved,
+ question: `Apply ${summary.destructive} ${deletionLabel} stored data on ${target.apiUrl}?`,
+ code: 'CONFIRMATION_REQUIRED',
+ message: `The preview includes ${summary.destructive} ${deletionLabel} stored data.`,
+ hint: 'Review it with twenty app plan, then pass --yes to apply it, or --no-delete to keep entities missing from source.',
+ });
+ }
+
+ if (!isRegistrationCreated) {
+ await runPhase('installation', () =>
+ installDevelopmentApp({ application, target, signal }),
+ );
+ }
+
+ output.progress(
+ `Uploading ${build.files.length} ${build.files.length === 1 ? 'file' : 'files'}…`,
+ );
+ await runPhase('upload', () =>
+ uploadAppFiles({
+ build,
+ snapshotDirectory,
+ target,
+ signal,
+ progress: upload,
+ }),
+ );
+ output.progress('Synchronizing the app…');
+
+ const { actions: appliedActions, acknowledgedUniversalIdentifier } =
+ await runPhase('sync', () =>
+ syncAppManifest({
+ build,
+ inferDeletionFromMissingEntities,
+ target,
+ signal,
+ }),
+ );
+
+ return {
+ completedPhases,
+ isRegistrationCreated,
+ appliedActions,
+ acknowledgedUniversalIdentifier,
+ upload,
+ };
+};
diff --git a/packages/twenty-cli/src/app/deployment/constants/app-apply.constant.ts b/packages/twenty-cli/src/app/deployment/constants/app-apply.constant.ts
new file mode 100644
index 00000000000..fc56299ed98
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/constants/app-apply.constant.ts
@@ -0,0 +1,4 @@
+export const APP_APPLY = {
+ UPLOAD_CONCURRENCY: 4,
+ UPLOAD_TIMEOUT_MILLISECONDS: 300_000,
+} as const;
diff --git a/packages/twenty-cli/src/app/deployment/constants/upload-file-folder-by-artifact-role.constant.ts b/packages/twenty-cli/src/app/deployment/constants/upload-file-folder-by-artifact-role.constant.ts
new file mode 100644
index 00000000000..b9b2723fcd5
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/constants/upload-file-folder-by-artifact-role.constant.ts
@@ -0,0 +1,11 @@
+import { type MetadataSchema } from 'twenty-client-sdk/metadata';
+
+export const UPLOAD_FILE_FOLDER_BY_ARTIFACT_ROLE: Partial<
+ Record<string, MetadataSchema.FileFolder>
+> = {
+ 'built-logic-function': 'BuiltLogicFunction',
+ 'built-front-component': 'BuiltFrontComponent',
+ source: 'Source',
+ dependencies: 'Dependencies',
+ 'public-asset': 'PublicAsset',
+};
diff --git a/packages/twenty-cli/src/app/deployment/create-apply-failure.ts b/packages/twenty-cli/src/app/deployment/create-apply-failure.ts
new file mode 100644
index 00000000000..a3c8b64c0ef
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/create-apply-failure.ts
@@ -0,0 +1,88 @@
+import {
+ type AppApplyOutcome,
+ type AppApplyPhase,
+} from '@/app/deployment/types/app-apply-phase.type';
+import { type AppUploadProgress } from '@/app/deployment/types/app-upload-progress.type';
+import { withPhaseDetails } from '@/app/deployment/with-phase-details';
+import { toCliError } from '@/output/to-cli-error';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+
+const REJECTED_BEFORE_EXECUTION_CODES = new Set<CliErrorCode>([
+ 'AUTH_REQUIRED',
+ 'PERMISSION_DENIED',
+]);
+
+const LOCAL_FAILURE_CODES = new Set<CliErrorCode>([
+ 'SNAPSHOT_INVALID',
+ 'TOOLING_UNSUPPORTED',
+]);
+
+const getOutcome = ({
+ phase,
+ code,
+ upload,
+}: {
+ phase: AppApplyPhase;
+ code: CliErrorCode;
+ upload: AppUploadProgress;
+}): AppApplyOutcome => {
+ if (phase === 'build' || phase === 'preview' || phase === 'confirmation') {
+ return 'not-started';
+ }
+
+ if (phase === 'upload' && upload.fileCount > 0) {
+ return 'partial';
+ }
+
+ if (phase === 'upload' && upload.hasCreatedTargets) {
+ return 'unknown';
+ }
+
+ if (
+ REJECTED_BEFORE_EXECUTION_CODES.has(code) ||
+ LOCAL_FAILURE_CODES.has(code)
+ ) {
+ return 'not-started';
+ }
+
+ return 'unknown';
+};
+
+const getRecoveryHint = ({
+ phase,
+ outcome,
+}: {
+ phase: AppApplyPhase;
+ outcome: AppApplyOutcome;
+}) => {
+ if (outcome === 'not-started') {
+ return 'Fix the problem, then run twenty app apply again. It builds and previews from scratch.';
+ }
+
+ return `The ${phase} step may have changed the workspace. Run twenty app plan to see where it stands before applying again.`;
+};
+
+export const createApplyFailure = ({
+ error,
+ phase,
+ completedPhases,
+ upload,
+ signal,
+}: {
+ error: unknown;
+ phase: AppApplyPhase;
+ completedPhases: AppApplyPhase[];
+ upload: AppUploadProgress;
+ signal: AbortSignal;
+}) => {
+ const cliError = toCliError(error, signal);
+ const outcome = getOutcome({ phase, code: cliError.code, upload });
+
+ return withPhaseDetails({
+ error: cliError,
+ phase,
+ outcome,
+ completedPhases,
+ hint: getRecoveryHint({ phase, outcome }),
+ });
+};
diff --git a/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts b/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts
new file mode 100644
index 00000000000..22de5d6af7d
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts
@@ -0,0 +1,61 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type AppApplyPhase } from '@/app/deployment/types/app-apply-phase.type';
+import { withPhaseDetails } from '@/app/deployment/with-phase-details';
+import { CliError } from '@/output/cli-error';
+import { toCliError } from '@/output/to-cli-error';
+
+type PostSyncPhase = Extract<AppApplyPhase, 'pullBase' | 'clientGeneration'>;
+
+const POST_SYNC_STEPS: Record<
+ PostSyncPhase,
+ { cancelledMessage: string; failedMessage: string; hint: string }
+> = {
+ pullBase: {
+ cancelledMessage: 'recording its pull base was cancelled',
+ failedMessage: 'its pull base was not recorded',
+ hint: 'The workspace already has this version of the app. Any previous pull base was kept. The typed API client was not regenerated. Review twenty app plan before retrying twenty app apply, which repeats the sync before recording the base and regenerating the client.',
+ },
+ clientGeneration: {
+ cancelledMessage: 'generating its typed API client was cancelled',
+ failedMessage: 'its typed API client was not regenerated',
+ hint: 'The workspace already has this version of the app, but the client files in node_modules/twenty-client-sdk may be incomplete. Fix the problem, then run twenty app apply again: it repeats the preview, upload and sync before regenerating the client. twenty app plan shows what that sync would change.',
+ },
+};
+
+export const createPostSyncFailure = ({
+ error,
+ phase,
+ applicationName,
+ apiUrl,
+ completedPhases,
+ signal,
+}: {
+ error: unknown;
+ phase: PostSyncPhase;
+ applicationName: string;
+ apiUrl: string;
+ completedPhases: AppApplyPhase[];
+ signal: AbortSignal;
+}) => {
+ const cliError = toCliError(error, signal);
+ const step = POST_SYNC_STEPS[phase];
+ const message =
+ cliError.code === 'CANCELLED'
+ ? `${applicationName} was applied to ${apiUrl}, but ${step.cancelledMessage}.`
+ : `${applicationName} was applied to ${apiUrl}, but ${step.failedMessage}: ${cliError.message}`;
+
+ return withPhaseDetails({
+ error: new CliError({
+ code: cliError.code,
+ exitCode: cliError.exitCode,
+ message,
+ hint: [step.hint, cliError.hint].filter(isNonEmptyString).join(' '),
+ details: cliError.details,
+ }),
+ phase,
+ outcome: 'applied',
+ completedPhases,
+ hint: step.hint,
+ });
+};
diff --git a/packages/twenty-cli/src/app/deployment/create-uninstall-failure.ts b/packages/twenty-cli/src/app/deployment/create-uninstall-failure.ts
new file mode 100644
index 00000000000..ec5fe1b60fb
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/create-uninstall-failure.ts
@@ -0,0 +1,56 @@
+import {
+ type AppUninstallOutcome,
+ type AppUninstallPhase,
+} from '@/app/deployment/types/app-uninstall-phase.type';
+import { withPhaseDetails } from '@/app/deployment/with-phase-details';
+import { toCliError } from '@/output/to-cli-error';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+
+const REJECTED_BEFORE_UNINSTALL_CODES = new Set<CliErrorCode>([
+ 'AUTH_REQUIRED',
+ 'PERMISSION_DENIED',
+]);
+
+const getRecoveryHint = ({
+ code,
+ outcome,
+}: {
+ code: CliErrorCode;
+ outcome: AppUninstallOutcome;
+}) => {
+ if (outcome === 'unknown') {
+ return 'The uninstall may have partly run. Run twenty app uninstall again: it reports APP_NOT_INSTALLED once the app is gone.';
+ }
+
+ if (code === 'APP_NOT_INSTALLED') {
+ return 'Nothing was uninstalled. Check the target workspace and the universal identifier.';
+ }
+
+ return 'Fix the problem, then run twenty app uninstall again.';
+};
+
+export const createUninstallFailure = ({
+ error,
+ phase,
+ completedPhases,
+ signal,
+}: {
+ error: unknown;
+ phase: AppUninstallPhase;
+ completedPhases: AppUninstallPhase[];
+ signal: AbortSignal;
+}) => {
+ const cliError = toCliError(error, signal);
+ const outcome: AppUninstallOutcome =
+ phase !== 'uninstall' || REJECTED_BEFORE_UNINSTALL_CODES.has(cliError.code)
+ ? 'not-started'
+ : 'unknown';
+
+ return withPhaseDetails({
+ error: cliError,
+ phase,
+ outcome,
+ completedPhases,
+ hint: getRecoveryHint({ code: cliError.code, outcome }),
+ });
+};
diff --git a/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts b/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts
new file mode 100644
index 00000000000..1bcde99a9e2
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts
@@ -0,0 +1,83 @@
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { parseAppPlan } from '@/app/deployment/parse-app-plan';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchAppPlan = async ({
+ build,
+ inferDeletionFromMissingEntities,
+ target,
+ signal,
+}: {
+ build: ToolingBuild;
+ inferDeletionFromMissingEntities: boolean;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ if (
+ build.manifestFormat !== 'twenty-application' ||
+ !isPlainObject(build.manifest.application) ||
+ build.manifest.application.universalIdentifier !==
+ build.application.universalIdentifier
+ ) {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message: 'This CLI cannot preview the manifest returned by the SDK.',
+ });
+ }
+
+ try {
+ const data = await createMetadataClient({ target, signal }).mutation({
+ __name: 'PreviewApplication',
+ syncApplication: {
+ __args: {
+ manifest: build.manifest,
+ dryRun: true,
+ inferDeletionFromMissingEntities,
+ },
+ applicationUniversalIdentifier: true,
+ actions: true,
+ },
+ });
+
+ return parseAppPlan({
+ value: data?.syncApplication,
+ applicationUniversalIdentifier: build.application.universalIdentifier,
+ });
+ } catch (error) {
+ if (
+ error instanceof CliError &&
+ isApplicationNotFoundError({ error, field: 'syncApplication' })
+ ) {
+ throw new CliError({
+ code: 'PLAN_UNAVAILABLE',
+ message:
+ 'This app needs an owned registration before the server can preview it. Nothing was registered, uploaded or synchronized.',
+ hint: 'Run twenty app apply --create to register it and install it in this workspace.',
+ details: {
+ ...error.details,
+ body: undefined,
+ data: null,
+ applicationUniversalIdentifier: build.application.universalIdentifier,
+ plan: true,
+ },
+ });
+ }
+
+ if (error instanceof CliError && isPlainObject(error.details)) {
+ throw new CliError({
+ code: error.code,
+ exitCode: error.exitCode,
+ message: error.message,
+ hint: error.hint,
+ details: { ...error.details, body: undefined, data: null },
+ });
+ }
+
+ throw error;
+ }
+};
diff --git a/packages/twenty-cli/src/app/deployment/format-app-plan.ts b/packages/twenty-cli/src/app/deployment/format-app-plan.ts
new file mode 100644
index 00000000000..cd13381129f
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/format-app-plan.ts
@@ -0,0 +1,282 @@
+import { isBoolean, isNumber, isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { isDestructiveAppPlanAction } from '@/app/deployment/is-destructive-app-plan-action';
+import {
+ type AppPlanAction,
+ type AppPlanSummary,
+} from '@/app/deployment/types/app-plan.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { boldText, colorText, dimText } from '@/output/style';
+
+const MAX_VALUE_LENGTH = 80;
+
+const MASKED_VALUE = '(secret)';
+
+const NO_DELETE_HINT =
+ 'Entities missing from your source are destroyed by default. Re-run with --no-delete to keep them.';
+
+const DENIED_ATTRIBUTE_KEYS = new Set([
+ 'id',
+ 'createdAt',
+ 'updatedAt',
+ 'deletedAt',
+ 'universalIdentifier',
+ '__typename',
+]);
+
+const ACTION_TYPE_ORDER = { create: 0, update: 1, delete: 2 } as const;
+
+const SIGN_BY_TYPE = { create: '+', update: '~', delete: '-' } as const;
+
+const COLOR_BY_TYPE = {
+ create: 'green',
+ update: 'yellow',
+ delete: 'red',
+} as const;
+
+const VERB_BY_TYPE = {
+ create: 'will be created',
+ update: 'will be updated in-place',
+ delete: 'will be destroyed',
+} as const;
+
+const formatPlanValue = (value: unknown): string => {
+ if (!isDefined(value)) {
+ return 'null';
+ }
+
+ if (isBoolean(value) || isNumber(value)) {
+ return String(value);
+ }
+
+ const text = (JSON.stringify(value) ?? String(value)).replace(
+ /[\x7f-\x9f]/g,
+ (character) =>
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,
+ );
+
+ return text.length > MAX_VALUE_LENGTH
+ ? `${text.slice(0, MAX_VALUE_LENGTH - 1)}…`
+ : text;
+};
+
+const isApplicationVariableSecret = (action: AppPlanAction) => {
+ const fromFlatEntity = action.flatEntity?.isSecret;
+
+ if (isBoolean(fromFlatEntity)) {
+ return fromFlatEntity;
+ }
+
+ const fromDiff = action.diff?.isSecret?.after;
+
+ return isBoolean(fromDiff) ? fromDiff : undefined;
+};
+
+const shouldMaskValue = (action: AppPlanAction, key: string) =>
+ action.metadataName === 'applicationVariable' &&
+ key === 'value' &&
+ isApplicationVariableSecret(action) !== false;
+
+const selectEntityAttributes = (flatEntity: AppPlanAction['flatEntity']) =>
+ Object.entries(flatEntity ?? {})
+ .filter(
+ ([key, value]) =>
+ !DENIED_ATTRIBUTE_KEYS.has(key) &&
+ !key.endsWith('Id') &&
+ isDefined(value),
+ )
+ .sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
+
+const getActionEntityName = (action: AppPlanAction) =>
+ [
+ action.flatEntity?.name,
+ action.flatEntity?.nameSingular,
+ action.flatEntity?.universalIdentifier,
+ ].find(isString) ??
+ (action.type === 'create'
+ ? 'unknown'
+ : (action.universalIdentifier ?? 'unknown'));
+
+const sortActions = (actions: AppPlanAction[]) => {
+ const firstPositionByMetadataName = new Map<string, number>();
+
+ actions.forEach((action, position) => {
+ if (!firstPositionByMetadataName.has(action.metadataName)) {
+ firstPositionByMetadataName.set(action.metadataName, position);
+ }
+ });
+
+ return [...actions].sort(
+ (actionA, actionB) =>
+ (firstPositionByMetadataName.get(actionA.metadataName) ?? 0) -
+ (firstPositionByMetadataName.get(actionB.metadataName) ?? 0) ||
+ ACTION_TYPE_ORDER[actionA.type] - ACTION_TYPE_ORDER[actionB.type] ||
+ getActionEntityName(actionA).localeCompare(getActionEntityName(actionB)),
+ );
+};
+
+const formatBlockHeader = (action: AppPlanAction, stream: NodeJS.WriteStream) =>
+ boldText(
+ ` # ${formatDataValue(action.metadataName)} ${formatPlanValue(getActionEntityName(action))} ${VERB_BY_TYPE[action.type]}`,
+ stream,
+ );
+
+const formatEntityAttributeLines = (
+ action: AppPlanAction,
+ stream: NodeJS.WriteStream,
+) => {
+ const entries = selectEntityAttributes(action.flatEntity);
+ const color = COLOR_BY_TYPE[action.type];
+
+ if (entries.length === 0) {
+ return [
+ action.type === 'delete'
+ ? colorText(
+ color,
+ ` - name = ${formatPlanValue(getActionEntityName(action))}`,
+ stream,
+ )
+ : colorText(color, ' + (no attributes to display)', stream),
+ ];
+ }
+
+ const padding = Math.max(...entries.map(([key]) => key.length));
+
+ return entries.map(([key, value]) =>
+ colorText(
+ color,
+ ` ${SIGN_BY_TYPE[action.type]} ${key.padEnd(padding)} = ${
+ shouldMaskValue(action, key) ? MASKED_VALUE : formatPlanValue(value)
+ }`,
+ stream,
+ ),
+ );
+};
+
+const formatUpdateAttributeLines = (
+ action: AppPlanAction,
+ stream: NodeJS.WriteStream,
+) => {
+ const keys = Object.keys(action.diff ?? {}).sort((keyA, keyB) =>
+ keyA.localeCompare(keyB),
+ );
+
+ if (keys.length === 0) {
+ return [];
+ }
+
+ const padding = Math.max(...keys.map((key) => key.length));
+
+ return keys.map((key) => {
+ const change = action.diff?.[key];
+ const masked = shouldMaskValue(action, key);
+ const before = masked ? MASKED_VALUE : formatPlanValue(change?.before);
+ const after = masked ? MASKED_VALUE : formatPlanValue(change?.after);
+
+ return ` ${colorText('yellow', '~', stream)} ${colorText('yellow', key.padEnd(padding), stream)} = ${colorText('red', before, stream)} ${dimText('->', stream)} ${colorText('green', after, stream)}`;
+ });
+};
+
+const formatBlock = (action: AppPlanAction, stream: NodeJS.WriteStream) => {
+ const attributeLines =
+ action.type === 'update'
+ ? formatUpdateAttributeLines(action, stream)
+ : formatEntityAttributeLines(action, stream);
+
+ return action.type === 'update' && attributeLines.length === 0
+ ? undefined
+ : [formatBlockHeader(action, stream), ...attributeLines].join('\n');
+};
+
+const formatDestructiveWarning = (
+ actions: AppPlanAction[],
+ stream: NodeJS.WriteStream,
+) => {
+ const destructiveActions = actions.filter(isDestructiveAppPlanAction);
+
+ return [
+ boldText(
+ colorText(
+ 'red',
+ `Warning: ${destructiveActions.length} destructive change(s) will permanently delete data.`,
+ stream,
+ ),
+ stream,
+ ),
+ ...destructiveActions.map((action) =>
+ colorText(
+ 'red',
+ ` - ${formatDataValue(action.metadataName)} ${formatPlanValue(getActionEntityName(action))}: ${
+ action.metadataName === 'objectMetadata'
+ ? 'drops the table and all its rows'
+ : 'drops the column and its data'
+ }`,
+ stream,
+ ),
+ ),
+ colorText(
+ 'red',
+ 'Destroys are irreversible. Review carefully before applying.',
+ stream,
+ ),
+ ].join('\n');
+};
+
+export const formatAppPlanActions = ({
+ actions,
+ summary,
+ inferDeletionFromMissingEntities,
+ stream = process.stdout,
+}: {
+ actions: AppPlanAction[];
+ summary: AppPlanSummary;
+ inferDeletionFromMissingEntities: boolean;
+ stream?: NodeJS.WriteStream;
+}) => {
+ if (actions.length === 0) {
+ return 'No changes. Twenty metadata matches your manifest.';
+ }
+
+ const blocks = sortActions(actions)
+ .map((action) => formatBlock(action, stream))
+ .filter(isDefined);
+
+ return [
+ boldText('Twenty will perform the following actions:', stream),
+ '',
+ blocks.join('\n\n'),
+ '',
+ `Plan: ${colorText('green', `${summary.create} to add`, stream)}, ${colorText('yellow', `${summary.update} to change`, stream)}, ${colorText('red', `${summary.delete} to destroy`, stream)}.`,
+ ...(inferDeletionFromMissingEntities && summary.delete > 0
+ ? [dimText(NO_DELETE_HINT, stream)]
+ : []),
+ ...(summary.destructive > 0
+ ? ['', formatDestructiveWarning(actions, stream)]
+ : []),
+ ].join('\n');
+};
+
+export const formatAppPlan = ({
+ applicationName,
+ apiUrl,
+ actions,
+ summary,
+ inferDeletionFromMissingEntities,
+}: {
+ applicationName: string;
+ apiUrl: string;
+ actions: AppPlanAction[];
+ summary: AppPlanSummary;
+ inferDeletionFromMissingEntities: boolean;
+}) =>
+ [
+ `Plan for ${formatDataValue(applicationName)} on ${apiUrl}`,
+ formatAppPlanActions({
+ actions,
+ summary,
+ inferDeletionFromMissingEntities,
+ }),
+ 'Use --json for complete action details.',
+ 'Nothing was registered, uploaded or synchronized. The server may return different actions when you apply.',
+ ].join('\n\n');
diff --git a/packages/twenty-cli/src/app/deployment/format-apply-summary.ts b/packages/twenty-cli/src/app/deployment/format-apply-summary.ts
new file mode 100644
index 00000000000..c066651d674
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/format-apply-summary.ts
@@ -0,0 +1,48 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { formatBytes, isDefined } from 'twenty-shared/utils';
+
+import { formatAppDuration } from '@/app/format-app-duration';
+import { type AppPlanSummary } from '@/app/deployment/types/app-plan.type';
+import { type AppUploadProgress } from '@/app/deployment/types/app-upload-progress.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { dimText, formatSuccessLine } from '@/output/style';
+
+export const formatApplySummary = ({
+ applicationName,
+ apiUrl,
+ summary,
+ upload,
+ isRegistrationCreated,
+ clientGeneration,
+ durationMilliseconds,
+}: {
+ applicationName: string;
+ apiUrl: string;
+ summary: AppPlanSummary | undefined;
+ upload: AppUploadProgress;
+ isRegistrationCreated: boolean;
+ clientGeneration: 'generated' | 'skipped';
+ durationMilliseconds: number;
+}) => {
+ const changes = isDefined(summary)
+ ? `${summary.create} added · ${summary.update} changed · ${summary.delete} deleted`
+ : 'changes not reported';
+ const fileLabel = upload.fileCount === 1 ? 'file' : 'files';
+
+ return [
+ formatSuccessLine(
+ `Applied ${formatDataValue(applicationName)} to ${apiUrl} ${dimText(`in ${formatAppDuration(durationMilliseconds)}`)}`,
+ ),
+ dimText(
+ ` ${changes} · ${upload.fileCount} ${fileLabel} uploaded (${formatBytes(upload.byteCount)})`,
+ ),
+ isRegistrationCreated
+ ? dimText(' Registered the app and installed it in this workspace.')
+ : '',
+ clientGeneration === 'generated'
+ ? dimText(' Regenerated the typed API client.')
+ : '',
+ ]
+ .filter(isNonEmptyString)
+ .join('\n');
+};
diff --git a/packages/twenty-cli/src/app/deployment/get-app-plan-summary.ts b/packages/twenty-cli/src/app/deployment/get-app-plan-summary.ts
new file mode 100644
index 00000000000..09b4b0efa51
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/get-app-plan-summary.ts
@@ -0,0 +1,19 @@
+import { isDestructiveAppPlanAction } from '@/app/deployment/is-destructive-app-plan-action';
+import {
+ type AppPlanAction,
+ type AppPlanSummary,
+} from '@/app/deployment/types/app-plan.type';
+
+export const getAppPlanSummary = (actions: AppPlanAction[]): AppPlanSummary => {
+ const summary = { create: 0, update: 0, delete: 0, destructive: 0 };
+
+ for (const action of actions) {
+ summary[action.type] += 1;
+
+ if (isDestructiveAppPlanAction(action)) {
+ summary.destructive += 1;
+ }
+ }
+
+ return summary;
+};
diff --git a/packages/twenty-cli/src/app/deployment/install-development-app.ts b/packages/twenty-cli/src/app/deployment/install-development-app.ts
new file mode 100644
index 00000000000..f6d2081e749
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/install-development-app.ts
@@ -0,0 +1,47 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const installDevelopmentApp = async ({
+ application,
+ target,
+ signal,
+}: {
+ application: ToolingBuild['application'];
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const data = await createMetadataClient({ target, signal }).mutation({
+ __name: 'InstallDevelopmentApplication',
+ createDevelopmentApplication: {
+ __args: {
+ universalIdentifier: application.universalIdentifier,
+ name: application.displayName,
+ },
+ id: true,
+ universalIdentifier: true,
+ },
+ });
+ const installation = data?.createDevelopmentApplication;
+
+ if (
+ !isPlainObject(installation) ||
+ !isNonEmptyString(installation.id) ||
+ !isSameUniversalIdentifier({
+ value: installation.universalIdentifier,
+ universalIdentifier: application.universalIdentifier,
+ })
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid development installation.',
+ });
+ }
+
+ return { applicationId: installation.id };
+};
diff --git a/packages/twenty-cli/src/app/deployment/is-destructive-app-plan-action.ts b/packages/twenty-cli/src/app/deployment/is-destructive-app-plan-action.ts
new file mode 100644
index 00000000000..d95ddf9133c
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/is-destructive-app-plan-action.ts
@@ -0,0 +1,6 @@
+import { type AppPlanAction } from '@/app/deployment/types/app-plan.type';
+
+export const isDestructiveAppPlanAction = (action: AppPlanAction) =>
+ action.type === 'delete' &&
+ (action.metadataName === 'objectMetadata' ||
+ action.metadataName === 'fieldMetadata');
diff --git a/packages/twenty-cli/src/app/deployment/parse-app-plan.ts b/packages/twenty-cli/src/app/deployment/parse-app-plan.ts
new file mode 100644
index 00000000000..cee994f1b04
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/parse-app-plan.ts
@@ -0,0 +1,76 @@
+import { isArray, isNonEmptyString, isUndefined } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { type AppPlanAction } from '@/app/deployment/types/app-plan.type';
+import { CliError } from '@/output/cli-error';
+import { RESULT_ITEM_LIMIT } from '@/transport/constants/result-item-limit.constant';
+
+const isAction = (value: unknown): value is AppPlanAction =>
+ isPlainObject(value) &&
+ (value.type === 'create' ||
+ value.type === 'update' ||
+ value.type === 'delete') &&
+ isNonEmptyString(value.metadataName) &&
+ (value.type === 'create'
+ ? isUndefined(value.universalIdentifier) ||
+ isNonEmptyString(value.universalIdentifier)
+ : isNonEmptyString(value.universalIdentifier)) &&
+ (isUndefined(value.flatEntity) || isPlainObject(value.flatEntity)) &&
+ (isUndefined(value.diff) ||
+ (isPlainObject(value.diff) &&
+ Object.values(value.diff).every(isPlainObject)));
+
+const redactVariableValues = (action: AppPlanAction): AppPlanAction => {
+ if (action.metadataName !== 'applicationVariable') {
+ return action;
+ }
+
+ return {
+ ...action,
+ ...(isDefined(action.flatEntity) && 'value' in action.flatEntity
+ ? { flatEntity: { ...action.flatEntity, value: '(redacted)' } }
+ : {}),
+ ...(isDefined(action.diff) && 'value' in action.diff
+ ? {
+ diff: {
+ ...action.diff,
+ value: { before: '(redacted)', after: '(redacted)' },
+ },
+ }
+ : {}),
+ };
+};
+
+export const parseAppPlan = ({
+ value,
+ applicationUniversalIdentifier,
+}: {
+ value: unknown;
+ applicationUniversalIdentifier: string;
+}) => {
+ if (
+ !isPlainObject(value) ||
+ !isSameUniversalIdentifier({
+ value: value.applicationUniversalIdentifier,
+ universalIdentifier: applicationUniversalIdentifier,
+ }) ||
+ !isArray(value.actions) ||
+ !value.actions.every(isAction)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid application plan.',
+ });
+ }
+
+ if (value.actions.length > RESULT_ITEM_LIMIT) {
+ throw new CliError({
+ code: 'RESPONSE_LIMIT_EXCEEDED',
+ message: `The application plan exceeds ${RESULT_ITEM_LIMIT} actions.`,
+ hint: 'Reduce the app changes before requesting another preview.',
+ });
+ }
+
+ return value.actions.map(redactVariableValues);
+};
diff --git a/packages/twenty-cli/src/app/deployment/put-upload-file.ts b/packages/twenty-cli/src/app/deployment/put-upload-file.ts
new file mode 100644
index 00000000000..8b994d66f97
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/put-upload-file.ts
@@ -0,0 +1,42 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { APP_APPLY } from '@/app/deployment/constants/app-apply.constant';
+import { CliError } from '@/output/cli-error';
+import { API_URL_PROTOCOLS } from '@/target/constants/api-url-protocols.constant';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+
+export const putUploadFile = async ({
+ uploadUrl,
+ contentType,
+ bytes,
+ signal,
+}: {
+ uploadUrl: string;
+ contentType: string;
+ bytes: Blob | Uint8Array<ArrayBuffer>;
+ signal: AbortSignal;
+}) => {
+ const url = URL.parse(uploadUrl);
+
+ if (!isDefined(url) || !API_URL_PROTOCOLS.includes(url.protocol)) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an upload URL the CLI cannot use.',
+ });
+ }
+
+ const response = await fetchWithProxy(url, {
+ method: 'PUT',
+ headers: { 'Content-Type': contentType },
+ body: bytes,
+ redirect: 'manual',
+ signal: AbortSignal.any([
+ signal,
+ AbortSignal.timeout(APP_APPLY.UPLOAD_TIMEOUT_MILLISECONDS),
+ ]),
+ });
+
+ await response.body?.cancel().catch(() => undefined);
+
+ return response.status;
+};
diff --git a/packages/twenty-cli/src/app/deployment/read-snapshot-file.ts b/packages/twenty-cli/src/app/deployment/read-snapshot-file.ts
new file mode 100644
index 00000000000..340805790e1
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/read-snapshot-file.ts
@@ -0,0 +1,68 @@
+import { createHash } from 'node:crypto';
+import { openAsBlob } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { type ToolingArtifact } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { isInsideDirectory } from '@/utils/is-inside-directory';
+import { readBlobChunks } from '@/utils/read-blob-chunks';
+
+const createSnapshotInvalidError = ({
+ message,
+ path,
+}: {
+ message: string;
+ path: string;
+}) =>
+ new CliError({
+ code: 'SNAPSHOT_INVALID',
+ message,
+ hint: 'Build again. If it keeps happening, check that nothing else writes to the snapshot directory.',
+ details: { path },
+ });
+
+export const readSnapshotFile = async ({
+ snapshotDirectory,
+ artifact,
+}: {
+ snapshotDirectory: string;
+ artifact: ToolingArtifact;
+}) => {
+ const filePath = resolve(snapshotDirectory, artifact.path);
+
+ if (!isInsideDirectory({ filePath, directory: snapshotDirectory })) {
+ throw createSnapshotInvalidError({
+ message: `The build lists a file outside its snapshot: ${artifact.path}`,
+ path: artifact.path,
+ });
+ }
+
+ const bytes = await openAsBlob(filePath);
+ const hash = createHash('sha256');
+
+ try {
+ for await (const chunk of readBlobChunks(bytes)) {
+ hash.update(chunk);
+ }
+ } catch (error) {
+ if (error instanceof DOMException && error.name === 'NotReadableError') {
+ throw createSnapshotInvalidError({
+ message: `${artifact.path} changed after the build.`,
+ path: artifact.path,
+ });
+ }
+
+ throw error;
+ }
+
+ const sha256 = hash.digest('hex');
+
+ if (bytes.size !== artifact.size || sha256 !== artifact.sha256) {
+ throw createSnapshotInvalidError({
+ message: `${artifact.path} changed after the build.`,
+ path: artifact.path,
+ });
+ }
+
+ return bytes;
+};
diff --git a/packages/twenty-cli/src/app/deployment/register-app.ts b/packages/twenty-cli/src/app/deployment/register-app.ts
new file mode 100644
index 00000000000..3dbf96dd228
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/register-app.ts
@@ -0,0 +1,51 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const registerApp = async ({
+ application,
+ target,
+ signal,
+}: {
+ application: ToolingBuild['application'];
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const data = await createMetadataClient({ target, signal }).mutation({
+ __name: 'RegisterApplication',
+ createApplicationRegistration: {
+ __args: {
+ input: {
+ name: application.displayName,
+ universalIdentifier: application.universalIdentifier,
+ },
+ },
+ applicationRegistration: { id: true, universalIdentifier: true },
+ },
+ });
+ const created = data?.createApplicationRegistration;
+ const registration = isPlainObject(created)
+ ? created.applicationRegistration
+ : undefined;
+
+ if (
+ !isPlainObject(registration) ||
+ !isNonEmptyString(registration.id) ||
+ !isSameUniversalIdentifier({
+ value: registration.universalIdentifier,
+ universalIdentifier: application.universalIdentifier,
+ })
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid application registration.',
+ });
+ }
+
+ return { registrationId: registration.id };
+};
diff --git a/packages/twenty-cli/src/app/deployment/require-approval.ts b/packages/twenty-cli/src/app/deployment/require-approval.ts
new file mode 100644
index 00000000000..a59144dbd89
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/require-approval.ts
@@ -0,0 +1,40 @@
+import { confirmInTerminal } from '@/input/confirm-in-terminal';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+
+export const requireApproval = async ({
+ isApproved,
+ canPrompt,
+ question,
+ code,
+ message,
+ hint,
+ declinedMessage,
+ signal,
+}: {
+ isApproved: boolean;
+ canPrompt: boolean;
+ question: string;
+ code: CliErrorCode;
+ message: string;
+ hint: string;
+ declinedMessage: string;
+ signal: AbortSignal;
+}) => {
+ if (isApproved) {
+ return;
+ }
+
+ if (!canPrompt) {
+ throw new CliError({ code, exitCode: EXIT_CODE.USAGE, message, hint });
+ }
+
+ if (!(await confirmInTerminal({ question, signal }))) {
+ throw new CliError({
+ code: 'CONFIRMATION_DECLINED',
+ exitCode: EXIT_CODE.USAGE,
+ message: declinedMessage,
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/deployment/resolve-snapshot-directory.ts b/packages/twenty-cli/src/app/deployment/resolve-snapshot-directory.ts
new file mode 100644
index 00000000000..918901458b4
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/resolve-snapshot-directory.ts
@@ -0,0 +1,38 @@
+import { join } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { isInsideDirectory } from '@/utils/is-inside-directory';
+
+export const resolveSnapshotDirectory = ({
+ build,
+ appPath,
+}: {
+ build: ToolingBuild;
+ appPath: string;
+}) => {
+ if (!isDefined(build.directory)) {
+ throw new CliError({
+ code: 'SNAPSHOT_INVALID',
+ message:
+ 'The build did not report its snapshot directory, so the CLI cannot upload it.',
+ });
+ }
+
+ if (
+ !isInsideDirectory({
+ filePath: build.directory,
+ directory: join(appPath, '.twenty', 'cli', 'snapshots'),
+ })
+ ) {
+ throw new CliError({
+ code: 'SNAPSHOT_INVALID',
+ message: `The build snapshot ${build.directory} is outside the app's .twenty/cli/snapshots folder.`,
+ details: { directory: build.directory },
+ });
+ }
+
+ return build.directory;
+};
diff --git a/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts b/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts
new file mode 100644
index 00000000000..ea315adab86
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts
@@ -0,0 +1,93 @@
+import { isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { parseAppPlan } from '@/app/deployment/parse-app-plan';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+const withoutResponseContent = (error: unknown) => {
+ if (!(error instanceof CliError) || !isPlainObject(error.details)) {
+ return error;
+ }
+
+ const { body: _body, ...details } = error.details;
+
+ return new CliError({
+ code: error.code,
+ exitCode: error.exitCode,
+ message: error.message,
+ hint: error.hint,
+ details: { ...details, data: null },
+ });
+};
+
+const readAppliedActions = ({
+ value,
+ applicationUniversalIdentifier,
+}: {
+ value: unknown;
+ applicationUniversalIdentifier: string;
+}) => {
+ try {
+ return parseAppPlan({ value, applicationUniversalIdentifier });
+ } catch (error) {
+ if (error instanceof CliError) {
+ return undefined;
+ }
+
+ throw error;
+ }
+};
+
+export const syncAppManifest = async ({
+ build,
+ inferDeletionFromMissingEntities,
+ target,
+ signal,
+}: {
+ build: ToolingBuild;
+ inferDeletionFromMissingEntities: boolean;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const applicationUniversalIdentifier = build.application.universalIdentifier;
+ const data = await createMetadataClient({ target, signal })
+ .mutation({
+ __name: 'SyncApplication',
+ syncApplication: {
+ __args: { manifest: build.manifest, inferDeletionFromMissingEntities },
+ applicationUniversalIdentifier: true,
+ actions: true,
+ },
+ })
+ .catch((error: unknown) => {
+ throw withoutResponseContent(error);
+ });
+ const acknowledgement = data?.syncApplication;
+
+ if (
+ !isPlainObject(acknowledgement) ||
+ !isString(acknowledgement.applicationUniversalIdentifier) ||
+ !isSameUniversalIdentifier({
+ value: acknowledgement.applicationUniversalIdentifier,
+ universalIdentifier: applicationUniversalIdentifier,
+ })
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `The server did not confirm the sync of ${applicationUniversalIdentifier}.`,
+ });
+ }
+
+ return {
+ actions: readAppliedActions({
+ value: acknowledgement,
+ applicationUniversalIdentifier,
+ }),
+ acknowledgedUniversalIdentifier:
+ acknowledgement.applicationUniversalIdentifier,
+ };
+};
diff --git a/packages/twenty-cli/src/app/deployment/types/app-apply-phase.type.ts b/packages/twenty-cli/src/app/deployment/types/app-apply-phase.type.ts
new file mode 100644
index 00000000000..0b119604282
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/types/app-apply-phase.type.ts
@@ -0,0 +1,12 @@
+export type AppApplyPhase =
+ | 'build'
+ | 'preview'
+ | 'confirmation'
+ | 'registration'
+ | 'installation'
+ | 'upload'
+ | 'sync'
+ | 'pullBase'
+ | 'clientGeneration';
+
+export type AppApplyOutcome = 'not-started' | 'partial' | 'unknown' | 'applied';
diff --git a/packages/twenty-cli/src/app/deployment/types/app-plan.type.ts b/packages/twenty-cli/src/app/deployment/types/app-plan.type.ts
new file mode 100644
index 00000000000..0e5b7d37459
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/types/app-plan.type.ts
@@ -0,0 +1,14 @@
+export type AppPlanAction = {
+ type: 'create' | 'update' | 'delete';
+ metadataName: string;
+ universalIdentifier?: string;
+ flatEntity?: Record<string, unknown>;
+ diff?: Record<string, { before?: unknown; after?: unknown }>;
+};
+
+export type AppPlanSummary = {
+ create: number;
+ update: number;
+ delete: number;
+ destructive: number;
+};
diff --git a/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts b/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts
new file mode 100644
index 00000000000..49e61984213
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts
@@ -0,0 +1,7 @@
+export type AppUninstallPhase =
+ | 'build'
+ | 'check'
+ | 'confirmation'
+ | 'uninstall';
+
+export type AppUninstallOutcome = 'not-started' | 'unknown';
diff --git a/packages/twenty-cli/src/app/deployment/types/app-upload-progress.type.ts b/packages/twenty-cli/src/app/deployment/types/app-upload-progress.type.ts
new file mode 100644
index 00000000000..4658e85b8d0
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/types/app-upload-progress.type.ts
@@ -0,0 +1,5 @@
+export type AppUploadProgress = {
+ fileCount: number;
+ byteCount: number;
+ hasCreatedTargets: boolean;
+};
diff --git a/packages/twenty-cli/src/app/deployment/uninstall-app.ts b/packages/twenty-cli/src/app/deployment/uninstall-app.ts
new file mode 100644
index 00000000000..5585fbe38b5
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/uninstall-app.ts
@@ -0,0 +1,40 @@
+import { createAppNotInstalledError } from '@/app/create-app-not-installed-error';
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const uninstallApp = async ({
+ universalIdentifier,
+ target,
+ signal,
+}: {
+ universalIdentifier: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const data = await createMetadataClient({ target, signal })
+ .mutation({
+ __name: 'UninstallApplication',
+ uninstallApplication: { __args: { universalIdentifier } },
+ })
+ .catch((error: unknown) => {
+ if (
+ isApplicationNotFoundError({ error, field: 'uninstallApplication' })
+ ) {
+ throw createAppNotInstalledError({
+ universalIdentifier,
+ apiUrl: target.apiUrl,
+ });
+ }
+
+ throw error;
+ });
+
+ if (data?.uninstallApplication !== true) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `The server did not confirm the uninstall of ${universalIdentifier}.`,
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/deployment/upload-app-files.ts b/packages/twenty-cli/src/app/deployment/upload-app-files.ts
new file mode 100644
index 00000000000..159dfdd60d0
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/upload-app-files.ts
@@ -0,0 +1,384 @@
+import { isArray, isNonEmptyString } from '@sniptt/guards';
+import { APPLICATION_FILE_UPLOAD_BATCH_SIZE } from 'twenty-shared/application';
+import { isDefined, isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
+
+import { APP_APPLY } from '@/app/deployment/constants/app-apply.constant';
+import { UPLOAD_FILE_FOLDER_BY_ARTIFACT_ROLE } from '@/app/deployment/constants/upload-file-folder-by-artifact-role.constant';
+import { putUploadFile } from '@/app/deployment/put-upload-file';
+import { readSnapshotFile } from '@/app/deployment/read-snapshot-file';
+import { type AppUploadProgress } from '@/app/deployment/types/app-upload-progress.type';
+import {
+ type ToolingArtifact,
+ type ToolingBuild,
+} from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+type UploadTarget = {
+ fileId: string;
+ filePath: string;
+ uploadUrl: string;
+ contentType: string;
+};
+
+type UploadFailure = {
+ path: string;
+ message: string;
+};
+
+type UploadBatchContext = {
+ applicationUniversalIdentifier: string;
+ snapshotDirectory: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ progress: AppUploadProgress;
+};
+
+const createInvalidUploadResponseError = () =>
+ new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid file upload response.',
+ });
+
+const isUploadTarget = (value: unknown): value is UploadTarget =>
+ isPlainObject(value) &&
+ isNonEmptyString(value.fileId) &&
+ isNonEmptyString(value.filePath) &&
+ isNonEmptyString(value.uploadUrl) &&
+ isNonEmptyString(value.contentType);
+
+const readUploadErrors = ({
+ value,
+ idKey,
+}: {
+ value: unknown;
+ idKey: 'filePath' | 'fileId';
+}) => {
+ if (!isArray(value)) {
+ throw createInvalidUploadResponseError();
+ }
+
+ return value.map((entry) => {
+ const id = isPlainObject(entry) ? entry[idKey] : undefined;
+
+ if (!isPlainObject(entry) || !isNonEmptyString(id)) {
+ throw createInvalidUploadResponseError();
+ }
+
+ return {
+ id,
+ message: isNonEmptyString(entry.message)
+ ? entry.message
+ : 'The server refused this file.',
+ };
+ });
+};
+
+const toUploadRequest = (artifact: ToolingArtifact) => {
+ const fileFolder = UPLOAD_FILE_FOLDER_BY_ARTIFACT_ROLE[artifact.role];
+
+ if (!isDefined(fileFolder)) {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message: `The build contains a ${artifact.role} file, which the CLI cannot upload.`,
+ details: { path: artifact.path, role: artifact.role },
+ });
+ }
+
+ return { fileFolder, filePath: artifact.path, size: artifact.size };
+};
+
+const runConcurrently = async <TItem>({
+ items,
+ run,
+}: {
+ items: TItem[];
+ run: (item: TItem) => Promise<void>;
+}) => {
+ let nextIndex = 0;
+ let firstFailure: { error: unknown } | undefined;
+
+ const runNext = async (): Promise<void> => {
+ if (nextIndex >= items.length || isDefined(firstFailure)) {
+ return;
+ }
+
+ const item = items[nextIndex];
+
+ nextIndex += 1;
+
+ try {
+ await run(item);
+ } catch (error) {
+ firstFailure ??= { error };
+ }
+
+ await runNext();
+ };
+
+ await Promise.all(
+ Array.from(
+ { length: Math.min(APP_APPLY.UPLOAD_CONCURRENCY, items.length) },
+ runNext,
+ ),
+ );
+
+ if (isDefined(firstFailure)) {
+ throw firstFailure.error;
+ }
+};
+
+const requestUploadTargets = async ({
+ artifacts,
+ context,
+}: {
+ artifacts: ToolingArtifact[];
+ context: UploadBatchContext;
+}) => {
+ const data = await createMetadataClient({
+ target: context.target,
+ signal: context.signal,
+ }).mutation({
+ __name: 'CreateApplicationFileUploads',
+ createApplicationFileUploads: {
+ __args: {
+ applicationUniversalIdentifier: context.applicationUniversalIdentifier,
+ files: artifacts.map(toUploadRequest),
+ },
+ targets: {
+ fileId: true,
+ filePath: true,
+ uploadUrl: true,
+ contentType: true,
+ },
+ errors: { filePath: true, message: true },
+ },
+ });
+ const created = data?.createApplicationFileUploads;
+
+ if (
+ !isPlainObject(created) ||
+ !isArray(created.targets) ||
+ !created.targets.every(isUploadTarget)
+ ) {
+ throw createInvalidUploadResponseError();
+ }
+
+ context.progress.hasCreatedTargets = true;
+
+ const refusals = readUploadErrors({
+ value: created.errors,
+ idKey: 'filePath',
+ });
+ const answeredPaths = new Set([
+ ...created.targets.map((uploadTarget) => uploadTarget.filePath),
+ ...refusals.map(({ id }) => id),
+ ]);
+
+ return {
+ uploadTargets: created.targets,
+ failures: [
+ ...refusals.map(({ id, message }) => ({ path: id, message })),
+ ...artifacts
+ .filter((artifact) => !answeredPaths.has(artifact.path))
+ .map((artifact) => ({
+ path: artifact.path,
+ message: 'The server did not accept this file.',
+ })),
+ ],
+ };
+};
+
+const sendUploadedBytes = async ({
+ uploadTargets,
+ artifactByPath,
+ context,
+ failures,
+}: {
+ uploadTargets: UploadTarget[];
+ artifactByPath: Map<string, ToolingArtifact>;
+ context: UploadBatchContext;
+ failures: UploadFailure[];
+}) => {
+ const sentTargets: UploadTarget[] = [];
+
+ await runConcurrently({
+ items: uploadTargets,
+ run: async (uploadTarget) => {
+ const artifact = artifactByPath.get(uploadTarget.filePath);
+
+ if (!isDefined(artifact)) {
+ failures.push({
+ path: uploadTarget.filePath,
+ message: 'The server asked for a file this build does not have.',
+ });
+
+ return;
+ }
+
+ const bytes = await readSnapshotFile({
+ snapshotDirectory: context.snapshotDirectory,
+ artifact,
+ });
+
+ try {
+ const status = await putUploadFile({
+ uploadUrl: uploadTarget.uploadUrl,
+ contentType: uploadTarget.contentType,
+ bytes,
+ signal: context.signal,
+ });
+
+ if (status < 200 || status >= 300) {
+ failures.push({
+ path: artifact.path,
+ message: `File storage answered ${status}.`,
+ });
+
+ return;
+ }
+
+ sentTargets.push(uploadTarget);
+ } catch (error) {
+ if (context.signal.aborted || error instanceof CliError) {
+ throw error;
+ }
+
+ failures.push({
+ path: artifact.path,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ },
+ });
+
+ return sentTargets;
+};
+
+const completeUploads = async ({
+ sentTargets,
+ artifactByPath,
+ context,
+ failures,
+}: {
+ sentTargets: UploadTarget[];
+ artifactByPath: Map<string, ToolingArtifact>;
+ context: UploadBatchContext;
+ failures: UploadFailure[];
+}) => {
+ if (!isNonEmptyArray(sentTargets)) {
+ return;
+ }
+
+ const data = await createMetadataClient({
+ target: context.target,
+ signal: context.signal,
+ }).mutation({
+ __name: 'CompleteApplicationFileUploads',
+ completeApplicationFileUploads: {
+ __args: {
+ applicationUniversalIdentifier: context.applicationUniversalIdentifier,
+ fileIds: sentTargets.map((uploadTarget) => uploadTarget.fileId),
+ },
+ errors: { fileId: true, message: true },
+ },
+ });
+ const completion = data?.completeApplicationFileUploads;
+
+ if (!isPlainObject(completion)) {
+ throw createInvalidUploadResponseError();
+ }
+
+ const completionErrors = readUploadErrors({
+ value: completion.errors,
+ idKey: 'fileId',
+ });
+ const failedFileIds = new Set(completionErrors.map(({ id }) => id));
+ const pathByFileId = new Map(
+ sentTargets.map((uploadTarget) => [
+ uploadTarget.fileId,
+ uploadTarget.filePath,
+ ]),
+ );
+
+ failures.push(
+ ...completionErrors.map(({ id, message }) => ({
+ path: pathByFileId.get(id) ?? id,
+ message,
+ })),
+ );
+
+ for (const uploadTarget of sentTargets) {
+ if (!failedFileIds.has(uploadTarget.fileId)) {
+ context.progress.fileCount += 1;
+ context.progress.byteCount +=
+ artifactByPath.get(uploadTarget.filePath)?.size ?? 0;
+ }
+ }
+};
+
+export const uploadAppFiles = async ({
+ build,
+ snapshotDirectory,
+ target,
+ signal,
+ progress,
+}: {
+ build: ToolingBuild;
+ snapshotDirectory: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ progress: AppUploadProgress;
+}) => {
+ build.files.forEach(toUploadRequest);
+
+ for (const artifact of build.files) {
+ await readSnapshotFile({ snapshotDirectory, artifact });
+ }
+
+ const context: UploadBatchContext = {
+ applicationUniversalIdentifier: build.application.universalIdentifier,
+ snapshotDirectory,
+ target,
+ signal,
+ progress,
+ };
+ const artifactByPath = new Map(
+ build.files.map((artifact) => [artifact.path, artifact]),
+ );
+ const failures: UploadFailure[] = [];
+
+ for (
+ let batchStart = 0;
+ batchStart < build.files.length;
+ batchStart += APPLICATION_FILE_UPLOAD_BATCH_SIZE
+ ) {
+ const { uploadTargets, failures: refusals } = await requestUploadTargets({
+ artifacts: build.files.slice(
+ batchStart,
+ batchStart + APPLICATION_FILE_UPLOAD_BATCH_SIZE,
+ ),
+ context,
+ });
+
+ failures.push(...refusals);
+
+ const sentTargets = await sendUploadedBytes({
+ uploadTargets,
+ artifactByPath,
+ context,
+ failures,
+ });
+
+ await completeUploads({ sentTargets, artifactByPath, context, failures });
+ }
+
+ if (isNonEmptyArray(failures)) {
+ throw new CliError({
+ code: 'UPLOAD_FAILED',
+ message: `${failures.length} of ${build.files.length} files could not be uploaded.`,
+ details: { failures },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/deployment/with-phase-details.ts b/packages/twenty-cli/src/app/deployment/with-phase-details.ts
new file mode 100644
index 00000000000..b9b34803deb
--- /dev/null
+++ b/packages/twenty-cli/src/app/deployment/with-phase-details.ts
@@ -0,0 +1,28 @@
+import { CliError } from '@/output/cli-error';
+
+export const withPhaseDetails = ({
+ error,
+ phase,
+ outcome,
+ completedPhases,
+ hint,
+}: {
+ error: CliError;
+ phase: string;
+ outcome: string;
+ completedPhases: string[];
+ hint: string;
+}) =>
+ new CliError({
+ cause: error,
+ code: error.code,
+ exitCode: error.exitCode,
+ message: error.message,
+ hint: error.hint ?? hint,
+ details: {
+ ...error.details,
+ phase,
+ outcome,
+ completedPhases: [...completedPhases],
+ },
+ });
diff --git a/packages/twenty-cli/src/app/dev/README.md b/packages/twenty-cli/src/app/dev/README.md
new file mode 100644
index 00000000000..69d91c4ebd5
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/README.md
@@ -0,0 +1,35 @@
+# App development session
+
+The parent owns observation and two bounded scheduling lanes: one build worker
+and one remote apply. `runDevLoop` keeps only the latest pending snapshot. Every
+snapshot is released once, including superseded builds and cancellation; the
+active apply retains its files until its reads settle. The skip key is the last
+acknowledged remote content hash, cleared after a failed apply.
+
+`buildDevSnapshot` copies declared, size/SHA-256-verified artifacts into a fresh
+`dev-*` directory while the compiler's snapshot lease is held. The worker then
+releases its own snapshot and exits, so retained builds do not retain compiler
+heaps. At most three snapshot directories exist for an active session: in-flight
+apply, compiler source, and its copy. No hard links or mutable output tree.
+
+Input collection is private worker metadata, absent on ordinary build requests.
+It observes esbuild loads/resolution parents, static-file copies and TypeScript
+reads. Missing TypeScript package-scope probes cannot expand watching into
+unrelated ancestor directories. Inputs have stamps captured before reads; after
+attaching the watcher, changed stamps invalidate the result. A successful graph
+replaces the previous graph; a failure watches the last successful graph plus
+only that attempt's inputs. External directory observation is shallow.
+
+`applyAppBuild` handles remote operations. Dev supplies a
+revision-specific approval signal and a check immediately before the first
+write. Once writes start, a newer build does not cancel those writes. Client
+generation pauses compilation and invalidates pending builds; its successful
+input key plus output stamps prevent generation loops. A failure after client
+writes start ends the session. Normal compilation failures keep watching;
+abnormal worker exits and watcher failures require restart.
+
+There is no incremental compiler cache or package-manager dependency watcher.
+Arbitrary app-code filesystem reads, concurrent independent dev processes,
+and SIGKILL recovery are outside this
+session's guarantees. See the [command reference](../../../docs/commands.md#develop-an-app) for
+user-visible limits.
diff --git a/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts
new file mode 100644
index 00000000000..1ce53e586a4
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createDevOutput } from '@/app/dev/create-dev-output';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+
+describe('dev stream output', () => {
+ it('serializes build and sync events under backpressure and bounds buffered progress', async () => {
+ const drain = Promise.withResolvers<void>();
+ const event = vi.fn(async () => {
+ await drain.promise;
+ });
+ const context: TargetCommandContext = {
+ command: 'app dev',
+ arguments: [],
+ options: {},
+ outputMode: 'ndjson',
+ signal: new AbortController().signal,
+ target: {
+ apiUrl: 'http://localhost:3000',
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ output: {
+ event,
+ progress: vi.fn(),
+ warn: vi.fn(),
+ succeed: vi.fn(),
+ fail: vi.fn(),
+ },
+ };
+ const output = createDevOutput(context);
+ for (let index = 0; index < 1000; index += 1)
+ output.output.warn({ code: 'WARNING', message: `warning ${index}` });
+ const first = output.emit(
+ { kind: 'build-start', message: 'Building' },
+ context.signal,
+ );
+ const second = output.emit(
+ { kind: 'sync-start', message: 'Syncing' },
+ context.signal,
+ );
+ await vi.waitFor(() => expect(event).toHaveBeenCalledOnce());
+ expect(event).toHaveBeenCalledWith(
+ 'progress',
+ expect.objectContaining({
+ messages: expect.arrayContaining([
+ { message: '968 additional progress messages omitted.' },
+ ]),
+ }),
+ context.signal,
+ );
+ drain.resolve();
+ await Promise.all([first, second]);
+ expect(event).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/dev-approval.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/dev-approval.spec.ts
new file mode 100644
index 00000000000..76fdeca1f59
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/dev-approval.spec.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { applyAppBuild } from '@/app/deployment/apply-app-build';
+import { fetchAppPlan } from '@/app/deployment/fetch-app-plan';
+import { installDevelopmentApp } from '@/app/deployment/install-development-app';
+import { requireApproval } from '@/app/deployment/require-approval';
+import { syncAppManifest } from '@/app/deployment/sync-app-manifest';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { uploadAppFiles } from '@/app/deployment/upload-app-files';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+
+vi.mock('@/app/deployment/fetch-app-plan');
+vi.mock('@/app/deployment/install-development-app');
+vi.mock('@/app/deployment/require-approval');
+vi.mock('@/app/deployment/sync-app-manifest');
+vi.mock('@/app/deployment/upload-app-files');
+
+const build: ToolingBuild = {
+ buildId: 'first',
+ contentHash: 'first',
+ directory: '/app/.twenty/cli/snapshots/dev-first',
+ application: { name: 'app', displayName: 'App', universalIdentifier: 'id' },
+ manifest: {},
+ manifestFormat: 'twenty-application',
+ files: [],
+};
+const context: TargetCommandContext = {
+ command: 'app dev',
+ arguments: [],
+ options: {},
+ outputMode: 'human',
+ signal: new AbortController().signal,
+ target: {
+ apiUrl: 'http://localhost:3000',
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ output: {
+ event: vi.fn(),
+ progress: vi.fn(),
+ warn: vi.fn(),
+ succeed: vi.fn(),
+ fail: vi.fn(),
+ },
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(fetchAppPlan).mockResolvedValue([
+ {
+ type: 'delete',
+ metadataName: 'objectMetadata',
+ flatEntity: { nameSingular: 'invoice' },
+ },
+ ]);
+ vi.mocked(installDevelopmentApp).mockResolvedValue({ applicationId: 'id' });
+ vi.mocked(uploadAppFiles).mockResolvedValue(undefined);
+ vi.mocked(syncAppManifest).mockResolvedValue({
+ actions: [],
+ acknowledgedUniversalIdentifier: 'id',
+ });
+});
+
+describe('dev apply approvals', () => {
+ it('flushes the preview before prompting and rejects an answer for an edited revision', async () => {
+ const approval = Promise.withResolvers<void>();
+ const controller = new AbortController();
+ let wasPreviewFlushed = false;
+ vi.mocked(requireApproval).mockImplementation(async () => {
+ expect(wasPreviewFlushed).toBe(true);
+ return approval.promise;
+ });
+ const applying = applyAppBuild({
+ build,
+ appPath: '/app',
+ context,
+ inferDeletionFromMissingEntities: true,
+ isCreationApproved: false,
+ isDeletionApproved: false,
+ approvalSignal: controller.signal,
+ flushProgress: async () => {
+ wasPreviewFlushed = true;
+ },
+ beforeWrite: () => controller.signal.throwIfAborted(),
+ });
+ const failure = expect(applying).rejects.toMatchObject({
+ details: { phase: 'confirmation', outcome: 'not-started' },
+ });
+ await vi.waitFor(() => expect(requireApproval).toHaveBeenCalledOnce());
+ controller.abort();
+ approval.resolve();
+ await failure;
+ expect(installDevelopmentApp).not.toHaveBeenCalled();
+ expect(uploadAppFiles).not.toHaveBeenCalled();
+ expect(syncAppManifest).not.toHaveBeenCalled();
+ });
+
+ it('checks freshness after output backpressure, immediately before the first remote write', async () => {
+ vi.mocked(fetchAppPlan).mockResolvedValue([]);
+ const controller = new AbortController();
+ await expect(
+ applyAppBuild({
+ build,
+ appPath: '/app',
+ context,
+ inferDeletionFromMissingEntities: true,
+ isCreationApproved: true,
+ isDeletionApproved: true,
+ approvalSignal: controller.signal,
+ flushProgress: async () => {
+ controller.abort();
+ },
+ beforeWrite: () => controller.signal.throwIfAborted(),
+ }),
+ ).rejects.toMatchObject({ details: { phase: 'confirmation' } });
+ expect(installDevelopmentApp).not.toHaveBeenCalled();
+ });
+ it('keeps completed phases when output is interrupted between remote operations', async () => {
+ vi.mocked(fetchAppPlan).mockResolvedValue([]);
+ const controller = new AbortController();
+ const cancelledContext = { ...context, signal: controller.signal };
+ let flushes = 0;
+ await expect(
+ applyAppBuild({
+ build,
+ appPath: '/app',
+ context: cancelledContext,
+ inferDeletionFromMissingEntities: true,
+ isCreationApproved: true,
+ isDeletionApproved: true,
+ flushProgress: async () => {
+ flushes += 1;
+ if (flushes === 2) {
+ controller.abort();
+ throw controller.signal.reason;
+ }
+ },
+ }),
+ ).rejects.toMatchObject({
+ code: 'CANCELLED',
+ details: {
+ completedPhases: ['build', 'preview', 'installation'],
+ outcome: 'not-started',
+ },
+ });
+ expect(uploadAppFiles).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/dev-watch-inputs-worker.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/dev-watch-inputs-worker.spec.ts
new file mode 100644
index 00000000000..33181d7386d
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/dev-watch-inputs-worker.spec.ts
@@ -0,0 +1,496 @@
+import { existsSync } from 'node:fs';
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { stop } from 'esbuild';
+import { isPlainObject } from 'twenty-shared/utils';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { type WatchInputs } from '@/app/dev/types/watch-inputs.type';
+import { runAppWorker } from '@/app/run-app-worker';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const MINIMAL_APP = join(
+ REPOSITORY_ROOT,
+ 'packages/twenty-apps/fixtures/minimal-app',
+);
+const REPOSITORY_PACKAGES = [
+ 'react',
+ 'react-dom',
+ '@types',
+ '@sniptt/guards',
+ 'typescript',
+ 'twenty-shared',
+ 'twenty-client-sdk',
+ 'twenty-ui',
+];
+const SDK_EXPORTS = [
+ 'define',
+ 'front-component',
+ 'logic-function',
+ 'billing',
+ 'utils',
+];
+const IGNORED_SEGMENTS = ['node_modules', '.git', '.twenty'];
+
+type Workspace = {
+ workspace: string;
+ appPath: string;
+};
+
+describe('dev watch inputs reported by the app worker', () => {
+ let root: string;
+
+ const writeFiles = async (
+ directory: string,
+ files: Record<string, string>,
+ ) => {
+ for (const [name, content] of Object.entries(files)) {
+ await mkdir(dirname(join(directory, name)), { recursive: true });
+ await writeFile(join(directory, name), content);
+ }
+ };
+
+ const writeLinkedPackage = async ({
+ workspace,
+ name,
+ files,
+ }: {
+ workspace: string;
+ name: string;
+ files: Record<string, string>;
+ }) => {
+ await writeFiles(join(workspace, 'libs', name), {
+ 'package.json': JSON.stringify({
+ name,
+ version: '1.0.0',
+ main: 'index.js',
+ types: 'index.d.ts',
+ }),
+ ...files,
+ });
+ await symlink(
+ join(workspace, 'libs', name),
+ join(workspace, 'app/node_modules', name),
+ );
+ };
+
+ const createWorkspace = async (): Promise<Workspace> => {
+ const workspace = await realpath(await mkdtemp(join(root, 'workspace-')));
+ const appPath = join(workspace, 'app');
+
+ await cp(MINIMAL_APP, appPath, {
+ recursive: true,
+ filter: (source) =>
+ !source
+ .split(sep)
+ .some((part) => ['node_modules', '.twenty', 'dist'].includes(part)),
+ });
+ await mkdir(join(appPath, 'node_modules'));
+
+ for (const name of await readdir(join(root, 'node_modules'))) {
+ await symlink(
+ join(root, 'node_modules', name),
+ join(appPath, 'node_modules', name),
+ );
+ }
+
+ const appConfig = JSON.parse(
+ await readFile(join(appPath, 'tsconfig.json'), 'utf8'),
+ );
+ const compilerOptions = Object.fromEntries(
+ Object.entries(appConfig.compilerOptions).filter(
+ ([option]) => option !== 'baseUrl' && option !== 'paths',
+ ),
+ );
+
+ await writeFiles(workspace, {
+ 'tsconfig.base.json': JSON.stringify({ compilerOptions }),
+ 'shared-src/relative-label.ts': `export const RELATIVE_LABEL = 'relative';\n`,
+ });
+ await writeFiles(appPath, {
+ 'tsconfig.json': JSON.stringify({
+ extends: '../tsconfig.base.json',
+ include: appConfig.include,
+ exclude: appConfig.exclude,
+ }),
+ 'my.object.ts': (await readFile(join(appPath, 'my.object.ts'), 'utf8'))
+ .replace(
+ "import { FieldType, defineObject } from 'twenty-sdk/define';",
+ "import { OBJECT_DESCRIPTION } from 'define-lib';\nimport { FieldType, defineObject } from 'twenty-sdk/define';",
+ )
+ .replace("'A simple root-level object'", 'OBJECT_DESCRIPTION'),
+ 'my.function.ts': (
+ await readFile(join(appPath, 'my.function.ts'), 'utf8')
+ )
+ .replace(
+ "import { defineLogicFunction } from 'twenty-sdk/define';",
+ "import { FUNCTION_RESULT } from 'function-lib';\nimport { defineLogicFunction } from 'twenty-sdk/define';\n\nimport { RELATIVE_LABEL } from '../shared-src/relative-label';",
+ )
+ .replace(
+ "return 'my-function-result';",
+ 'return `${FUNCTION_RESULT}-${RELATIVE_LABEL}`;',
+ ),
+ 'my.front-component.tsx': (
+ await readFile(join(appPath, 'my.front-component.tsx'), 'utf8')
+ )
+ .replace(
+ "import 'twenty-ui/style.css';",
+ "import 'twenty-ui/style.css';\nimport 'component-lib/theme.css';\nimport { COMPONENT_TITLE } from 'component-lib';",
+ )
+ .replace('<h2>My Component</h2>', '<h2>{COMPONENT_TITLE}</h2>'),
+ });
+
+ await writeLinkedPackage({
+ workspace,
+ name: 'define-lib',
+ files: {
+ 'index.js': `export const OBJECT_DESCRIPTION = 'Described by a linked package';\n`,
+ 'index.d.ts': 'export declare const OBJECT_DESCRIPTION: string;\n',
+ },
+ });
+ await writeLinkedPackage({
+ workspace,
+ name: 'function-lib',
+ files: {
+ 'index.js': `export const FUNCTION_RESULT = 'linked-result';\n`,
+ 'index.d.ts': 'export declare const FUNCTION_RESULT: string;\n',
+ },
+ });
+ await writeLinkedPackage({
+ workspace,
+ name: 'component-lib',
+ files: {
+ 'index.js': `export const COMPONENT_TITLE = 'Linked title';\n`,
+ 'index.d.ts': 'export declare const COMPONENT_TITLE: string;\n',
+ 'theme.css': '.linked-title { color: rebeccapurple; }\n',
+ },
+ });
+
+ return { workspace, appPath };
+ };
+
+ const bundleSnapshot = async ({
+ appPath,
+ collectWatchInputs,
+ }: {
+ appPath: string;
+ collectWatchInputs: boolean;
+ }) => {
+ const response = await runAppWorker({
+ request: {
+ type: 'bundleSnapshot',
+ appPath,
+ holdSnapshot: false,
+ ...(collectWatchInputs ? { collectWatchInputs: true } : {}),
+ },
+ signal: new AbortController().signal,
+ });
+
+ return {
+ isSuccess:
+ isPlainObject(response.result) && response.result.success === true,
+ result: response.result,
+ watchInputs: response.watchInputs,
+ };
+ };
+
+ const describeInputs = (watchInputs: WatchInputs, workspace: string) =>
+ watchInputs
+ .filter((input) => !relative(workspace, input.path).startsWith('..'))
+ .map(
+ (input) => `${input.kind}:${relative(workspace, input.path) || '.'}`,
+ );
+
+ const findInput = (
+ watchInputs: WatchInputs,
+ kind: 'file' | 'directory',
+ path: string,
+ ) => watchInputs.find((input) => input.kind === kind && input.path === path);
+
+ beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-dev-watch-inputs-'));
+
+ const modules = join(root, 'node_modules');
+ const sourceSdk = join(REPOSITORY_ROOT, 'packages/twenty-sdk');
+ const sdkPath = join(modules, 'twenty-sdk');
+ const sdkRequire = createRequire(join(sourceSdk, 'package.json'));
+
+ await mkdir(join(modules, '@sniptt'), { recursive: true });
+
+ for (const name of REPOSITORY_PACKAGES) {
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules', name),
+ join(modules, name),
+ );
+ }
+ await symlink(
+ dirname(sdkRequire.resolve('uuid/package.json')),
+ join(modules, 'uuid'),
+ );
+
+ const packageJson = JSON.parse(
+ await readFile(join(sourceSdk, 'package.json'), 'utf8'),
+ );
+ const exports: Record<string, unknown> = {};
+
+ for (const name of SDK_EXPORTS) {
+ await cp(join(sourceSdk, 'dist', name), join(sdkPath, 'dist', name), {
+ recursive: true,
+ });
+ exports[`./${name}`] = packageJson.exports[`./${name}`];
+ }
+
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: packageJson.name,
+ version: packageJson.version,
+ engines: packageJson.engines,
+ exports,
+ }),
+ );
+ await buildTestAppWorker(join(root, 'cli'));
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ }, 120_000);
+
+ afterAll(async () => {
+ await stop();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('reports linked files read by definitions, bundles and the typecheck, and nothing above the workspace', async () => {
+ const { workspace, appPath } = await createWorkspace();
+
+ const { isSuccess, result, watchInputs } = await bundleSnapshot({
+ appPath,
+ collectWatchInputs: true,
+ });
+
+ expect(isSuccess, JSON.stringify(result)).toBe(true);
+ expect(watchInputs).toBeDefined();
+
+ const inputs = watchInputs ?? [];
+
+ expect(describeInputs(inputs, workspace)).toEqual(
+ expect.arrayContaining([
+ 'file:libs/define-lib/index.js',
+ 'file:libs/function-lib/index.js',
+ 'file:libs/component-lib/index.js',
+ 'file:libs/component-lib/theme.css',
+ 'file:shared-src/relative-label.ts',
+ 'file:tsconfig.base.json',
+ 'directory:libs/define-lib',
+ 'directory:libs/function-lib',
+ 'directory:libs/component-lib',
+ 'directory:shared-src',
+ 'directory:.',
+ ]),
+ );
+
+ for (const input of inputs) {
+ expect(
+ input.path.split(sep).filter((part) => IGNORED_SEGMENTS.includes(part)),
+ input.path,
+ ).toEqual([]);
+ expect(input.stamp === null, input.path).toBe(!existsSync(input.path));
+ }
+
+ expect(
+ inputs
+ .filter((input) => input.kind === 'directory')
+ .map((input) => input.path)
+ .filter((path) => workspace.startsWith(`${path}${sep}`)),
+ ).toEqual([]);
+
+ const existingFileDirectories = new Set(
+ inputs
+ .filter((input) => input.kind === 'file' && input.stamp !== null)
+ .map((input) => dirname(input.path)),
+ );
+
+ expect(
+ inputs
+ .filter((input) => input.kind === 'file' && input.stamp === null)
+ .map((input) => input.path)
+ .filter((path) => !existingFileDirectories.has(dirname(path))),
+ ).toEqual([]);
+ }, 120_000);
+
+ it('reports a linked file that breaks the build, and a changed stamp once it is fixed', async () => {
+ const { workspace, appPath } = await createWorkspace();
+ const linkedFile = join(workspace, 'libs/function-lib/index.js');
+
+ await writeFile(linkedFile, 'export const FUNCTION_RESULT = ;\n');
+
+ const broken = await bundleSnapshot({ appPath, collectWatchInputs: true });
+ const brokenInput = findInput(broken.watchInputs ?? [], 'file', linkedFile);
+
+ expect(broken.isSuccess).toBe(false);
+ expect(brokenInput?.stamp ?? null).not.toBeNull();
+
+ await writeFile(linkedFile, `export const FUNCTION_RESULT = 'fixed';\n`);
+
+ const fixed = await bundleSnapshot({ appPath, collectWatchInputs: true });
+ const fixedInput = findInput(fixed.watchInputs ?? [], 'file', linkedFile);
+
+ expect(fixed.isSuccess, JSON.stringify(fixed.result)).toBe(true);
+ expect(fixedInput?.stamp ?? null).not.toBeNull();
+ expect(fixedInput?.stamp).not.toBe(brokenInput?.stamp);
+ }, 120_000);
+
+ it('reports the directory of a missing linked import so its creation can trigger a rebuild', async () => {
+ const { workspace, appPath } = await createWorkspace();
+ const extrasDirectory = join(workspace, 'libs/function-lib-extras');
+
+ await mkdir(extrasDirectory);
+ await writeFile(
+ join(workspace, 'libs/function-lib/index.js'),
+ `export { EXTRA as FUNCTION_RESULT } from '../function-lib-extras/extra.js';\n`,
+ );
+
+ const missing = await bundleSnapshot({ appPath, collectWatchInputs: true });
+
+ expect(missing.isSuccess).toBe(false);
+ expect(
+ findInput(missing.watchInputs ?? [], 'directory', extrasDirectory)?.stamp,
+ ).toBe(JSON.stringify([]));
+
+ await writeFile(
+ join(extrasDirectory, 'extra.js'),
+ `export const EXTRA = 'extra';\n`,
+ );
+
+ const created = await bundleSnapshot({ appPath, collectWatchInputs: true });
+
+ expect(created.isSuccess, JSON.stringify(created.result)).toBe(true);
+ expect(
+ findInput(created.watchInputs ?? [], 'directory', extrasDirectory)?.stamp,
+ ).toBe(JSON.stringify([['extra.js', false, true, false]]));
+ expect(
+ findInput(
+ created.watchInputs ?? [],
+ 'file',
+ join(extrasDirectory, 'extra.js'),
+ ),
+ ).toBeDefined();
+ }, 120_000);
+
+ it('reports a linked package that only the shared dependencies bundle reads', async () => {
+ const { workspace, appPath } = await createWorkspace();
+ const packageJsonPath = join(appPath, 'package.json');
+ const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8'));
+
+ await writeLinkedPackage({
+ workspace,
+ name: 'shared-lib',
+ files: {
+ 'index.js': 'export const SHARED_VALUE = 1;\n',
+ 'index.d.ts': 'export declare const SHARED_VALUE: number;\n',
+ },
+ });
+ await writeFile(
+ packageJsonPath,
+ JSON.stringify({
+ ...packageJson,
+ frontComponentSharedDependencies: ['shared-lib'],
+ }),
+ );
+
+ const { isSuccess, result, watchInputs } = await bundleSnapshot({
+ appPath,
+ collectWatchInputs: true,
+ });
+
+ expect(isSuccess, JSON.stringify(result)).toBe(true);
+ expect(describeInputs(watchInputs ?? [], workspace)).toEqual(
+ expect.arrayContaining([
+ 'file:libs/shared-lib/index.js',
+ 'directory:libs/shared-lib',
+ ]),
+ );
+ }, 120_000);
+
+ it('reports an external tsconfig that breaks the build, so fixing it can trigger a rebuild', async () => {
+ const { workspace, appPath } = await createWorkspace();
+ const baseConfigPath = join(workspace, 'tsconfig.base.json');
+ const baseConfig = await readFile(baseConfigPath, 'utf8');
+
+ await writeFile(baseConfigPath, '{ "compilerOptions": ');
+
+ const broken = await bundleSnapshot({ appPath, collectWatchInputs: true });
+
+ expect(broken.isSuccess).toBe(false);
+ expect(
+ findInput(broken.watchInputs ?? [], 'file', baseConfigPath)?.stamp ??
+ null,
+ ).not.toBeNull();
+
+ await writeFile(baseConfigPath, baseConfig);
+
+ const fixed = await bundleSnapshot({ appPath, collectWatchInputs: true });
+
+ expect(fixed.isSuccess, JSON.stringify(fixed.result)).toBe(true);
+ }, 120_000);
+
+ it('reports the target of a public asset symlinked from outside the app', async () => {
+ const { workspace, appPath } = await createWorkspace();
+
+ await writeFiles(workspace, {
+ 'shared-assets/logo.svg':
+ '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>\n',
+ });
+ await mkdir(join(appPath, 'public'));
+ await symlink(
+ join(workspace, 'shared-assets/logo.svg'),
+ join(appPath, 'public/logo.svg'),
+ );
+
+ const { isSuccess, result, watchInputs } = await bundleSnapshot({
+ appPath,
+ collectWatchInputs: true,
+ });
+
+ expect(isSuccess, JSON.stringify(result)).toBe(true);
+ expect(describeInputs(watchInputs ?? [], workspace)).toEqual(
+ expect.arrayContaining([
+ 'file:shared-assets/logo.svg',
+ 'directory:shared-assets',
+ ]),
+ );
+ }, 120_000);
+
+ it('returns no watch inputs unless they are requested', async () => {
+ const { appPath } = await createWorkspace();
+
+ const { isSuccess, result, watchInputs } = await bundleSnapshot({
+ appPath,
+ collectWatchInputs: false,
+ });
+
+ expect(isSuccess, JSON.stringify(result)).toBe(true);
+ expect(watchInputs).toBeUndefined();
+ }, 120_000);
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/generate-dev-client.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/generate-dev-client.spec.ts
new file mode 100644
index 00000000000..7796090f298
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/generate-dev-client.spec.ts
@@ -0,0 +1,228 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type AppApplyResult } from '@/app/deployment/apply-app-build';
+import { type BuiltDevSnapshot } from '@/app/dev/build-dev-snapshot';
+import { createDevClientGenerator } from '@/app/dev/generate-dev-client';
+import {
+ fetchAppClientSchema,
+ generateAppClientFromSchema,
+} from '@/app/generate-app-client';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+
+vi.mock('@/app/generate-app-client');
+
+let appPath: string;
+let controller: AbortController;
+let context: TargetCommandContext;
+let applied: AppApplyResult;
+const snapshot: BuiltDevSnapshot = {
+ contentHash: 'hash',
+ build: {
+ buildId: 'build',
+ contentHash: 'hash',
+ application: {
+ name: 'test',
+ displayName: 'Test',
+ universalIdentifier: 'id',
+ },
+ manifestFormat: 'twenty-application',
+ manifest: {},
+ files: [],
+ directory: '/snapshot',
+ },
+ diagnostics: [],
+ tooling: {
+ version: '2.44.0',
+ packagePath: '/sdk',
+ },
+ sourceFingerprints: {},
+ release: async () => {},
+};
+const invalidate = vi.fn();
+let isPaused = false;
+const withBuildsPaused = async <TResult>(run: () => Promise<TResult>) => {
+ isPaused = true;
+ try {
+ return await run();
+ } finally {
+ isPaused = false;
+ }
+};
+
+beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'dev-client-'));
+ await mkdir(join(appPath, 'node_modules/twenty-client-sdk'), {
+ recursive: true,
+ });
+ await writeFile(
+ join(appPath, 'node_modules/twenty-client-sdk/package.json'),
+ '{"name":"twenty-client-sdk","version":"2.44.0","exports":{"./generate":"./generate.cjs"}}',
+ );
+ await writeFile(
+ join(appPath, 'node_modules/twenty-client-sdk/generate.cjs'),
+ 'module.exports = {};',
+ );
+ controller = new AbortController();
+ context = {
+ command: 'app dev',
+ arguments: [],
+ options: {},
+ outputMode: 'ndjson',
+ signal: controller.signal,
+ target: {
+ apiUrl: 'http://localhost:3000',
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ output: {
+ event: vi.fn(),
+ progress: vi.fn(),
+ warn: vi.fn(),
+ succeed: vi.fn(),
+ fail: vi.fn(),
+ },
+ };
+ applied = {
+ completedPhases: ['sync', 'pullBase'],
+ isRegistrationCreated: false,
+ appliedActions: [],
+ acknowledgedUniversalIdentifier: 'id',
+ upload: { fileCount: 0, byteCount: 0, hasCreatedTargets: false },
+ };
+ vi.mocked(fetchAppClientSchema).mockResolvedValue('schema');
+ vi.mocked(generateAppClientFromSchema).mockImplementation(async () => {
+ expect(isPaused).toBe(true);
+ return [];
+ });
+});
+afterEach(async () => {
+ vi.resetAllMocks();
+ await rm(appPath, { recursive: true, force: true });
+});
+
+describe('dev client generation', () => {
+ it('quiesces builds and avoids generation loops using schema and installed generator identity', async () => {
+ const generate = createDevClientGenerator({ appPath });
+ const options = {
+ snapshot,
+ applied,
+ context,
+ withBuildsPaused,
+ invalidate,
+ };
+ expect(await generate(options)).toBe('generated');
+ expect(await generate(options)).toBe('unchanged');
+ expect(generateAppClientFromSchema).toHaveBeenCalledOnce();
+ await mkdir(join(appPath, 'node_modules/twenty-client-sdk/dist'), {
+ recursive: true,
+ });
+ await writeFile(
+ join(appPath, 'node_modules/twenty-client-sdk/dist/core.cjs'),
+ 'reinstalled stub',
+ );
+ expect(await generate(options)).toBe('generated');
+ expect(await generate(options)).toBe('unchanged');
+ await writeFile(
+ join(appPath, 'node_modules/twenty-client-sdk/package.json'),
+ '{"name":"twenty-client-sdk","version":"2.45.0","exports":{"./generate":"./generate.cjs"}}',
+ );
+ expect(await generate(options)).toBe('generated');
+ vi.mocked(fetchAppClientSchema).mockResolvedValue('new schema');
+ expect(await generate(options)).toBe('generated');
+ expect(invalidate).toHaveBeenCalledTimes(4);
+ });
+
+ it('regenerates after generator bytes or a nested generated file change', async () => {
+ const generate = createDevClientGenerator({ appPath });
+ const options = {
+ snapshot,
+ applied,
+ context,
+ withBuildsPaused,
+ invalidate,
+ };
+ const packageRoot = join(appPath, 'node_modules/twenty-client-sdk');
+ const directory = join(packageRoot, 'dist/core/generated/models');
+
+ await mkdir(directory, { recursive: true });
+ await writeFile(join(directory, 'company.ts'), 'original');
+ expect(await generate(options)).toBe('generated');
+ expect(await generate(options)).toBe('unchanged');
+ await writeFile(join(directory, 'company.ts'), 'modified');
+ expect(await generate(options)).toBe('generated');
+ await writeFile(
+ join(packageRoot, 'generate.cjs'),
+ 'module.exports = { rebuilt: true };',
+ );
+ expect(await generate(options)).toBe('generated');
+ expect(await generate(options)).toBe('unchanged');
+ });
+
+ it('keeps the old client on schema failure and does not cache a failed attempt', async () => {
+ const generate = createDevClientGenerator({ appPath });
+ vi.mocked(fetchAppClientSchema).mockRejectedValueOnce(
+ new Error('network failure'),
+ );
+ const options = {
+ snapshot,
+ applied,
+ context,
+ withBuildsPaused,
+ invalidate,
+ };
+ expect(await generate(options)).toBe('skipped');
+ expect(generateAppClientFromSchema).not.toHaveBeenCalled();
+ expect(invalidate).not.toHaveBeenCalled();
+ expect(context.output.warn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining('previous client was kept'),
+ }),
+ );
+ expect(await generate(options)).toBe('generated');
+ });
+
+ it('reports applied phases and incomplete files after a generation failure', async () => {
+ const generate = createDevClientGenerator({ appPath });
+ vi.mocked(generateAppClientFromSchema).mockRejectedValueOnce(
+ new Error('disk full'),
+ );
+ await expect(
+ generate({ snapshot, applied, context, withBuildsPaused, invalidate }),
+ ).rejects.toMatchObject({
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: ['sync', 'pullBase'],
+ },
+ hint: expect.stringContaining('may be incomplete'),
+ });
+ expect(invalidate).not.toHaveBeenCalled();
+ expect(isPaused).toBe(false);
+ });
+ it('keeps applied phases when cancelled while waiting for the compiler to pause, before client writes', async () => {
+ const generate = createDevClientGenerator({ appPath });
+ const withCancelledPause = async () => {
+ controller.abort();
+ throw controller.signal.reason;
+ };
+ await expect(
+ generate({
+ snapshot,
+ applied,
+ context,
+ withBuildsPaused: withCancelledPause,
+ invalidate,
+ }),
+ ).rejects.toMatchObject({
+ code: 'CANCELLED',
+ details: { phase: 'clientGeneration', outcome: 'applied' },
+ hint: expect.stringContaining('previous typed API client was kept'),
+ });
+ expect(generateAppClientFromSchema).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/retain-dev-snapshot.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/retain-dev-snapshot.spec.ts
new file mode 100644
index 00000000000..4d8ba0c1679
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/retain-dev-snapshot.spec.ts
@@ -0,0 +1,100 @@
+import { createHash } from 'node:crypto';
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { retainDevSnapshot } from '@/app/dev/retain-dev-snapshot';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+const fixture = async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'dev-snapshot-'));
+ roots.push(appPath);
+ const directory = join(appPath, '.twenty/cli/snapshots/build-original/files');
+ await mkdir(directory, { recursive: true });
+ await writeFile(join(directory, 'bundle.js'), 'original');
+ const build: ToolingBuild = {
+ buildId: 'test',
+ directory,
+ contentHash: 'opaque-hash',
+ manifest: {},
+ manifestFormat: 'twenty-application',
+ application: {
+ name: 'test',
+ displayName: 'Test',
+ universalIdentifier: 'id',
+ },
+ files: [
+ {
+ path: 'bundle.js',
+ role: 'built-logic-function',
+ sourcePath: 'source.ts',
+ size: 8,
+ sha256: createHash('sha256').update('original').digest('hex'),
+ },
+ ],
+ };
+
+ return {
+ build,
+ appPath,
+ signal: new AbortController().signal,
+ };
+};
+
+describe('retained dev snapshots', () => {
+ it('keeps independent verified bytes after the compiler snapshot is changed and released', async () => {
+ const options = await fixture();
+ const retained = await retainDevSnapshot(options);
+ await writeFile(join(options.build.directory!, 'bundle.js'), 'different');
+ await rm(options.build.directory!, { recursive: true });
+ expect(
+ await readFile(join(retained.build.directory, 'bundle.js'), 'utf8'),
+ ).toBe('original');
+ expect(retained.build.contentHash).toBe('opaque-hash');
+ await retained.release();
+ await expect(
+ readFile(join(retained.build.directory, 'bundle.js')),
+ ).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it.each(['changed', 'escape', 'duplicate'])(
+ 'cleans partial copies on %s artifacts',
+ async (mode) => {
+ const options = await fixture();
+ if (mode === 'changed')
+ await writeFile(join(options.build.directory!, 'bundle.js'), 'bad');
+ if (mode === 'escape') options.build.files[0].path = '../../outside';
+ if (mode === 'duplicate')
+ options.build.files.push(options.build.files[0]);
+ await expect(retainDevSnapshot(options)).rejects.toThrow();
+ expect(
+ await readdir(join(options.appPath, '.twenty/cli/snapshots')),
+ ).toEqual(['build-original']);
+ },
+ );
+
+ it('does not allocate a snapshot after cancellation', async () => {
+ const options = await fixture();
+ await expect(
+ retainDevSnapshot({ ...options, signal: AbortSignal.abort() }),
+ ).rejects.toThrow();
+ expect(
+ await readdir(join(options.appPath, '.twenty/cli/snapshots')),
+ ).toEqual(['build-original']);
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/run-dev-loop.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/run-dev-loop.spec.ts
new file mode 100644
index 00000000000..5da70e464ff
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/run-dev-loop.spec.ts
@@ -0,0 +1,215 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { runDevLoop, type DevSnapshot } from '@/app/dev/run-dev-loop';
+
+const deferred = <TValue>() => Promise.withResolvers<TValue>();
+const snapshot = (contentHash: string) => ({
+ contentHash,
+ release: vi.fn(async () => {}),
+});
+
+describe('dev scheduling', () => {
+ it('coalesces behind a slow sync, keeps its snapshot alive, compares with the last acknowledgement', async () => {
+ const controller = new AbortController();
+ const firstSync = deferred<boolean>();
+ const snapshots = [
+ snapshot('A'),
+ snapshot('B'),
+ snapshot('C'),
+ snapshot('C'),
+ ];
+ const apply = vi.fn(async (_snapshot: DevSnapshot) =>
+ apply.mock.calls.length === 1 ? firstSync.promise : true,
+ );
+ const build = vi.fn(async () => snapshots[build.mock.calls.length - 1]);
+ const skipped = vi.fn(async () => {});
+ let invalidate = () => {};
+ const close = vi.fn(async () => {});
+ const session = runDevLoop({
+ signal: controller.signal,
+ subscribe: async (change) => {
+ invalidate = change;
+ return close;
+ },
+ build,
+ apply,
+ onSkipped: skipped,
+ debounceMilliseconds: 0,
+ }).catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(apply).toHaveBeenCalledTimes(1));
+ invalidate();
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(2));
+ invalidate();
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(3));
+ expect(apply).toHaveBeenCalledTimes(1);
+ expect(snapshots[0].release).not.toHaveBeenCalled();
+ expect(snapshots[1].release).toHaveBeenCalledTimes(1);
+ firstSync.resolve(true);
+ await vi.waitFor(() => expect(apply).toHaveBeenCalledTimes(2));
+ expect(apply.mock.calls[1][0].contentHash).toBe('C');
+ invalidate();
+ await vi.waitFor(() =>
+ expect(skipped).toHaveBeenCalledWith(4, 'unchanged'),
+ );
+ expect(apply).toHaveBeenCalledTimes(2);
+ controller.abort();
+ await session;
+ for (const retained of snapshots)
+ expect(retained.release).toHaveBeenCalledTimes(1);
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+
+ it('never syncs a build superseded by an invalid revision and recovers on a later edit', async () => {
+ const controller = new AbortController();
+ const firstBuild = deferred<DevSnapshot>();
+ const obsolete = snapshot('obsolete');
+ const fixed = snapshot('fixed');
+ const build = vi
+ .fn<
+ (_: number, signal: AbortSignal) => Promise<DevSnapshot | undefined>
+ >()
+ .mockImplementationOnce(() => firstBuild.promise)
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValue(fixed);
+ const apply = vi.fn(async () => true);
+ let invalidate = () => {};
+ const session = runDevLoop({
+ signal: controller.signal,
+ subscribe: async (change) => {
+ invalidate = change;
+ return async () => {};
+ },
+ build,
+ apply,
+ onSkipped: async () => {},
+ debounceMilliseconds: 0,
+ }).catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));
+ invalidate();
+ firstBuild.resolve(obsolete);
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(2));
+ expect(apply).not.toHaveBeenCalled();
+ expect(obsolete.release).toHaveBeenCalledOnce();
+ invalidate();
+ await vi.waitFor(() => expect(apply).toHaveBeenCalledOnce());
+ controller.abort();
+ await session;
+ expect(fixed.release).toHaveBeenCalledOnce();
+ });
+
+ it('quiesces compilation before client writes, then rebuilds explicitly without another sync', async () => {
+ const controller = new AbortController();
+ const secondBuild = deferred<DevSnapshot>();
+ const startGeneration = deferred<void>();
+ const thirdBuild = snapshot('A');
+ const built = [snapshot('A'), snapshot('B')];
+ let invalidate = () => {};
+ let generationStarted = false;
+ const build = vi.fn(async () => {
+ if (build.mock.calls.length === 2) return secondBuild.promise;
+ return build.mock.calls.length === 1 ? built[0] : thirdBuild;
+ });
+ const skipped = vi.fn(async () => {});
+ const session = runDevLoop({
+ signal: controller.signal,
+ subscribe: async (change) => {
+ invalidate = change;
+ return async () => {};
+ },
+ build,
+ apply: async (_snapshot, controls) => {
+ await startGeneration.promise;
+ await controls.withBuildsPaused(async () => {
+ generationStarted = true;
+ controls.invalidate();
+ });
+ return true;
+ },
+ onSkipped: skipped,
+ debounceMilliseconds: 0,
+ }).catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());
+ invalidate();
+ await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(2));
+ startGeneration.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(generationStarted).toBe(false);
+ secondBuild.resolve(built[1]);
+ await vi.waitFor(() =>
+ expect(skipped).toHaveBeenCalledWith(3, 'unchanged'),
+ );
+ expect(generationStarted).toBe(true);
+ controller.abort();
+ await session;
+ for (const retained of [...built, thirdBuild])
+ expect(retained.release).toHaveBeenCalledOnce();
+ });
+
+ it('invalidates pending approvals but lets an active sync settle before releasing its files', async () => {
+ const controller = new AbortController();
+ const retained = snapshot('A');
+ const settled = deferred<boolean>();
+ let invalidate = () => {};
+ let approvalSignal: AbortSignal | undefined;
+ const apply = vi.fn(async (_snapshot, controls) => {
+ approvalSignal = controls.revisionSignal;
+ return settled.promise;
+ });
+ const session = runDevLoop({
+ signal: controller.signal,
+ subscribe: async (change) => {
+ invalidate = change;
+ return async () => {};
+ },
+ build: async (revision) => (revision === 1 ? retained : undefined),
+ apply,
+ onSkipped: async () => {},
+ debounceMilliseconds: 0,
+ }).catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(apply).toHaveBeenCalledOnce());
+ invalidate();
+ expect(approvalSignal?.aborted).toBe(true);
+ controller.abort();
+ expect(retained.release).not.toHaveBeenCalled();
+ settled.resolve(true);
+ await session;
+ expect(retained.release).toHaveBeenCalledOnce();
+ });
+
+ it('aborts active compilation when the watcher fails', async () => {
+ const fatal = new Error('watch failed');
+ const controller = new AbortController();
+ let fail = (_error: unknown) => {};
+ const build = vi.fn(
+ async (
+ _revision,
+ signal: AbortSignal,
+ ): Promise<DevSnapshot | undefined> =>
+ new Promise((_, reject) =>
+ signal.addEventListener('abort', () => reject(signal.reason), {
+ once: true,
+ }),
+ ),
+ );
+ const session = runDevLoop({
+ signal: controller.signal,
+ subscribe: async (_change, failed) => {
+ fail = failed;
+ return async () => {};
+ },
+ build,
+ apply: async () => true,
+ onSkipped: async () => {},
+ debounceMilliseconds: 0,
+ });
+ const result = expect(session).rejects.toBe(fatal);
+
+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());
+ fail(fatal);
+ await result;
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/__tests__/watch-app-inputs.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/watch-app-inputs.spec.ts
new file mode 100644
index 00000000000..d14fd5fd7f6
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/__tests__/watch-app-inputs.spec.ts
@@ -0,0 +1,222 @@
+import {
+ mkdir,
+ mkdtemp,
+ realpath,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import type * as chokidar from 'chokidar';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ collectWatchInputs,
+ recordWatchFile,
+} from '@/app/dev/collect-watch-inputs';
+import { readWatchInputStamp } from '@/app/dev/read-watch-input-stamp';
+import { watchAppInputs } from '@/app/dev/watch-app-inputs';
+
+const watcherOptions = vi.hoisted(() => ({ useFsEvents: false }));
+
+vi.mock('chokidar', async (importOriginal) => {
+ const actual = await importOriginal<typeof chokidar>();
+
+ return {
+ ...actual,
+ watch: (...[paths, options]: Parameters<typeof actual.watch>) =>
+ actual.watch(paths, {
+ ...options,
+ useFsEvents: watcherOptions.useFsEvents,
+ }),
+ };
+});
+
+const cleanups: (() => Promise<void>)[] = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+const fixture = async () => {
+ const root = await mkdtemp(join(tmpdir(), 'twenty-watch-'));
+ cleanups.push(() => rm(root, { recursive: true, force: true }));
+ const appPath = join(root, 'app');
+ await mkdir(appPath);
+ const onChange = vi.fn();
+ const onError = vi.fn();
+ const watcher = await watchAppInputs({
+ appPath,
+ signal: new AbortController().signal,
+ onChange,
+ onError,
+ });
+ cleanups.push(watcher.close);
+
+ return { root, appPath, watcher, onChange, onError };
+};
+const collect = async (file: string) =>
+ (
+ await collectWatchInputs(async () => {
+ recordWatchFile(file);
+ })
+ ).watchInputs;
+
+describe.each(['platform', 'node'])('app input watch (%s)', (backend) => {
+ beforeEach(() => {
+ watcherOptions.useFsEvents = backend === 'platform';
+ });
+ it('observes atomic saves and new files, ignores generated output and dependency installations', async () => {
+ const { appPath, onChange, onError } = await fixture();
+ const source = join(appPath, 'source.ts');
+ await writeFile(source, 'first');
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ onChange.mockClear();
+ await writeFile(join(appPath, 'source.tmp'), 'second');
+ await rename(join(appPath, 'source.tmp'), source);
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ onChange.mockClear();
+ for (const ignored of ['.twenty', '.git', 'node_modules']) {
+ await mkdir(join(appPath, ignored));
+ await writeFile(join(appPath, ignored, 'output.ts'), 'ignored');
+ }
+ await writeFile(join(appPath, '.source.ts.swo'), 'editor swap');
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('keeps successful external inputs on failure, handles missing siblings, then drops obsolete inputs', async () => {
+ const { root, watcher, onChange } = await fixture();
+ const external = join(root, 'linked', 'external.ts');
+ await mkdir(join(root, 'linked'));
+ await writeFile(external, 'initial');
+ await watcher.update(await collect(external), true);
+ await writeFile(external, 'syntax error');
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ await watcher.update([], false);
+ onChange.mockClear();
+ await writeFile(external, 'fixed');
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ const missing = join(root, 'linked', 'new-folder', 'missing.ts');
+ await watcher.update(await collect(missing), false);
+ onChange.mockClear();
+ await mkdir(join(root, 'linked', 'new-folder'));
+ await writeFile(missing, 'created');
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ await watcher.update([], true);
+ onChange.mockClear();
+ await writeFile(external, 'unrelated now');
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('observes recreation of a previously successful external input directory', async () => {
+ const { root, watcher, onChange } = await fixture();
+ const directory = join(root, 'linked', 'nested');
+ const external = join(directory, 'external.ts');
+
+ await mkdir(directory, { recursive: true });
+ await writeFile(external, 'initial');
+ await watcher.update(await collect(external), true);
+ await rm(directory, { recursive: true });
+ await watcher.update(await collect(external), false);
+ onChange.mockClear();
+
+ await mkdir(directory);
+ await writeFile(external, 'restored');
+
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ });
+
+ it('keeps a shallow watch when the tracked directory and its parent disappear', async () => {
+ const { root, watcher, onChange, onError } = await fixture();
+ const parent = join(root, 'linked');
+ const directory = join(parent, 'nested');
+ await mkdir(directory, { recursive: true });
+ const path = await realpath(directory);
+ const inputs = [
+ {
+ path,
+ kind: 'directory' as const,
+ stamp: readWatchInputStamp({ path, kind: 'directory' }),
+ },
+ ];
+ await watcher.update(inputs, true);
+ await rm(parent, { recursive: true });
+ await watcher.update([], false);
+ await vi.waitFor(
+ async () => {
+ onChange.mockClear();
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ { timeout: 3000 },
+ );
+ await mkdir(join(root, 'unrelated'));
+ await writeFile(join(root, 'unrelated', 'ignored.ts'), 'ignored');
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(onChange).not.toHaveBeenCalled();
+ await mkdir(parent);
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ await watcher.update([], false);
+ onChange.mockClear();
+ await mkdir(directory);
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('observes removal of an external directory even with no file inputs', async () => {
+ const { root, watcher, onChange } = await fixture();
+ const directory = join(root, 'empty-linked');
+ await mkdir(directory);
+ const path = await realpath(directory);
+ await watcher.update(
+ [
+ {
+ path,
+ kind: 'directory',
+ stamp: readWatchInputStamp({ path, kind: 'directory' }),
+ },
+ ],
+ false,
+ );
+ await vi.waitFor(
+ async () => {
+ onChange.mockClear();
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ { timeout: 3000 },
+ );
+ onChange.mockClear();
+ await writeFile(join(root, 'unrelated.ts'), 'outside the tracked inputs');
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(onChange).not.toHaveBeenCalled();
+ await rm(directory, { recursive: true });
+ await vi.waitFor(() => expect(onChange).toHaveBeenCalled());
+ });
+
+ it('detects a file replaced by a directory before watcher registration', async () => {
+ const { root, watcher, onChange } = await fixture();
+ const directory = join(root, 'external');
+ await mkdir(directory);
+ await writeFile(join(directory, 'entry'), 'file');
+ const path = await realpath(directory);
+ const stamp = readWatchInputStamp({ path, kind: 'directory' });
+ await rm(join(directory, 'entry'));
+ await mkdir(join(directory, 'entry'));
+ await watcher.update([{ path, kind: 'directory', stamp }], false);
+ expect(onChange).toHaveBeenCalled();
+ });
+
+ it('detects an external edit in the gap between compilation and watcher registration', async () => {
+ const { root, watcher, onChange } = await fixture();
+ const external = join(root, 'external.ts');
+ await writeFile(external, 'before');
+ const inputs = await collect(external);
+ await writeFile(external, 'after');
+ await watcher.update(inputs, true);
+ expect(onChange).toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-cli/src/app/dev/build-dev-snapshot.ts b/packages/twenty-cli/src/app/dev/build-dev-snapshot.ts
new file mode 100644
index 00000000000..53e2d76fd53
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/build-dev-snapshot.ts
@@ -0,0 +1,111 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { createToolingFailure } from '@/app/create-tooling-failure';
+import { retainDevSnapshot } from '@/app/dev/retain-dev-snapshot';
+import { type WatchInputs } from '@/app/dev/types/watch-inputs.type';
+import { parseBuildData, parseToolingResult } from '@/app/parse-tooling-result';
+import { collectSourceFingerprints } from '@/app/pull/collect-source-fingerprints';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { runAppWorker } from '@/app/run-app-worker';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import { CliError } from '@/output/cli-error';
+
+export const buildDevSnapshot = async ({
+ appPath,
+ signal,
+ updateWatchInputs,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+ updateWatchInputs: (inputs: WatchInputs, success: boolean) => Promise<void>;
+}) => {
+ const tooling = await resolveSourceSdk({
+ appPath,
+ });
+ const sourceFingerprints = await collectSourceFingerprints(appPath).catch(
+ () => undefined,
+ );
+ let retained: Awaited<ReturnType<typeof retainDevSnapshot>> | undefined;
+
+ try {
+ const workerRun = await runAppWorker({
+ request: {
+ type: 'bundleSnapshot',
+ appPath,
+ holdSnapshot: true,
+ collectWatchInputs: true,
+ },
+ signal,
+ useHeldSnapshot: async ({ result }) => {
+ const parsed = parseToolingResult({
+ value: result,
+ parseData: parseBuildData,
+ });
+
+ if (parsed.success) {
+ retained = await retainDevSnapshot({
+ build: parsed.data,
+ appPath,
+ signal,
+ });
+ }
+ },
+ });
+ signal.throwIfAborted();
+ const result = parseToolingResult({
+ value: workerRun.result,
+ parseData: parseBuildData,
+ });
+ const diagnostics = [
+ ...result.diagnostics,
+ ...toWorkerOutputDiagnostics(workerRun.output),
+ ];
+
+ await updateWatchInputs(workerRun.watchInputs ?? [], result.success);
+
+ if (!result.success) {
+ throw createToolingFailure({
+ error: result.error,
+ diagnostics,
+ sdkVersion: tooling.version,
+ });
+ }
+
+ if (!isDefined(retained)) {
+ throw new CliError({
+ code: 'WORKER_FAILED',
+ message: 'The build worker did not retain its dev snapshot.',
+ });
+ }
+
+ const releaseResult = workerRun.release;
+
+ if (
+ !isDefined(releaseResult) ||
+ !parseToolingResult({
+ value: releaseResult,
+ parseData: (value) => (value === null ? { data: null } : undefined),
+ }).success
+ ) {
+ throw new CliError({
+ code: 'WORKER_FAILED',
+ message:
+ 'The build worker could not release its source snapshot. Stop and clean up .twenty/cli/snapshots before restarting dev.',
+ });
+ }
+
+ return {
+ ...retained,
+ contentHash: retained.build.contentHash,
+ tooling,
+ diagnostics,
+ sourceFingerprints,
+ };
+ } catch (error) {
+ await retained?.release();
+
+ throw error;
+ }
+};
+
+export type BuiltDevSnapshot = Awaited<ReturnType<typeof buildDevSnapshot>>;
diff --git a/packages/twenty-cli/src/app/dev/collect-watch-inputs.ts b/packages/twenty-cli/src/app/dev/collect-watch-inputs.ts
new file mode 100644
index 00000000000..9bbfa2ff009
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/collect-watch-inputs.ts
@@ -0,0 +1,130 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { realpathSync, statSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+
+import { type Plugin } from 'esbuild';
+import { isDefined } from 'twenty-shared/utils';
+
+import { isIgnoredWatchPath } from '@/app/dev/is-ignored-watch-path';
+import { readWatchInputStamp } from '@/app/dev/read-watch-input-stamp';
+import { type WatchInput } from '@/app/dev/types/watch-inputs.type';
+
+type InputCollection = {
+ inputs: Map<string, WatchInput>;
+ probes: Map<string, WatchInput>;
+};
+
+const watchInputs = new AsyncLocalStorage<InputCollection>();
+
+export const collectWatchInputs = async <TResult>(
+ run: () => Promise<TResult>,
+) => {
+ const inputs = new Map<string, WatchInput>();
+ const probes = new Map<string, WatchInput>();
+ const result = await watchInputs.run({ inputs, probes }, run);
+ const sourceDirectories = new Set(
+ [...inputs.values()]
+ .filter((input) => input.kind === 'file' && input.stamp !== null)
+ .map((input) => dirname(input.path)),
+ );
+
+ for (const [key, probe] of probes) {
+ if (sourceDirectories.has(dirname(probe.path)) && !inputs.has(key)) {
+ inputs.set(key, probe);
+ }
+ }
+
+ return { result, watchInputs: [...inputs.values()] };
+};
+
+const recordInput = (
+ inputs: Map<string, WatchInput>,
+ path: string,
+ kind: WatchInput['kind'],
+) => {
+ let canonicalPath: string;
+
+ try {
+ canonicalPath = realpathSync(path);
+ } catch {
+ canonicalPath = resolve(path);
+ }
+
+ if (isIgnoredWatchPath(canonicalPath)) {
+ return;
+ }
+
+ const key = `${kind}:${canonicalPath}`;
+
+ if (!inputs.has(key)) {
+ const input = { path: canonicalPath, kind };
+
+ inputs.set(key, { ...input, stamp: readWatchInputStamp(input) });
+ }
+
+ return canonicalPath;
+};
+
+const recordParent = (inputs: Map<string, WatchInput>, path: string) => {
+ let parent = dirname(path);
+
+ while (dirname(parent) !== parent) {
+ try {
+ if (statSync(parent).isDirectory()) {
+ recordInput(inputs, parent, 'directory');
+
+ return;
+ }
+ } catch {}
+
+ parent = dirname(parent);
+ }
+};
+
+export const recordWatchFile = (path: string) => {
+ const collection = watchInputs.getStore();
+
+ if (!isDefined(collection)) {
+ return;
+ }
+
+ const canonicalPath = recordInput(collection.inputs, path, 'file');
+ if (isDefined(canonicalPath)) recordParent(collection.inputs, canonicalPath);
+};
+
+export const recordWatchProbe = (path: string) => {
+ const collection = watchInputs.getStore();
+
+ if (isDefined(collection)) recordInput(collection.probes, path, 'file');
+};
+
+export const getWatchInputPlugins = (): Plugin[] => {
+ const collection = watchInputs.getStore();
+
+ if (!isDefined(collection)) {
+ return [];
+ }
+
+ const { inputs } = collection;
+
+ return [
+ {
+ name: 'collect-watch-inputs',
+ setup: (build) => {
+ build.onLoad({ filter: /.*/, namespace: 'file' }, ({ path }) => {
+ const canonicalPath = recordInput(inputs, path, 'file');
+ if (isDefined(canonicalPath)) recordParent(inputs, canonicalPath);
+
+ return undefined;
+ });
+ build.onResolve({ filter: /^\./ }, ({ path, resolveDir }) => {
+ if (resolveDir.length > 0) {
+ recordParent(inputs, resolve(resolveDir, path));
+ }
+
+ return undefined;
+ });
+ },
+ },
+ ];
+};
diff --git a/packages/twenty-cli/src/app/dev/create-dev-output.ts b/packages/twenty-cli/src/app/dev/create-dev-output.ts
new file mode 100644
index 00000000000..12396d62a52
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/create-dev-output.ts
@@ -0,0 +1,64 @@
+import { once } from 'node:events';
+
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatWarningLine } from '@/output/style';
+import { type Output } from '@/output/types/output.type';
+
+export const createDevOutput = (context: TargetCommandContext) => {
+ const messages: { message: string; code?: string }[] = [];
+ let delivery = Promise.resolve();
+ let omittedMessages = 0;
+ const output: Output = {
+ ...context.output,
+ progress: (message) => {
+ if (messages.length < 32) messages.push({ message });
+ else omittedMessages += 1;
+ },
+ warn: (warning) => {
+ if (messages.length < 32) messages.push(warning);
+ else omittedMessages += 1;
+ },
+ };
+ const emit = (
+ event: { kind: string; message: string; [key: string]: unknown },
+ signal: AbortSignal,
+ ) => {
+ const pendingMessages = messages.splice(0);
+ if (omittedMessages > 0) {
+ pendingMessages.push({
+ message: `${omittedMessages} additional progress messages omitted.`,
+ });
+ omittedMessages = 0;
+ }
+ const next = delivery.then(async () => {
+ signal.throwIfAborted();
+
+ if (context.outputMode === 'ndjson') {
+ await context.output.event(
+ 'progress',
+ { ...event, messages: pendingMessages },
+ signal,
+ );
+ } else {
+ const text = [
+ ...pendingMessages.map((message) =>
+ message.code ? formatWarningLine(message.message) : message.message,
+ ),
+ event.message,
+ ]
+ .filter((message) => message.length > 0)
+ .join('\n');
+
+ if (!process.stderr.write(`${text}\n`)) {
+ await once(process.stderr, 'drain', { signal });
+ }
+ }
+ });
+
+ delivery = next.catch(() => undefined);
+
+ return next;
+ };
+
+ return { output, emit };
+};
diff --git a/packages/twenty-cli/src/app/dev/generate-dev-client.ts b/packages/twenty-cli/src/app/dev/generate-dev-client.ts
new file mode 100644
index 00000000000..02c3df23d79
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/generate-dev-client.ts
@@ -0,0 +1,158 @@
+import { createHash } from 'node:crypto';
+import { readFile, realpath } from 'node:fs/promises';
+import { join } from 'node:path';
+import { createRequire } from 'node:module';
+import { resolveInsideSdk } from '@/app/project/resolve-inside-sdk';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AppApplyResult } from '@/app/deployment/apply-app-build';
+import { createPostSyncFailure } from '@/app/deployment/create-post-sync-failure';
+import { readGeneratedClientStamp } from '@/app/dev/read-generated-client-stamp';
+import { type BuiltDevSnapshot } from '@/app/dev/build-dev-snapshot';
+import {
+ fetchAppClientSchema,
+ generateAppClientFromSchema,
+} from '@/app/generate-app-client';
+import { getClientGenerationSkipReason } from '@/app/get-client-generation-skip-reason';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { withPhaseDetails } from '@/app/deployment/with-phase-details';
+import { toCliError } from '@/output/to-cli-error';
+
+export const createDevClientGenerator = ({ appPath }: { appPath: string }) => {
+ let generatedKey: string | undefined;
+ let generatedOutputStamp: string | undefined;
+ const readGeneratedOutputStamp = () =>
+ readGeneratedClientStamp(
+ join(appPath, 'node_modules', 'twenty-client-sdk'),
+ );
+
+ return async ({
+ snapshot,
+ applied,
+ context,
+ withBuildsPaused,
+ invalidate,
+ }: {
+ snapshot: BuiltDevSnapshot;
+ applied: AppApplyResult;
+ context: TargetCommandContext;
+ withBuildsPaused: <TResult>(
+ run: () => Promise<TResult>,
+ ) => Promise<TResult>;
+ invalidate: () => void;
+ }) => {
+ const skipReason = await getClientGenerationSkipReason({
+ appPath,
+ });
+
+ if (isDefined(skipReason)) {
+ context.output.warn({
+ code: 'CLIENT_NOT_GENERATED',
+ message: skipReason,
+ });
+
+ return 'skipped';
+ }
+
+ let schema: string;
+ let generationKey: string;
+ let currentGeneratedOutputStamp: string;
+
+ try {
+ schema = await fetchAppClientSchema({
+ applicationUniversalIdentifier: applied.acknowledgedUniversalIdentifier,
+ context,
+ });
+ const packageRoot = await realpath(
+ join(appPath, 'node_modules', 'twenty-client-sdk'),
+ );
+ const packageJson = await readFile(join(packageRoot, 'package.json'));
+
+ const generatorPath = resolveInsideSdk({
+ resolveFromApp: createRequire(join(packageRoot, 'package.json'))
+ .resolve,
+ specifier: 'twenty-client-sdk/generate',
+ sdkPath: packageRoot,
+ });
+
+ if (!isDefined(generatorPath)) {
+ throw new Error(
+ 'The installed twenty-client-sdk has no compatible generate entry point.',
+ );
+ }
+
+ generationKey = createHash('sha256')
+ .update(schema)
+ .update(packageRoot)
+ .update(packageJson)
+ .update(await readFile(generatorPath))
+ .digest('hex');
+ currentGeneratedOutputStamp = await readGeneratedOutputStamp();
+ } catch (error) {
+ if (context.signal.aborted) {
+ throw withPhaseDetails({
+ error: toCliError(error, context.signal),
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: applied.completedPhases,
+ hint: 'The app was synced. Client generation had not started, so the previous typed API client was kept.',
+ });
+ }
+
+ context.output.warn({
+ code: 'CLIENT_NOT_GENERATED',
+ message: `The app was synced, but its client inputs could not be fetched: ${toCliError(error).message} The previous client was kept.`,
+ });
+
+ return 'skipped';
+ }
+
+ if (
+ generationKey === generatedKey &&
+ currentGeneratedOutputStamp === generatedOutputStamp
+ ) {
+ return 'unchanged';
+ }
+
+ let hasStartedGeneration = false;
+
+ try {
+ await withBuildsPaused(async () => {
+ context.signal.throwIfAborted();
+ hasStartedGeneration = true;
+ await generateAppClientFromSchema({
+ appPath,
+ schema,
+ sdk: snapshot.tooling,
+ context,
+ });
+ generatedKey = generationKey;
+ generatedOutputStamp = await readGeneratedOutputStamp();
+ applied.completedPhases.push('clientGeneration');
+ invalidate();
+ });
+ } catch (error) {
+ if (!hasStartedGeneration) {
+ throw withPhaseDetails({
+ error: toCliError(error, context.signal),
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: applied.completedPhases,
+ hint: 'The app was synced. Client generation had not started, so the previous typed API client was kept.',
+ });
+ }
+
+ throw createPostSyncFailure({
+ error,
+ phase: 'clientGeneration',
+ applicationName: snapshot.build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ completedPhases: applied.completedPhases,
+ signal: context.signal,
+ });
+ }
+
+ return 'generated';
+ };
+};
diff --git a/packages/twenty-cli/src/app/dev/is-ignored-watch-path.ts b/packages/twenty-cli/src/app/dev/is-ignored-watch-path.ts
new file mode 100644
index 00000000000..8d1d7bd27a9
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/is-ignored-watch-path.ts
@@ -0,0 +1,8 @@
+import { basename, sep } from 'node:path';
+
+const IGNORED_DIRECTORIES = new Set(['node_modules', '.git', '.twenty']);
+
+export const isIgnoredWatchPath = (filePath: string) =>
+ filePath.split(sep).some((part) => IGNORED_DIRECTORIES.has(part)) ||
+ basename(filePath) === '.DS_Store' ||
+ /(?:~|\.sw[a-z]|\.tmp)$/.test(basename(filePath));
diff --git a/packages/twenty-cli/src/app/dev/read-generated-client-stamp.ts b/packages/twenty-cli/src/app/dev/read-generated-client-stamp.ts
new file mode 100644
index 00000000000..bb085f39080
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/read-generated-client-stamp.ts
@@ -0,0 +1,46 @@
+import { readFile, readdir } from 'node:fs/promises';
+import { join, relative } from 'node:path';
+
+import { hashContent } from '@/utils/hash-content';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const readGeneratedClientStamp = async (
+ packageRoot: string,
+): Promise<string> => {
+ const readFileHash = async (path: string): Promise<string | null> => {
+ try {
+ return hashContent(await readFile(path));
+ } catch (error) {
+ if (hasErrorCode(error, 'ENOENT')) return null;
+ throw error;
+ }
+ };
+ const paths = ['dist/core.mjs', 'dist/core.cjs'];
+ const generatedDirectory = join(packageRoot, 'dist/core/generated');
+
+ try {
+ const entries = await readdir(generatedDirectory, {
+ recursive: true,
+ withFileTypes: true,
+ });
+
+ for (const entry of entries) {
+ if (entry.isFile() || entry.isSymbolicLink()) {
+ paths.push(relative(packageRoot, join(entry.parentPath, entry.name)));
+ }
+ }
+ } catch (error) {
+ if (!hasErrorCode(error, 'ENOENT')) throw error;
+ }
+
+ return JSON.stringify(
+ await Promise.all(
+ paths
+ .sort()
+ .map(async (path) => [
+ path,
+ await readFileHash(join(packageRoot, path)),
+ ]),
+ ),
+ );
+};
diff --git a/packages/twenty-cli/src/app/dev/read-watch-input-stamp.ts b/packages/twenty-cli/src/app/dev/read-watch-input-stamp.ts
new file mode 100644
index 00000000000..80a8da9d4ba
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/read-watch-input-stamp.ts
@@ -0,0 +1,34 @@
+import { readdirSync, statSync } from 'node:fs';
+
+import { isIgnoredWatchPath } from '@/app/dev/is-ignored-watch-path';
+
+import { type WatchInput } from '@/app/dev/types/watch-inputs.type';
+
+export const readWatchInputStamp = ({
+ path,
+ kind,
+}: Pick<WatchInput, 'path' | 'kind'>): string | null => {
+ try {
+ if (kind === 'directory') {
+ return JSON.stringify(
+ readdirSync(path, { withFileTypes: true })
+ .filter((entry) => !isIgnoredWatchPath(entry.name))
+ .map((entry) => [
+ entry.name,
+ entry.isDirectory(),
+ entry.isFile(),
+ entry.isSymbolicLink(),
+ ])
+ .sort(([first], [second]) =>
+ String(first).localeCompare(String(second)),
+ ),
+ );
+ }
+
+ const stat = statSync(path, { bigint: true });
+
+ return `${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/twenty-cli/src/app/dev/record-typecheck-config-inputs.ts b/packages/twenty-cli/src/app/dev/record-typecheck-config-inputs.ts
new file mode 100644
index 00000000000..63ee6b392d5
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/record-typecheck-config-inputs.ts
@@ -0,0 +1,25 @@
+import { join } from 'node:path';
+
+import { recordWatchFile } from '@/app/dev/collect-watch-inputs';
+import { resolveProjectTypeScript } from '@/app/typecheck/resolve-project-typescript';
+
+export const recordTypecheckConfigInputs = async (appPath: string) => {
+ try {
+ const typescript = await resolveProjectTypeScript(appPath);
+ const configPath = join(appPath, 'tsconfig.json');
+ const readFile: typeof typescript.sys.readFile = (path, encoding) => {
+ recordWatchFile(path);
+
+ return typescript.sys.readFile(path, encoding);
+ };
+ const config = typescript.readConfigFile(configPath, readFile);
+
+ typescript.parseJsonConfigFileContent(
+ config.config ?? {},
+ { ...typescript.sys, readFile },
+ appPath,
+ undefined,
+ configPath,
+ );
+ } catch {}
+};
diff --git a/packages/twenty-cli/src/app/dev/retain-dev-snapshot.ts b/packages/twenty-cli/src/app/dev/retain-dev-snapshot.ts
new file mode 100644
index 00000000000..e8100109e15
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/retain-dev-snapshot.ts
@@ -0,0 +1,53 @@
+import { readBlobChunks } from '@/utils/read-blob-chunks';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+
+import { readSnapshotFile } from '@/app/deployment/read-snapshot-file';
+import { resolveSnapshotDirectory } from '@/app/deployment/resolve-snapshot-directory';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+
+export const retainDevSnapshot = async ({
+ build,
+ appPath,
+ signal,
+}: {
+ build: ToolingBuild;
+ appPath: string;
+ signal: AbortSignal;
+}) => {
+ signal.throwIfAborted();
+ const sourceDirectory = resolveSnapshotDirectory({
+ build,
+ appPath,
+ });
+ const root = join(appPath, '.twenty', 'cli', 'snapshots');
+
+ await mkdir(root, { recursive: true });
+ const directory = await mkdtemp(join(root, 'dev-'));
+ const release = () => rm(directory, { recursive: true, force: true });
+
+ try {
+ for (const artifact of build.files) {
+ signal.throwIfAborted();
+ const bytes = await readSnapshotFile({
+ snapshotDirectory: sourceDirectory,
+ artifact,
+ });
+ const destination = join(directory, artifact.path);
+
+ await mkdir(dirname(destination), { recursive: true });
+ await writeFile(destination, readBlobChunks(bytes), {
+ flag: 'wx',
+ signal,
+ });
+ }
+
+ signal.throwIfAborted();
+
+ return { build: { ...build, directory }, release };
+ } catch (error) {
+ await release();
+
+ throw error;
+ }
+};
diff --git a/packages/twenty-cli/src/app/dev/run-dev-loop.ts b/packages/twenty-cli/src/app/dev/run-dev-loop.ts
new file mode 100644
index 00000000000..ee502d3004e
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/run-dev-loop.ts
@@ -0,0 +1,205 @@
+import { setTimeout } from 'node:timers/promises';
+
+import { isDefined } from 'twenty-shared/utils';
+
+export type DevSnapshot = {
+ contentHash: string;
+ release: () => Promise<void>;
+};
+
+export const runDevLoop = async <TSnapshot extends DevSnapshot>({
+ signal,
+ subscribe,
+ build,
+ apply,
+ onSkipped,
+ debounceMilliseconds = 100,
+}: {
+ signal: AbortSignal;
+ subscribe: (
+ invalidate: () => void,
+ fail: (error: unknown) => void,
+ ) => Promise<() => Promise<void>>;
+ build: (
+ revision: number,
+ signal: AbortSignal,
+ ) => Promise<TSnapshot | undefined>;
+ apply: (
+ snapshot: TSnapshot,
+ controls: {
+ revision: number;
+ signal: AbortSignal;
+ revisionSignal: AbortSignal;
+ withBuildsPaused: <TResult>(
+ run: () => Promise<TResult>,
+ ) => Promise<TResult>;
+ invalidate: () => void;
+ },
+ ) => Promise<boolean>;
+ onSkipped: (
+ revision: number,
+ reason: 'superseded' | 'unchanged',
+ ) => Promise<void>;
+ debounceMilliseconds?: number;
+}) => {
+ const stopped = new AbortController();
+ let terminalError: unknown;
+ const stop = (error: unknown) => {
+ stopped.abort(error);
+ wake();
+ };
+ const interrupted = () => stop(signal.reason);
+ const waiters = new Set<() => void>();
+ const wake = () => {
+ for (const waiter of waiters) {
+ waiter();
+ }
+ };
+ const waitFor = async (predicate: () => boolean) => {
+ while (!predicate()) {
+ stopped.signal.throwIfAborted();
+ await new Promise<void>((resolve) => {
+ const waiter = () => {
+ waiters.delete(waiter);
+ resolve();
+ };
+
+ waiters.add(waiter);
+ });
+ }
+
+ stopped.signal.throwIfAborted();
+ };
+ let revision = 1;
+ let attemptedRevision = 0;
+ let pending: { snapshot: TSnapshot; revision: number } | undefined;
+ let isBuilding = false;
+ let areBuildsPaused = false;
+ let approval = new AbortController();
+ let acknowledgedHash: string | undefined;
+ const invalidate = () => {
+ revision += 1;
+ approval.abort(new Error('App changed while awaiting approval.'));
+ wake();
+ };
+ const buildLoop = async () => {
+ while (!stopped.signal.aborted) {
+ await waitFor(() => !areBuildsPaused && revision !== attemptedRevision);
+ const nextRevision = revision;
+
+ await setTimeout(debounceMilliseconds, undefined, {
+ signal: stopped.signal,
+ });
+
+ if (nextRevision !== revision || areBuildsPaused) {
+ continue;
+ }
+
+ attemptedRevision = nextRevision;
+ isBuilding = true;
+ let snapshot: TSnapshot | undefined;
+
+ try {
+ if (isDefined(pending)) {
+ await pending.snapshot.release();
+ pending = undefined;
+ }
+
+ snapshot = await build(
+ nextRevision,
+ AbortSignal.any([signal, stopped.signal]),
+ );
+
+ if (isDefined(snapshot)) {
+ if (nextRevision !== revision || stopped.signal.aborted) {
+ await snapshot.release();
+ await onSkipped(nextRevision, 'superseded');
+ } else {
+ pending = { snapshot, revision: nextRevision };
+ }
+ }
+ } finally {
+ isBuilding = false;
+ wake();
+ }
+ }
+ };
+ const applyLoop = async () => {
+ while (!stopped.signal.aborted) {
+ await waitFor(() => isDefined(pending) && pending.revision === revision);
+ const ready = pending;
+
+ if (!isDefined(ready)) {
+ continue;
+ }
+
+ pending = undefined;
+ approval = new AbortController();
+
+ try {
+ if (ready.snapshot.contentHash === acknowledgedHash) {
+ await onSkipped(ready.revision, 'unchanged');
+
+ continue;
+ }
+
+ const applied = await apply(ready.snapshot, {
+ revision: ready.revision,
+ signal: AbortSignal.any([signal, stopped.signal]),
+ revisionSignal: AbortSignal.any([
+ signal,
+ stopped.signal,
+ approval.signal,
+ ]),
+ invalidate,
+ withBuildsPaused: async (run) => {
+ areBuildsPaused = true;
+
+ try {
+ await waitFor(() => !isBuilding);
+
+ return await run();
+ } finally {
+ areBuildsPaused = false;
+ wake();
+ }
+ },
+ });
+
+ acknowledgedHash = applied ? ready.snapshot.contentHash : undefined;
+ } finally {
+ await ready.snapshot.release();
+ }
+ }
+ };
+
+ signal.addEventListener('abort', interrupted, { once: true });
+ let unsubscribe: (() => Promise<void>) | undefined;
+
+ try {
+ signal.throwIfAborted();
+ unsubscribe = await subscribe(invalidate, stop);
+ const tasks = [
+ buildLoop().catch((error: unknown) => {
+ if (!signal.aborted && !isDefined(terminalError)) terminalError = error;
+ stop(error);
+ }),
+ applyLoop().catch((error: unknown) => {
+ terminalError = error;
+ stop(error);
+ }),
+ ];
+
+ await Promise.all(tasks);
+ if (isDefined(terminalError)) throw terminalError;
+ stopped.signal.throwIfAborted();
+ } finally {
+ stop(signal.reason);
+ signal.removeEventListener('abort', interrupted);
+ try {
+ await unsubscribe?.();
+ } finally {
+ await pending?.snapshot.release();
+ }
+ }
+};
diff --git a/packages/twenty-cli/src/app/dev/types/watch-inputs.type.ts b/packages/twenty-cli/src/app/dev/types/watch-inputs.type.ts
new file mode 100644
index 00000000000..5783898e11e
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/types/watch-inputs.type.ts
@@ -0,0 +1,7 @@
+export type WatchInput = {
+ path: string;
+ kind: 'file' | 'directory';
+ stamp: string | null;
+};
+
+export type WatchInputs = WatchInput[];
diff --git a/packages/twenty-cli/src/app/dev/watch-app-inputs.ts b/packages/twenty-cli/src/app/dev/watch-app-inputs.ts
new file mode 100644
index 00000000000..ab1fda394a3
--- /dev/null
+++ b/packages/twenty-cli/src/app/dev/watch-app-inputs.ts
@@ -0,0 +1,181 @@
+import { realpath } from 'node:fs/promises';
+import { dirname, relative, resolve, sep } from 'node:path';
+
+import { watch, type FSWatcher } from 'chokidar';
+
+import { isIgnoredWatchPath } from '@/app/dev/is-ignored-watch-path';
+import { readWatchInputStamp } from '@/app/dev/read-watch-input-stamp';
+import { type WatchInputs } from '@/app/dev/types/watch-inputs.type';
+import { pathExistsSync } from '@/app/fs-utils';
+import { isInsideDirectory } from '@/utils/is-inside-directory';
+
+const waitUntilReady = (watcher: FSWatcher, signal: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ const cleanup = () => {
+ watcher.off('ready', ready);
+ watcher.off('error', failed);
+ signal.removeEventListener('abort', aborted);
+ };
+ const ready = () => {
+ cleanup();
+ resolve();
+ };
+ const failed = (error: Error) => {
+ cleanup();
+ reject(error);
+ };
+ const aborted = () => {
+ cleanup();
+ reject(signal.reason);
+ };
+
+ watcher.once('ready', ready);
+ watcher.once('error', failed);
+ signal.addEventListener('abort', aborted, { once: true });
+
+ if (signal.aborted) {
+ aborted();
+ }
+ });
+
+export const watchAppInputs = async ({
+ appPath,
+ signal,
+ onChange,
+ onError,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+ onChange: () => void;
+ onError: (error: Error) => void;
+}) => {
+ appPath = await realpath(appPath);
+ const rootWatcher = watch(appPath, {
+ ignoreInitial: true,
+ followSymlinks: false,
+ ignored: (path) =>
+ relative(appPath, path).split(sep)[0] === 'dist' ||
+ isIgnoredWatchPath(relative(appPath, path)),
+ atomic: true,
+ })
+ .on('all', onChange)
+ .on('error', onError);
+ let externalWatcher: FSWatcher | undefined;
+ let successfulInputs: WatchInputs = [];
+
+ const close = async () => {
+ await Promise.all([rootWatcher.close(), externalWatcher?.close()]);
+ };
+
+ try {
+ await waitUntilReady(rootWatcher, signal);
+ } catch (error) {
+ await close();
+
+ throw error;
+ }
+
+ return {
+ close,
+ update: async (inputs: WatchInputs, success: boolean) => {
+ if (success) {
+ successfulInputs = inputs;
+ }
+
+ const externalInputs = [...successfulInputs, ...inputs].filter(
+ (input) =>
+ input.path !== appPath &&
+ !isInsideDirectory({ filePath: input.path, directory: appPath }),
+ );
+ const directories = new Set(
+ externalInputs
+ .filter((input) => input.kind === 'directory')
+ .map((input) => input.path),
+ );
+ const files = new Set(
+ externalInputs
+ .filter((input) => input.kind === 'file')
+ .map((input) => input.path),
+ );
+ const parentDirectories = new Set<string>();
+ const missingDirectories = new Set<string>();
+
+ for (const input of externalInputs) {
+ let parent = dirname(input.path);
+
+ while (!pathExistsSync(parent) && dirname(parent) !== parent) {
+ missingDirectories.add(parent);
+ parent = dirname(parent);
+ }
+
+ parentDirectories.add(parent);
+ }
+ const isDirectChild = (path: string) =>
+ [...directories].some((directory) => {
+ const child = relative(directory, path);
+ return child.length > 0 && child !== '..' && !child.includes(sep);
+ });
+ // Node's watcher needs the parent to observe an empty directory disappearing.
+ const paths = [
+ ...new Set([
+ ...externalInputs.map((input) => input.path),
+ ...parentDirectories,
+ ]),
+ ].filter(pathExistsSync);
+ const previousWatcher = externalWatcher;
+
+ if (paths.length > 0) {
+ const nextWatcher = watch(paths, {
+ ignoreInitial: true,
+ followSymlinks: false,
+ depth: 0,
+ atomic: true,
+ ignored: (path) => {
+ const absolutePath = resolve(path);
+ return (
+ isIgnoredWatchPath(path) ||
+ !(
+ parentDirectories.has(absolutePath) ||
+ directories.has(absolutePath) ||
+ missingDirectories.has(absolutePath) ||
+ files.has(absolutePath) ||
+ isDirectChild(absolutePath)
+ )
+ );
+ },
+ })
+ .on('all', (event, path) => {
+ const absolutePath = resolve(path);
+
+ if (
+ files.has(absolutePath) ||
+ (event !== 'change' &&
+ (isDirectChild(absolutePath) ||
+ directories.has(absolutePath) ||
+ missingDirectories.has(absolutePath)))
+ ) {
+ onChange();
+ }
+ })
+ .on('error', onError);
+
+ externalWatcher = nextWatcher;
+ try {
+ await waitUntilReady(nextWatcher, signal);
+ } catch (error) {
+ await previousWatcher?.close();
+
+ throw error;
+ }
+ } else {
+ externalWatcher = undefined;
+ }
+
+ await previousWatcher?.close();
+
+ if (inputs.some((input) => readWatchInputStamp(input) !== input.stamp)) {
+ onChange();
+ }
+ },
+ };
+};
diff --git a/packages/twenty-cli/src/app/exec/README.md b/packages/twenty-cli/src/app/exec/README.md
new file mode 100644
index 00000000000..bf7e81c1fe0
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/README.md
@@ -0,0 +1,48 @@
+# CLI app function execution
+
+The command selects one deployed function from the
+local app's identifiers, executes it once with a payload, and reports status,
+duration, data, error and logs. Name matching is exact. Hooks select their
+function identifier; executing an uninstall hook does not uninstall the app.
+A non-SUCCESS result exits with failure. It executes deployed code, so local
+edits must be synced with apply or dev first.
+
+## Contract
+
+- Flags follow the space-separated command surface and kebab-case convention:
+ `app exec --name`, `--universal-identifier`, `--post-install`, `--pre-install`
+ or `--uninstall-hook`. Exactly one selector is required.
+- The CLI keeps no saved build manifest. It uses the `buildManifest`
+ worker to load definitions with the app's authoring SDK, without bundling or
+ typechecking. Worker output becomes diagnostics; credentials are not passed to it.
+- Function selection checks both the local manifest identifiers and the remote
+ installed application's ID. The `findOneApplication` lookup prevents
+ copied or stale identifiers from selecting another installed app's function.
+ This needs `APPLICATIONS` in addition to execution's `WORKFLOWS` permission.
+- The current server requires a user-bound token for execution. Browser-login
+ OAuth remotes are supported; API-key targets fail before loading app source.
+ The server still decides which functions that user can run: workspace custom
+ app functions, functions exposed as workflow actions, or functions from an
+ app registered by this workspace. The CLI does not bypass those checks.
+- Payloads use the JSON-object input reader: inline JSON, `@file` or
+ `-` for stdin, default `{}`. Non-object values are rejected.
+- Human output escapes terminal controls. JSON success includes function/app
+ identity, status, `durationMilliseconds`, data, logs, error and diagnostics.
+ A completed non-SUCCESS result exits 1 with `EXECUTION_FAILED` and retains
+ that information in `error.details`, with `outcome: "completed"`. A missing
+ function exits 4; ambiguous selection exits 6; bad input exits 2.
+- The execution request deadline is the deployed function's `timeoutSeconds`
+ plus the transport's 60-second allowance. Its HTTP dispatcher header/body
+ deadlines use the same value, avoiding Node's default five-minute cutoff.
+ Other commands use their own deadlines and lazy transport loading.
+ Proxies and the server can still close a request earlier.
+- Execution is never retried. Acknowledged authentication, permission,
+ not-found and input/validation rejections have `outcome: "not-started"`.
+ Transport failure, cancellation, internal server error or an invalid response
+ after submission have `outcome: "unknown"`: execution may still be running.
+ Ctrl+C exits 130 and cannot stop the server-side function or undo its effects.
+
+Command tests use the public command runner and real HTTP metadata transport,
+with controlled worker results. They cover selection, application binding,
+payloads, returned errors, rejection/unknown outcomes, cancellation and no
+replay. These tests do not establish live workspace authorization or execution.
diff --git a/packages/twenty-cli/src/app/exec/execute-app-function.ts b/packages/twenty-cli/src/app/exec/execute-app-function.ts
new file mode 100644
index 00000000000..56e7654a934
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/execute-app-function.ts
@@ -0,0 +1,231 @@
+import { isArray, isNumber, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { createAppNotInstalledError } from '@/app/create-app-not-installed-error';
+import { type ExecManifest } from '@/app/exec/read-exec-manifest';
+import { type AppFunctionSelector } from '@/app/exec/types/app-function-selector.type';
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { toCliError } from '@/output/to-cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { REQUEST_TIMEOUT_MILLISECONDS } from '@/transport/constants/request-timeout-milliseconds.constant';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+type LogicFunction = {
+ id: string;
+ name: string;
+ universalIdentifier: string | null;
+ applicationId: string | null;
+ timeoutSeconds: number;
+};
+
+const isLogicFunction = (value: unknown): value is LogicFunction =>
+ isPlainObject(value) &&
+ isString(value.id) &&
+ isString(value.name) &&
+ (isString(value.universalIdentifier) || value.universalIdentifier === null) &&
+ (isString(value.applicationId) || value.applicationId === null) &&
+ isNumber(value.timeoutSeconds) &&
+ Number.isFinite(value.timeoutSeconds) &&
+ value.timeoutSeconds >= 0 &&
+ Math.ceil(value.timeoutSeconds * 1000) + REQUEST_TIMEOUT_MILLISECONDS <
+ 2 ** 31;
+
+const invalidResponse = () =>
+ new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid logic-function response.',
+ });
+
+const wasExecutionRejected = (error: CliError) => {
+ if (['AUTH_REQUIRED', 'PERMISSION_DENIED'].includes(error.code)) {
+ return true;
+ }
+
+ const errors = error.details?.errors;
+
+ return (
+ error.code === 'GRAPHQL_ERROR' &&
+ isArray(errors) &&
+ errors.length > 0 &&
+ errors.every(
+ (entry: unknown) =>
+ isPlainObject(entry) &&
+ isString(entry.code) &&
+ ['NOT_FOUND', 'BAD_USER_INPUT', 'GRAPHQL_VALIDATION_FAILED'].includes(
+ entry.code,
+ ),
+ )
+ );
+};
+
+export const executeAppFunction = async ({
+ manifest,
+ selector,
+ payload,
+ target,
+ signal,
+ onExecuting,
+}: {
+ manifest: ExecManifest;
+ selector: AppFunctionSelector;
+ payload: Record<string, unknown>;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ onExecuting: (name: string) => void;
+}) => {
+ const client = createMetadataClient({ target, signal });
+ const { applicationUniversalIdentifier } = manifest;
+ const {
+ findOneApplication: application,
+ findManyLogicFunctions: logicFunctions,
+ } = await client
+ .query({
+ findOneApplication: {
+ __args: { universalIdentifier: applicationUniversalIdentifier },
+ id: true,
+ universalIdentifier: true,
+ },
+ findManyLogicFunctions: {
+ id: true,
+ name: true,
+ universalIdentifier: true,
+ applicationId: true,
+ timeoutSeconds: true,
+ },
+ })
+ .catch((error: unknown) => {
+ if (isApplicationNotFoundError({ error, field: 'findOneApplication' })) {
+ throw createAppNotInstalledError({
+ universalIdentifier: applicationUniversalIdentifier,
+ apiUrl: target.apiUrl,
+ });
+ }
+ throw error;
+ });
+
+ if (
+ !isPlainObject(application) ||
+ !isString(application.id) ||
+ !isSameUniversalIdentifier({
+ value: application.universalIdentifier,
+ universalIdentifier: applicationUniversalIdentifier,
+ }) ||
+ !isArray(logicFunctions) ||
+ !logicFunctions.every(isLogicFunction)
+ ) {
+ throw invalidResponse();
+ }
+
+ const appFunctions = logicFunctions.filter(
+ (logicFunction) =>
+ logicFunction.applicationId === application.id &&
+ isDefined(logicFunction.universalIdentifier) &&
+ manifest.universalIdentifiers.includes(
+ logicFunction.universalIdentifier.toLowerCase(),
+ ),
+ );
+ const identifier =
+ selector.kind === 'hook' ? manifest.hooks[selector.value] : selector.value;
+ const matches = appFunctions.filter(
+ (logicFunction) =>
+ isDefined(identifier) &&
+ (selector.kind === 'name'
+ ? logicFunction.name === identifier
+ : logicFunction.universalIdentifier?.toLowerCase() === identifier),
+ );
+
+ if (matches.length === 0) {
+ throw new CliError({
+ code: 'NOT_FOUND',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: `Function "${selector.value}" was not found in the deployed app.`,
+ hint: 'Check the selected workspace and function. Run twenty app apply or twenty app dev to sync local changes first.',
+ details: {
+ identifier: selector.value,
+ availableFunctions: appFunctions.map(
+ ({ name, universalIdentifier }) => ({ name, universalIdentifier }),
+ ),
+ },
+ });
+ }
+ if (matches.length > 1) {
+ throw new CliError({
+ code: 'AMBIGUOUS_RESOURCE',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `More than one app function matches "${selector.value}".`,
+ hint: 'Select a function with --universal-identifier.',
+ });
+ }
+
+ const logicFunction = matches[0];
+ const identity = {
+ applicationUniversalIdentifier,
+ functionName: logicFunction.name,
+ functionUniversalIdentifier: logicFunction.universalIdentifier,
+ };
+ onExecuting(logicFunction.name);
+ signal.throwIfAborted();
+ const executionClient = createMetadataClient({
+ target,
+ signal,
+ timeoutMilliseconds:
+ Math.ceil(logicFunction.timeoutSeconds * 1000) +
+ REQUEST_TIMEOUT_MILLISECONDS,
+ });
+
+ try {
+ const { executeOneLogicFunction: result } = await executionClient.mutation({
+ executeOneLogicFunction: {
+ __args: { input: { id: logicFunction.id, payload } },
+ data: true,
+ logs: true,
+ duration: true,
+ status: true,
+ error: true,
+ },
+ });
+
+ if (
+ !isPlainObject(result) ||
+ !isString(result.status) ||
+ !isString(result.logs) ||
+ !isNumber(result.duration) ||
+ !Number.isFinite(result.duration) ||
+ result.duration < 0
+ ) {
+ throw invalidResponse();
+ }
+
+ return {
+ ...identity,
+ status: result.status,
+ durationMilliseconds: result.duration,
+ data: result.data ?? null,
+ logs: result.logs,
+ error: result.error ?? null,
+ };
+ } catch (error) {
+ const cliError = toCliError(error, signal);
+ const rejected = wasExecutionRejected(cliError);
+ throw new CliError({
+ code: cliError.code,
+ exitCode: cliError.exitCode,
+ message: cliError.message,
+ hint: rejected
+ ? cliError.hint
+ : 'Execution may have started and may still be running. Check its effects before retrying; this command does not retry or stop server-side execution.',
+ details: {
+ ...cliError.details,
+ ...identity,
+ outcome: rejected ? 'not-started' : 'unknown',
+ },
+ });
+ }
+};
+
+export type AppFunctionExecution = Awaited<
+ ReturnType<typeof executeAppFunction>
+>;
diff --git a/packages/twenty-cli/src/app/exec/format-function-execution.ts b/packages/twenty-cli/src/app/exec/format-function-execution.ts
new file mode 100644
index 00000000000..de760cb81bb
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/format-function-execution.ts
@@ -0,0 +1,25 @@
+import { type AppFunctionExecution } from '@/app/exec/execute-app-function';
+import { formatDataValue } from '@/data/format-data-value';
+
+const formatExecutionValue = (value: unknown) =>
+ JSON.stringify(value, null, 2).replace(
+ /[\x7f-\x9f]/g,
+ (character) =>
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,
+ );
+
+export const formatFunctionExecution = (result: AppFunctionExecution) =>
+ [
+ `Function: ${formatDataValue(result.functionName)}`,
+ `Status: ${formatDataValue(result.status)}`,
+ `Duration: ${result.durationMilliseconds}ms`,
+ ...(result.data !== null
+ ? ['Data:', formatExecutionValue(result.data)]
+ : []),
+ ...(result.error !== null
+ ? ['Error:', formatExecutionValue(result.error)]
+ : []),
+ ...(result.logs.length > 0
+ ? ['Logs:', ...result.logs.split('\n').map(formatDataValue)]
+ : []),
+ ].join('\n');
diff --git a/packages/twenty-cli/src/app/exec/read-exec-manifest.ts b/packages/twenty-cli/src/app/exec/read-exec-manifest.ts
new file mode 100644
index 00000000000..c2168c27412
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/read-exec-manifest.ts
@@ -0,0 +1,104 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { createToolingFailure } from '@/app/create-tooling-failure';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { parseToolingResult } from '@/app/parse-tooling-result';
+import { isExportedManifest } from '@/app/pull/is-exported-manifest';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { runAppWorker } from '@/app/run-app-worker';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+
+export const readExecManifest = async ({
+ options,
+ output,
+ outputMode,
+ signal,
+}: CommandContext) => {
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const sdk = await resolveSourceSdk({ appPath: project.path });
+
+ output.progress(`Reading app definitions in ${project.path}…`);
+ const worker = await runAppWorker({
+ request: { type: 'buildManifest', appPath: project.path },
+ signal,
+ });
+ signal.throwIfAborted();
+ const result = parseToolingResult({
+ value: worker.result,
+ parseData: (value) => {
+ if (!isPlainObject(value) || !isExportedManifest(value.manifest)) {
+ return;
+ }
+ const { manifest } = value;
+ if (!isArray(manifest.logicFunctions)) {
+ return;
+ }
+
+ const universalIdentifiers: string[] = [];
+ for (const logicFunction of manifest.logicFunctions) {
+ if (
+ !isPlainObject(logicFunction) ||
+ !isString(logicFunction.universalIdentifier)
+ ) {
+ return;
+ }
+ universalIdentifiers.push(
+ logicFunction.universalIdentifier.toLowerCase(),
+ );
+ }
+
+ const hooks: Record<string, string> = {};
+ for (const key of [
+ 'postInstallLogicFunction',
+ 'preInstallLogicFunction',
+ 'uninstallLogicFunction',
+ ]) {
+ const hook = manifest.application[key];
+ if (!isDefined(hook)) {
+ continue;
+ }
+ if (!isPlainObject(hook) || !isString(hook.universalIdentifier)) {
+ return;
+ }
+ hooks[key] = hook.universalIdentifier.toLowerCase();
+ }
+
+ return {
+ data: {
+ applicationUniversalIdentifier:
+ manifest.application.universalIdentifier.toLowerCase(),
+ universalIdentifiers,
+ hooks,
+ },
+ };
+ },
+ });
+ const diagnostics = [
+ ...result.diagnostics,
+ ...toWorkerOutputDiagnostics(worker.output),
+ ];
+
+ if (outputMode === 'human') {
+ for (const diagnostic of diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+ if (!result.success) {
+ throw createToolingFailure({
+ error: result.error,
+ diagnostics,
+ sdkVersion: sdk.version,
+ });
+ }
+
+ return { ...result.data, diagnostics };
+};
+
+export type ExecManifest = Awaited<ReturnType<typeof readExecManifest>>;
diff --git a/packages/twenty-cli/src/app/exec/read-function-selector.ts b/packages/twenty-cli/src/app/exec/read-function-selector.ts
new file mode 100644
index 00000000000..90331b7c114
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/read-function-selector.ts
@@ -0,0 +1,62 @@
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AppFunctionSelector } from '@/app/exec/types/app-function-selector.type';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const readFunctionSelector = (options: Record<string, unknown>) => {
+ const selectors: AppFunctionSelector[] = [];
+ const name = readStringOption(options, 'name');
+ const universalIdentifier = readStringOption(options, 'universalIdentifier');
+
+ if (isDefined(name)) {
+ selectors.push({ kind: 'name', value: name });
+ }
+ if (isDefined(universalIdentifier)) {
+ selectors.push({
+ kind: 'universalIdentifier',
+ value: universalIdentifier.toLowerCase(),
+ });
+ }
+ if (readBooleanOption(options, 'postInstall')) {
+ selectors.push({ kind: 'hook', value: 'postInstallLogicFunction' });
+ }
+ if (readBooleanOption(options, 'preInstall')) {
+ selectors.push({ kind: 'hook', value: 'preInstallLogicFunction' });
+ }
+ if (readBooleanOption(options, 'uninstallHook')) {
+ selectors.push({ kind: 'hook', value: 'uninstallLogicFunction' });
+ }
+
+ if (selectors.length !== 1) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ 'Choose exactly one of --name, --universal-identifier, --post-install, --pre-install or --uninstall-hook.',
+ });
+ }
+
+ const selector = selectors[0];
+ if (
+ selector.value.trim().length === 0 ||
+ (selector.kind === 'universalIdentifier' &&
+ !isValidUniversalIdentifier(selector.value))
+ ) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ selector.kind === 'name'
+ ? '--name cannot be empty.'
+ : '--universal-identifier must be a UUID of version 4 or later.',
+ });
+ }
+
+ return selector;
+};
diff --git a/packages/twenty-cli/src/app/exec/types/app-function-selector.type.ts b/packages/twenty-cli/src/app/exec/types/app-function-selector.type.ts
new file mode 100644
index 00000000000..0cb29dfbf0f
--- /dev/null
+++ b/packages/twenty-cli/src/app/exec/types/app-function-selector.type.ts
@@ -0,0 +1,9 @@
+export type AppFunctionSelector =
+ | { kind: 'name' | 'universalIdentifier'; value: string }
+ | {
+ kind: 'hook';
+ value:
+ | 'postInstallLogicFunction'
+ | 'preInstallLogicFunction'
+ | 'uninstallLogicFunction';
+ };
diff --git a/packages/twenty-cli/src/app/fetch-app-export.ts b/packages/twenty-cli/src/app/fetch-app-export.ts
new file mode 100644
index 00000000000..a4d17cf7a46
--- /dev/null
+++ b/packages/twenty-cli/src/app/fetch-app-export.ts
@@ -0,0 +1,121 @@
+import { isArray, isNull, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { createAppNotInstalledError } from '@/app/create-app-not-installed-error';
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { parseAppExport } from '@/app/parse-app-export';
+import { type AppExport } from '@/app/types/app-export.type';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+const NOT_EXPORTABLE_SUB_CODES = new Set([
+ 'APPLICATION_NOT_EXPORTABLE',
+ 'STANDARD_APPLICATION_NOT_EXPORTABLE',
+]);
+
+const isExportUnsupportedError = (error: unknown): error is CliError => {
+ if (!(error instanceof CliError) || error.code !== 'GRAPHQL_ERROR') {
+ return false;
+ }
+
+ const errors = error.details?.errors;
+
+ if (!isArray(errors) || errors.length !== 1) {
+ return false;
+ }
+
+ const entry: unknown = errors[0];
+
+ return (
+ isPlainObject(entry) &&
+ (entry.code === 'GRAPHQL_VALIDATION_FAILED' ||
+ (isNull(entry.code) && error.details?.status === 400)) &&
+ isNull(entry.path) &&
+ isString(entry.message) &&
+ entry.message.startsWith(
+ 'Cannot query field "exportApplication" on type "Query".',
+ )
+ );
+};
+
+const isNotExportableError = (error: unknown): error is CliError => {
+ if (!(error instanceof CliError) || error.code !== 'GRAPHQL_ERROR') {
+ return false;
+ }
+
+ const errors = error.details?.errors;
+
+ if (!isArray(errors) || errors.length !== 1) {
+ return false;
+ }
+
+ const entry: unknown = errors[0];
+
+ return (
+ isPlainObject(entry) &&
+ isString(entry.subCode) &&
+ NOT_EXPORTABLE_SUB_CODES.has(entry.subCode)
+ );
+};
+
+export const fetchAppExport = async ({
+ universalIdentifier,
+ target,
+ signal,
+}: {
+ universalIdentifier: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}): Promise<AppExport> => {
+ const data = await createMetadataClient({ target, signal })
+ .query({
+ __name: 'ExportApplication',
+ exportApplication: {
+ __args: { universalIdentifier },
+ application: {
+ universalIdentifier: true,
+ displayName: true,
+ sourceType: true,
+ },
+ manifest: true,
+ coverage: {
+ metadataName: true,
+ universalIdentifier: true,
+ status: true,
+ reason: true,
+ },
+ files: { folder: true, path: true, content: true },
+ },
+ })
+ .catch((error: unknown) => {
+ if (isApplicationNotFoundError({ error, field: 'exportApplication' })) {
+ throw createAppNotInstalledError({
+ universalIdentifier,
+ apiUrl: target.apiUrl,
+ });
+ }
+
+ if (isExportUnsupportedError(error)) {
+ throw new CliError({
+ code: 'APP_EXPORT_UNSUPPORTED',
+ message: 'This server does not support application export.',
+ });
+ }
+
+ if (isNotExportableError(error)) {
+ throw new CliError({
+ code: 'APP_NOT_EXPORTABLE',
+ message: error.message,
+ hint: 'Only apps developed locally can be pulled: not the standard app, and not apps installed from a package.',
+ details: { universalIdentifier },
+ });
+ }
+
+ throw error;
+ });
+ return parseAppExport({
+ value: data?.exportApplication,
+ universalIdentifier,
+ });
+};
diff --git a/packages/twenty-cli/src/app/fetch-installed-app.ts b/packages/twenty-cli/src/app/fetch-installed-app.ts
new file mode 100644
index 00000000000..aabec9be505
--- /dev/null
+++ b/packages/twenty-cli/src/app/fetch-installed-app.ts
@@ -0,0 +1,61 @@
+import { isBoolean, isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { createAppNotInstalledError } from '@/app/create-app-not-installed-error';
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchInstalledApp = async ({
+ universalIdentifier,
+ target,
+ signal,
+}: {
+ universalIdentifier: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const data = await createMetadataClient({ target, signal })
+ .query({
+ __name: 'FindInstalledApplication',
+ findOneApplication: {
+ __args: { universalIdentifier },
+ name: true,
+ universalIdentifier: true,
+ canBeUninstalled: true,
+ },
+ })
+ .catch((error: unknown) => {
+ if (isApplicationNotFoundError({ error, field: 'findOneApplication' })) {
+ throw createAppNotInstalledError({
+ universalIdentifier,
+ apiUrl: target.apiUrl,
+ });
+ }
+
+ throw error;
+ });
+ const application = data?.findOneApplication;
+
+ if (
+ !isPlainObject(application) ||
+ !isNonEmptyString(application.name) ||
+ !isSameUniversalIdentifier({
+ value: application.universalIdentifier,
+ universalIdentifier,
+ }) ||
+ !isBoolean(application.canBeUninstalled)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid installed application.',
+ });
+ }
+
+ return {
+ name: application.name,
+ canBeUninstalled: application.canBeUninstalled,
+ };
+};
diff --git a/packages/twenty-cli/src/app/fetch-workspace-id.ts b/packages/twenty-cli/src/app/fetch-workspace-id.ts
new file mode 100644
index 00000000000..35977933a1b
--- /dev/null
+++ b/packages/twenty-cli/src/app/fetch-workspace-id.ts
@@ -0,0 +1,33 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject, isValidUuid } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchWorkspaceId = async ({
+ target,
+ signal,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const client = createMetadataClient({ target, signal });
+ const data = await client.query({
+ currentWorkspace: { id: true },
+ });
+ const workspace = data?.currentWorkspace;
+
+ if (
+ !isPlainObject(workspace) ||
+ !isNonEmptyString(workspace.id) ||
+ !isValidUuid(workspace.id)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `${target.apiUrl} did not say which workspace these credentials belong to.`,
+ });
+ }
+
+ return workspace.id;
+};
diff --git a/packages/twenty-cli/src/app/format-app-duration.ts b/packages/twenty-cli/src/app/format-app-duration.ts
new file mode 100644
index 00000000000..f8ca9749ae5
--- /dev/null
+++ b/packages/twenty-cli/src/app/format-app-duration.ts
@@ -0,0 +1,2 @@
+export const formatAppDuration = (milliseconds: number) =>
+ `${(milliseconds / 1000).toFixed(1)} s`;
diff --git a/packages/twenty-cli/src/app/format-app-init-summary.ts b/packages/twenty-cli/src/app/format-app-init-summary.ts
new file mode 100644
index 00000000000..1d8f8c27102
--- /dev/null
+++ b/packages/twenty-cli/src/app/format-app-init-summary.ts
@@ -0,0 +1,34 @@
+import { type AppInitNextStep } from '@/app/types/app-init-next-step.type';
+import { formatList } from '@/output/format-list';
+import { dimText, formatSuccessLine } from '@/output/style';
+
+export const formatAppInitSummary = ({
+ appName,
+ location,
+ packageNames,
+ packageVersion,
+ nextSteps,
+}: {
+ appName: string;
+ location: string;
+ packageNames: string[];
+ packageVersion: string;
+ nextSteps: AppInitNextStep[];
+}) => {
+ const commandWidth = Math.max(
+ ...nextSteps.map(({ command }) => command.length),
+ );
+
+ return [
+ formatSuccessLine(`Created ${appName} in ${location}`),
+ dimText(
+ ` ${formatList(packageNames)} pinned to ${packageVersion}. Nothing was installed.`,
+ ),
+ '',
+ 'Next steps',
+ ...nextSteps.map(
+ ({ command, description }) =>
+ ` ${command.padEnd(commandWidth)} ${dimText(`# ${description}`)}`,
+ ),
+ ].join('\n');
+};
diff --git a/packages/twenty-cli/src/app/format-build-summary.ts b/packages/twenty-cli/src/app/format-build-summary.ts
new file mode 100644
index 00000000000..1918e9069ca
--- /dev/null
+++ b/packages/twenty-cli/src/app/format-build-summary.ts
@@ -0,0 +1,63 @@
+import { formatBytes } from 'twenty-shared/utils';
+
+import { formatAppDuration } from '@/app/format-app-duration';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+import { dimText, formatSuccessLine } from '@/output/style';
+
+const ROLE_LABELS: Record<string, [singular: string, plural: string]> = {
+ 'built-logic-function': ['logic function', 'logic functions'],
+ 'built-front-component': ['front component', 'front components'],
+ source: ['source file', 'source files'],
+ dependencies: ['dependency file', 'dependency files'],
+ 'public-asset': ['asset', 'assets'],
+};
+
+const ROLE_ORDER = Object.keys(ROLE_LABELS);
+
+const getRoleRank = (role: string) => {
+ const rank = ROLE_ORDER.indexOf(role);
+
+ return rank === -1 ? ROLE_ORDER.length : rank;
+};
+
+const formatRoleCounts = (build: ToolingBuild) => {
+ const roleCounts = new Map<string, number>();
+
+ for (const file of build.files) {
+ roleCounts.set(file.role, (roleCounts.get(file.role) ?? 0) + 1);
+ }
+
+ return [...roleCounts]
+ .sort(
+ ([firstRole], [secondRole]) =>
+ getRoleRank(firstRole) - getRoleRank(secondRole),
+ )
+ .map(([role, count]) => {
+ const labels = ROLE_LABELS[role] ?? [role, role];
+
+ return `${count} ${labels[count === 1 ? 0 : 1]}`;
+ })
+ .join(' · ');
+};
+
+export const formatBuildSummary = ({
+ build,
+ durationMilliseconds,
+}: {
+ build: ToolingBuild;
+ durationMilliseconds: number;
+}) => {
+ const totalSize = build.files.reduce((sum, file) => sum + file.size, 0);
+
+ return [
+ formatSuccessLine(
+ `Built ${build.application.displayName} with twenty ${CLI_VERSION} ${dimText(`in ${formatAppDuration(durationMilliseconds)}`)}`,
+ ),
+ dimText(
+ ` ${build.files.length} files · ${formatBytes(totalSize)} · content hash ${build.contentHash.slice(0, 12)}`,
+ ),
+ dimText(` ${formatRoleCounts(build)}`),
+ dimText(' Nothing was uploaded.'),
+ ].join('\n');
+};
diff --git a/packages/twenty-cli/src/app/format-tooling-diagnostic.ts b/packages/twenty-cli/src/app/format-tooling-diagnostic.ts
new file mode 100644
index 00000000000..423668964f6
--- /dev/null
+++ b/packages/twenty-cli/src/app/format-tooling-diagnostic.ts
@@ -0,0 +1,24 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ToolingDiagnostic } from '@/app/types/tooling-result.type';
+import { dimText, formatFailureLine, formatWarningLine } from '@/output/style';
+
+export const formatToolingDiagnostic = ({
+ severity,
+ code,
+ message,
+ file,
+ line,
+ column,
+}: ToolingDiagnostic) => {
+ const location = isDefined(file)
+ ? [file, line, column].filter(isDefined).join(':')
+ : undefined;
+ const text = [location, dimText(code, process.stderr), message]
+ .filter(isDefined)
+ .join(' ');
+
+ return severity === 'error'
+ ? formatFailureLine(text)
+ : formatWarningLine(text);
+};
diff --git a/packages/twenty-cli/src/app/fs-utils.ts b/packages/twenty-cli/src/app/fs-utils.ts
new file mode 100644
index 00000000000..29d3f855c6e
--- /dev/null
+++ b/packages/twenty-cli/src/app/fs-utils.ts
@@ -0,0 +1,72 @@
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ access,
+ cp,
+ lstat,
+ mkdir,
+ readdir,
+ readFile,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const pathExists = async (filePath: string): Promise<boolean> => {
+ try {
+ await access(filePath);
+ return true;
+ } catch (error) {
+ if (hasErrorCode(error, 'ENOENT')) {
+ return false;
+ }
+
+ throw error;
+ }
+};
+
+export const ensureDir = (directoryPath: string) =>
+ mkdir(directoryPath, { recursive: true });
+export const copy = (source: string, destination: string) =>
+ cp(source, destination, { recursive: true });
+export const remove = (filePath: string) =>
+ rm(filePath, { recursive: true, force: true });
+
+export const emptyDir = async (dirPath: string): Promise<void> => {
+ let entries: string[];
+
+ try {
+ if ((await lstat(dirPath)).isSymbolicLink()) {
+ throw new Error(`Cannot empty a symbolic link: ${dirPath}`);
+ }
+
+ entries = await readdir(dirPath);
+ } catch (error: unknown) {
+ if (hasErrorCode(error, 'ENOENT')) {
+ await mkdir(dirPath, { recursive: true });
+ return;
+ }
+ throw error;
+ }
+
+ await Promise.all(
+ entries.map((entry) =>
+ rm(join(dirPath, entry), { recursive: true, force: true }),
+ ),
+ );
+};
+
+export const pathExistsSync = (filePath: string): boolean =>
+ existsSync(filePath);
+
+export const writeJson = async (
+ filePath: string,
+ data: unknown,
+): Promise<void> => {
+ await writeFile(filePath, JSON.stringify(data, null, 2) + '\n');
+};
+
+export const readJson = async <TData = unknown>(
+ filePath: string,
+): Promise<TData> => JSON.parse(await readFile(filePath, 'utf-8')) as TData;
diff --git a/packages/twenty-cli/src/app/function-logs/README.md b/packages/twenty-cli/src/app/function-logs/README.md
new file mode 100644
index 00000000000..d4f4156efff
--- /dev/null
+++ b/packages/twenty-cli/src/app/function-logs/README.md
@@ -0,0 +1,44 @@
+# CLI app function logs
+
+The command subscribes to POST `/metadata`,
+`logicFunctionLogs(input: LogicFunctionLogsInput!)`, application universal
+identifier and optional exact function name or universal identifier. It receives
+future completed-execution output, not history or per-line execution progress.
+Names can repeat within one app; name selection is a filter matching all of them.
+
+## Contract
+
+- `app logs` uses the CLI app-identity worker. Only the app definition is needed;
+ no function bundles, full manifest build or generated client is required. Source
+ diagnostics use CLI output, and target credentials stay outside the worker.
+- The CLI target supplies OAuth or API-key credentials, environment proxy
+ routing and cancellation. Server authorization requires `WORKFLOWS`,
+ workspace scoping and per-payload application access checks. There is no
+ execution mutation, app registration or workspace audit-log query.
+- The selection requests nullable `name` and `universalIdentifier` fields. Server
+ schemas rejecting only these fields trigger one explicit, warned fallback to
+ `{ logs }`, before any record has been emitted. Unrelated validation,
+ authorization, network and execution errors are never retried. An explicit
+ filter provides that identity if the server cannot; unknown values stay null.
+- A pull-driven reader uses the GraphQL `next`/`complete` SSE protocol,
+ awaits output and reads the next
+ frame only when the consumer is ready. It handles comments, multiline data,
+ split UTF-8 and LF/CRLF/CR framing. Each frame is capped at 16 MiB; the session
+ has no total byte cap. Reader locks and HTTP requests are released on exit.
+- Setup has a 60-second deadline. After setup there is no whole-session timer;
+ the HTTP body's 60-second idle deadline detects missing heartbeats. Yoga sends
+ comments every 12 seconds in production. Undici suspends its body deadline
+ while the body is paused for backpressure and refreshes it on resume.
+- There is no automatic reconnect or replay. EOF without `complete`, broken
+ JSON or records, redirects, oversized frames and network failures stop the
+ command. Errors retain `recordCount`; network failures explain the gap.
+ Explicit server completion exits 0, Ctrl+C exits 130. Human text escapes
+ terminal control characters; NDJSON emits start, connection progress, records
+ and a final result/error. A compatibility fallback may establish two
+ connections and therefore emit two connection progress events.
+
+Tests cover the public command with a real local HTTP transport, duplicate-name
+filters, compatibility failures, proxy routing, per-frame bounds, output
+backpressure, idle heartbeats, stalled connections, completion and cancellation.
+These tests verify protocol behavior, not live workspace authorization or
+execution.
diff --git a/packages/twenty-cli/src/app/function-logs/read-logs-filter.ts b/packages/twenty-cli/src/app/function-logs/read-logs-filter.ts
new file mode 100644
index 00000000000..5dfcb83aa40
--- /dev/null
+++ b/packages/twenty-cli/src/app/function-logs/read-logs-filter.ts
@@ -0,0 +1,32 @@
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { readStringOption } from '@/catalog/read-command-values';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const readLogsFilter = (options: Record<string, unknown>) => {
+ const name = readStringOption(options, 'name');
+ const universalIdentifier = readStringOption(options, 'universalIdentifier');
+
+ if (
+ (isDefined(name) && isDefined(universalIdentifier)) ||
+ (isDefined(name) && name.trim().length === 0) ||
+ (isDefined(universalIdentifier) &&
+ !isValidUniversalIdentifier(universalIdentifier))
+ ) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ 'Use either a nonempty --name or a UUID of version 4 or later for --universal-identifier, or neither to watch every function in the app.',
+ });
+ }
+
+ return {
+ ...(isDefined(name) ? { name } : {}),
+ ...(isDefined(universalIdentifier)
+ ? { universalIdentifier: universalIdentifier.toLowerCase() }
+ : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/app/function-logs/subscribe-to-app-logs.ts b/packages/twenty-cli/src/app/function-logs/subscribe-to-app-logs.ts
new file mode 100644
index 00000000000..c268a3b89f4
--- /dev/null
+++ b/packages/twenty-cli/src/app/function-logs/subscribe-to-app-logs.ts
@@ -0,0 +1,105 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { subscribeGraphql } from '@/transport/graphql/subscribe-graphql';
+
+export type AppLogRecord = {
+ applicationUniversalIdentifier: string;
+ functionName: string | null;
+ functionUniversalIdentifier: string | null;
+ logs: string;
+};
+
+const isUnsupportedIdentityQuery = (error: unknown) => {
+ if (!(error instanceof CliError) || error.code !== 'GRAPHQL_ERROR') {
+ return false;
+ }
+ const errors = error.details?.errors;
+
+ return (
+ isArray(errors) &&
+ errors.length > 0 &&
+ errors.every(
+ (entry: unknown) =>
+ isPlainObject(entry) &&
+ (!isDefined(entry.code) ||
+ entry.code === 'GRAPHQL_VALIDATION_FAILED') &&
+ isString(entry.message) &&
+ /Cannot query field "(?:name|universalIdentifier)" on type "LogicFunctionLogs"/.test(
+ entry.message,
+ ),
+ )
+ );
+};
+
+export const subscribeToAppLogs = async ({
+ applicationUniversalIdentifier,
+ filter,
+ target,
+ signal,
+ onConnected,
+ onIdentityUnavailable,
+ onRecord,
+}: {
+ applicationUniversalIdentifier: string;
+ filter: { name?: string; universalIdentifier?: string };
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ onConnected: () => Promise<void>;
+ onIdentityUnavailable: () => Promise<void>;
+ onRecord: (record: AppLogRecord) => Promise<void>;
+}) => {
+ let receivedRecords = 0;
+ const subscribe = (includeIdentity: boolean) =>
+ subscribeGraphql({
+ target,
+ signal,
+ query: `subscription SubscribeToLogs($input: LogicFunctionLogsInput!) {
+ logicFunctionLogs(input: $input) {
+ logs
+ ${includeIdentity ? 'name universalIdentifier' : ''}
+ }
+ }`,
+ variables: { input: { applicationUniversalIdentifier, ...filter } },
+ onConnected,
+ onData: async (data) => {
+ const record = isPlainObject(data) ? data.logicFunctionLogs : undefined;
+ if (
+ !isPlainObject(record) ||
+ !isString(record.logs) ||
+ (isDefined(record.name) && !isString(record.name)) ||
+ (isDefined(record.universalIdentifier) &&
+ !isString(record.universalIdentifier))
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid application log record.',
+ });
+ }
+ receivedRecords += 1;
+ await onRecord({
+ applicationUniversalIdentifier,
+ functionName: record.name ?? filter.name ?? null,
+ functionUniversalIdentifier:
+ record.universalIdentifier ?? filter.universalIdentifier ?? null,
+ logs: record.logs,
+ });
+ },
+ });
+
+ try {
+ await subscribe(true);
+ } catch (error) {
+ if (
+ signal.aborted ||
+ receivedRecords > 0 ||
+ !isUnsupportedIdentityQuery(error)
+ ) {
+ throw error;
+ }
+ await onIdentityUnavailable();
+ await subscribe(false);
+ }
+};
diff --git a/packages/twenty-cli/src/app/generate-app-client.ts b/packages/twenty-cli/src/app/generate-app-client.ts
new file mode 100644
index 00000000000..b1baecad733
--- /dev/null
+++ b/packages/twenty-cli/src/app/generate-app-client.ts
@@ -0,0 +1,95 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { createToolingFailure } from '@/app/create-tooling-failure';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { parseNullData, parseToolingResult } from '@/app/parse-tooling-result';
+import { runAppWorker } from '@/app/run-app-worker';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import { type ProjectSdk } from '@/app/project/types/project-sdk.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { CliError } from '@/output/cli-error';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchAppClientSchema = async ({
+ applicationUniversalIdentifier,
+ context: { target, signal, output },
+}: {
+ applicationUniversalIdentifier: string;
+ context: TargetCommandContext;
+}) => {
+ output.progress('Fetching the application schema…');
+
+ const data = await createMetadataClient({ target, signal }).query({
+ __name: 'ApplicationCoreGraphqlSchema',
+ applicationCoreGraphqlSchema: {
+ __args: { applicationUniversalIdentifier },
+ },
+ });
+ const schema = data?.applicationCoreGraphqlSchema;
+
+ if (!isNonEmptyString(schema) || schema.trim().length === 0) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server did not return an application GraphQL schema.',
+ });
+ }
+
+ return schema;
+};
+
+export const generateAppClientFromSchema = async ({
+ appPath,
+ schema,
+ sdk,
+ context: { signal, output, outputMode },
+}: {
+ appPath: string;
+ schema: string;
+ sdk: ProjectSdk;
+ context: TargetCommandContext;
+}) => {
+ output.progress('Generating the typed API client…');
+
+ const workerRun = await runAppWorker({
+ request: { type: 'generateSourceClient', appPath, schema },
+ signal,
+ });
+ const result = parseToolingResult({
+ value: workerRun.result,
+ parseData: parseNullData,
+ });
+ const diagnostics = [
+ ...result.diagnostics,
+ ...toWorkerOutputDiagnostics(workerRun.output),
+ ];
+
+ if (outputMode === 'human') {
+ for (const diagnostic of diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+
+ if (!result.success) {
+ throw createToolingFailure({
+ error: result.error,
+ diagnostics,
+ sdkVersion: sdk.version,
+ operation: 'generateClient',
+ });
+ }
+
+ signal.throwIfAborted();
+
+ return diagnostics;
+};
+
+export const generateAppClient = async (options: {
+ appPath: string;
+ applicationUniversalIdentifier: string;
+ sdk: ProjectSdk;
+ context: TargetCommandContext;
+}) =>
+ generateAppClientFromSchema({
+ ...options,
+ schema: await fetchAppClientSchema(options),
+ });
diff --git a/packages/twenty-cli/src/app/get-app-init-next-steps.ts b/packages/twenty-cli/src/app/get-app-init-next-steps.ts
new file mode 100644
index 00000000000..5e902cca247
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-app-init-next-steps.ts
@@ -0,0 +1,56 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AppInitNextStep } from '@/app/types/app-init-next-step.type';
+
+const SHELL_SAFE_PATTERN = /^[\w./-]+$/;
+
+const quoteForShell = (value: string) => {
+ if (SHELL_SAFE_PATTERN.test(value)) return value;
+ if (process.platform === 'win32') return `'${value.replace(/'/g, "''")}'`;
+
+ return `'${value.replace(/'/g, `'\\''`)}'`;
+};
+
+export const getAppInitNextSteps = ({
+ displayPath,
+ isTargetConfigured,
+ remoteName,
+}: {
+ displayPath: string;
+ isTargetConfigured: boolean;
+ remoteName: string | undefined;
+}): AppInitNextStep[] => {
+ const remoteFlag = isDefined(remoteName)
+ ? ` --remote ${quoteForShell(remoteName)}`
+ : '';
+
+ return [
+ ...(displayPath === '.'
+ ? []
+ : [
+ {
+ command: `cd ${quoteForShell(displayPath.startsWith('-') ? `./${displayPath}` : displayPath)}`,
+ description: 'Enter the new app',
+ },
+ ]),
+ { command: 'yarn install', description: 'Install the pinned dependencies' },
+ ...(isTargetConfigured
+ ? []
+ : [
+ {
+ command: `twenty auth login --url <url> --name ${isDefined(remoteName) ? quoteForShell(remoteName) : '<name>'}`,
+ description: 'Connect a workspace',
+ },
+ ]),
+ {
+ command: `twenty app apply --create${remoteFlag}`,
+ description: 'Build the app and install it in your workspace',
+ },
+ ].map((step) => ({
+ ...step,
+ description:
+ process.platform === 'win32'
+ ? `${step.description} (PowerShell)`
+ : step.description,
+ }));
+};
diff --git a/packages/twenty-cli/src/app/get-app-template-directory.ts b/packages/twenty-cli/src/app/get-app-template-directory.ts
new file mode 100644
index 00000000000..9a9f6ab9653
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-app-template-directory.ts
@@ -0,0 +1,5 @@
+import { realpathSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+export const getAppTemplateDirectory = () =>
+ join(dirname(realpathSync(process.argv[1] ?? '')), 'app-template');
diff --git a/packages/twenty-cli/src/app/get-app-template-overlay-directory.ts b/packages/twenty-cli/src/app/get-app-template-overlay-directory.ts
new file mode 100644
index 00000000000..95f7237f563
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-app-template-overlay-directory.ts
@@ -0,0 +1,5 @@
+import { realpathSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+export const getAppTemplateOverlayDirectory = () =>
+ join(dirname(realpathSync(process.argv[1] ?? '')), 'app-template-overlay');
diff --git a/packages/twenty-cli/src/app/get-app-worker-launch.ts b/packages/twenty-cli/src/app/get-app-worker-launch.ts
new file mode 100644
index 00000000000..f8de9dae3cb
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-app-worker-launch.ts
@@ -0,0 +1,12 @@
+import { realpathSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+import { type AppWorkerLaunch } from '@/app/types/app-worker-launch.type';
+
+export const getAppWorkerLaunch = (): AppWorkerLaunch => ({
+ modulePath: join(
+ dirname(realpathSync(process.argv[1] ?? '')),
+ 'app-worker.cjs',
+ ),
+ execArgv: [],
+});
diff --git a/packages/twenty-cli/src/app/get-client-generation-skip-reason.ts b/packages/twenty-cli/src/app/get-client-generation-skip-reason.ts
new file mode 100644
index 00000000000..ac68820376c
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-client-generation-skip-reason.ts
@@ -0,0 +1,23 @@
+import { lstat } from 'node:fs/promises';
+import { join } from 'node:path';
+
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const getClientGenerationSkipReason = async ({
+ appPath,
+}: {
+ appPath: string;
+}) => {
+ const isClientPackageMissing = await lstat(
+ join(appPath, 'node_modules', 'twenty-client-sdk'),
+ ).then(
+ () => false,
+ (error: unknown) => hasErrorCode(error, 'ENOENT'),
+ );
+
+ if (isClientPackageMissing) {
+ return "twenty-client-sdk is not installed in the app's own node_modules.";
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-cli/src/app/get-tooling-error-context.ts b/packages/twenty-cli/src/app/get-tooling-error-context.ts
new file mode 100644
index 00000000000..02fd7adf744
--- /dev/null
+++ b/packages/twenty-cli/src/app/get-tooling-error-context.ts
@@ -0,0 +1,4 @@
+import { CliError } from '@/output/cli-error';
+
+export const getToolingErrorContext = (error: unknown) =>
+ error instanceof CliError ? { hint: error.hint, details: error.details } : {};
diff --git a/packages/twenty-cli/src/app/is-application-not-found-error.ts b/packages/twenty-cli/src/app/is-application-not-found-error.ts
new file mode 100644
index 00000000000..6ccea625cc2
--- /dev/null
+++ b/packages/twenty-cli/src/app/is-application-not-found-error.ts
@@ -0,0 +1,31 @@
+import { isArray, isNull } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+
+export const isApplicationNotFoundError = ({
+ error,
+ field,
+}: {
+ error: unknown;
+ field: string;
+}) => {
+ if (!(error instanceof CliError) || error.code !== 'GRAPHQL_ERROR') {
+ return false;
+ }
+
+ const errors = error.details?.errors;
+
+ if (!isArray(errors) || errors.length !== 1) {
+ return false;
+ }
+
+ const entry: unknown = errors[0];
+
+ return (
+ isPlainObject(entry) &&
+ entry.code === 'NOT_FOUND' &&
+ entry.subCode === 'APPLICATION_NOT_FOUND' &&
+ (isNull(entry.path) || (isArray(entry.path) && entry.path[0] === field))
+ );
+};
diff --git a/packages/twenty-cli/src/app/is-same-universal-identifier.ts b/packages/twenty-cli/src/app/is-same-universal-identifier.ts
new file mode 100644
index 00000000000..3487a781876
--- /dev/null
+++ b/packages/twenty-cli/src/app/is-same-universal-identifier.ts
@@ -0,0 +1,10 @@
+import { isString } from '@sniptt/guards';
+
+export const isSameUniversalIdentifier = ({
+ value,
+ universalIdentifier,
+}: {
+ value: unknown;
+ universalIdentifier: string;
+}) =>
+ isString(value) && value.toLowerCase() === universalIdentifier.toLowerCase();
diff --git a/packages/twenty-cli/src/app/is-valid-package-name.ts b/packages/twenty-cli/src/app/is-valid-package-name.ts
new file mode 100644
index 00000000000..2f3ca722e4c
--- /dev/null
+++ b/packages/twenty-cli/src/app/is-valid-package-name.ts
@@ -0,0 +1,9 @@
+const PACKAGE_NAME_PATTERN =
+ /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
+
+const PACKAGE_NAME_MAX_LENGTH = 214;
+
+export const isValidPackageName = (name: string) =>
+ name.length <= PACKAGE_NAME_MAX_LENGTH &&
+ !['node_modules', 'favicon.ico'].includes(name) &&
+ PACKAGE_NAME_PATTERN.test(name);
diff --git a/packages/twenty-cli/src/app/manifest/README.md b/packages/twenty-cli/src/app/manifest/README.md
new file mode 100644
index 00000000000..54b118e7b2e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/README.md
@@ -0,0 +1,74 @@
+# Manifest generation
+
+The manifest builder constructs and validates metadata and compiles translations
+for build, plan and apply. The worker evaluates definitions through
+[app/source](../source/README.md); bundling and final artifact checksums belong to
+[app/bundles](../bundles/README.md).
+
+See the [app tooling overview](../README.md) for package ownership.
+
+## Contract
+
+The builder discovers definitions and assets, derives default object fields and
+permission identifiers, infers logic-function input schemas, resolves lifecycle
+hooks, reads the README and validates entity relationships, identifiers, role
+permissions and conditional availability. Manifests are sorted and carry
+checksum placeholders that the bundler replaces with final artifact checksums.
+
+`package.json`'s `engines.twenty` sets
+`application.requiredServerVersionRange`, with surrounding whitespace trimmed;
+an absent or empty value becomes `null`. No CLI version is substituted. The
+builder reports package dependency warnings and validates empty lockfiles.
+
+Translation compilation reuses the locale catalog helpers shared with
+pull. It preserves the distinction between no locale directory (`undefined`)
+and an empty one (`{}`), context-dependent message IDs, authored-over-compiled
+precedence, orphan compiled translations, collision handling and skipped-file
+warnings. It reads catalogs without rewriting them.
+
+Select options without an `id` receive a deterministic ID from their label and
+field identifier. Keep an explicit `id` when changing an option's label or value,
+so existing view filters continue to reference the same option. Duplicate option
+IDs fail validation. Pulled options already carry their server IDs.
+
+## Implementation
+
+- Definition discovery, detection and evaluation reuse `app/source`, including
+ its source and ignore globs and validation-result shape check.
+- Source and public-asset discovery is sorted so warning, error and entity file
+ order is deterministic.
+- The loader result accepts a compile-time config type, with the same runtime
+ shape check. Config types describe the authoring values consumed by the builder.
+ Handler parameters use `never` and return `unknown`; front components expose
+ only the `name` consumed here. The builder never calls those callbacks.
+- The version helper requires an explicit app path; the process working directory
+ cannot choose another app's version.
+- Filesystem reads use Node and the CLI `pathExists` helper. The JSON reader
+ propagates parse errors.
+- The worker resolves the app's authoring SDK with the source compatibility check,
+ returns structured errors and warnings, checks cancellation between phases and
+ stops esbuild before exiting. It uses credential filtering,
+ bounded output capture and cancellation/termination behavior. It does not hold
+ a snapshot or write build state.
+
+## Verification
+
+From `packages/twenty-cli`, after building the repository SDK, shared and UI
+packages:
+
+```bash
+node ../../node_modules/vitest/vitest.mjs run --config vitest.config.ts --maxWorkers=1 src/app/manifest/__tests__/manifest-parity.spec.ts
+```
+
+The suite bundles the SDK implementation as a test-only reference. It
+compares manifests, entity file paths, errors and warnings for every repository
+fixture and a freshly initialized app. It also exercises the production CLI
+worker using a copy of the real SDK's authoring entry points without `./build`,
+`./cli` or their implementation files.
+
+The SDK reference's discovery is sorted to match the CLI's deterministic input
+order. Comparisons remove only JSON-omitted `undefined` properties, matching the
+worker IPC boundary; arrays and diagnostics are not reordered. The invalid-app
+fixture throws `Invalid UUID` in both implementations. Additional cases cover
+duplicate identifiers, empty lockfiles, translations, source output and credential filtering.
+Unit tests cover individual validation and translation rules.
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts
new file mode 100644
index 00000000000..ad4fbfb565b
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-parity.spec.ts
@@ -0,0 +1,373 @@
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build as bundle, stop } from 'esbuild';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { SORTED_GLOB_PLUGIN } from '@/app/__tests__/utils/sorted-glob-plugin';
+import { buildAndValidateManifest } from '@/app/manifest/build-and-validate-manifest';
+import { buildManifest } from '@/app/manifest/manifest-build';
+import { createAppProject } from '@/app/create-app-project';
+import { runAppWorker } from '@/app/run-app-worker';
+import { type compileApplicationTranslations } from '@/app/translations/compile-application-translations';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+vi.mock('@/app/get-app-template-directory', () => ({
+ getAppTemplateDirectory: () =>
+ join(REPOSITORY_ROOT, 'packages/create-twenty-app/src/constants/template'),
+}));
+vi.mock('@/app/get-app-template-overlay-directory', () => ({
+ getAppTemplateOverlayDirectory: () =>
+ join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template-overlay'),
+}));
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const FIXTURES_DIRECTORY = join(
+ REPOSITORY_ROOT,
+ 'packages/twenty-apps/fixtures',
+);
+const FIXTURES = [
+ 'minimal-app',
+ 'rich-app',
+ 'function-execute-app',
+ 'shared-dependencies-app',
+ 'invalid-app',
+];
+
+type SdkReference = {
+ buildManifest: typeof buildManifest;
+ buildAndValidateManifest: typeof buildAndValidateManifest;
+ compileApplicationTranslations: typeof compileApplicationTranslations;
+};
+
+const json = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
+
+describe('CLI manifest parity with the repository SDK', () => {
+ let root: string;
+ let sdk: SdkReference;
+
+ const copyFixture = async (name: string) => {
+ const appPath = await mkdtemp(join(root, `${name}-`));
+
+ await cp(join(FIXTURES_DIRECTORY, name), appPath, {
+ recursive: true,
+ filter: (source) =>
+ !source
+ .split('/')
+ .some((part) => ['node_modules', '.twenty', 'dist'].includes(part)),
+ });
+ await symlink(join(root, 'node_modules'), join(appPath, 'node_modules'));
+
+ return appPath;
+ };
+
+ const compareManifest = async (appPath: string) => {
+ const expected = await sdk
+ .buildAndValidateManifest(appPath)
+ .catch((error: unknown) => ({
+ thrown: error instanceof Error ? error.message : String(error),
+ }));
+
+ if ('thrown' in expected) {
+ await expect(buildAndValidateManifest(appPath)).rejects.toThrow(
+ expected.thrown,
+ );
+ const worker = await runAppWorker({
+ request: { type: 'buildManifest', appPath },
+ signal: new AbortController().signal,
+ });
+
+ expect(worker.result).toMatchObject({
+ success: false,
+ error: { code: 'MANIFEST_BUILD_FAILED', message: expected.thrown },
+ });
+
+ return { success: false as const, errors: [expected.thrown] };
+ }
+
+ const actual = await buildAndValidateManifest(appPath);
+
+ expect(json(actual)).toEqual(json(expected));
+ expect(json(await buildManifest(appPath))).toEqual(
+ json(await sdk.buildManifest(appPath)),
+ );
+
+ const warnings: string[] = [];
+ const translations = expected.success
+ ? await sdk.compileApplicationTranslations({
+ appPath,
+ onWarning: (message) => warnings.push(message),
+ })
+ : undefined;
+ const worker = await runAppWorker({
+ request: { type: 'buildManifest', appPath },
+ signal: new AbortController().signal,
+ });
+
+ expect(worker.isSnapshotHeld).toBe(false);
+ expect(worker.result).toEqual(
+ json(
+ expected.success
+ ? {
+ success: true,
+ data: {
+ manifest: { ...expected.manifest, translations },
+ filePaths: expected.filePaths,
+ },
+ diagnostics: [...expected.warnings, ...warnings].map(
+ (message) => ({
+ severity: 'warning',
+ code: 'BUILD_WARNING',
+ message,
+ }),
+ ),
+ }
+ : {
+ success: false,
+ error: {
+ code: 'MANIFEST_BUILD_FAILED',
+ message: expected.errors.join('\n'),
+ },
+ diagnostics: expected.errors.map((message) => ({
+ severity: 'error',
+ code: 'MANIFEST_BUILD_FAILED',
+ message,
+ })),
+ },
+ ),
+ );
+
+ return actual;
+ };
+
+ beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-manifest-parity-'));
+ const modules = join(root, 'node_modules');
+ const sdkPath = join(modules, 'twenty-sdk');
+ const sourceSdk = join(REPOSITORY_ROOT, 'packages/twenty-sdk');
+ const sdkRequire = createRequire(join(sourceSdk, 'package.json'));
+
+ await mkdir(join(modules, '@sniptt'), { recursive: true });
+
+ for (const name of [
+ 'react',
+ 'react-dom',
+ '@sniptt/guards',
+ 'uuid',
+ 'esbuild',
+ 'typescript',
+ 'tinyglobby',
+ 'twenty-shared',
+ 'twenty-client-sdk',
+ 'twenty-ui',
+ ]) {
+ await symlink(
+ name === 'uuid'
+ ? dirname(sdkRequire.resolve('uuid/package.json'))
+ : join(REPOSITORY_ROOT, 'node_modules', name),
+ join(modules, name),
+ );
+ }
+
+ const packageJson = JSON.parse(
+ await readFile(join(sourceSdk, 'package.json'), 'utf8'),
+ );
+ const exports: Record<string, unknown> = {};
+
+ for (const name of [
+ 'define',
+ 'front-component',
+ 'logic-function',
+ 'billing',
+ 'utils',
+ ]) {
+ await cp(join(sourceSdk, 'dist', name), join(sdkPath, 'dist', name), {
+ recursive: true,
+ });
+ exports[`./${name}`] = packageJson.exports[`./${name}`];
+ }
+
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: packageJson.name,
+ version: packageJson.version,
+ engines: packageJson.engines,
+ exports,
+ }),
+ );
+ expect(() =>
+ createRequire(join(root, 'package.json')).resolve('twenty-sdk/build'),
+ ).toThrow();
+
+ const oraclePath = join(root, 'sdk-reference.cjs');
+ const sdkSource = join(sourceSdk, 'src');
+
+ await bundle({
+ stdin: {
+ contents: `export { buildManifest } from './cli/utilities/build/manifest/manifest-build';
+export { buildAndValidateManifest } from './cli/utilities/build/manifest/build-and-validate-manifest';
+export { compileApplicationTranslations } from './cli/utilities/translations/compile-application-translations';`,
+ resolveDir: sdkSource,
+ },
+ outfile: oraclePath,
+ alias: { '@': sdkSource },
+ bundle: true,
+ packages: 'external',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node24',
+ plugins: [SORTED_GLOB_PLUGIN],
+ });
+ sdk = createRequire(import.meta.url)(oraclePath) as SdkReference;
+
+ await buildTestAppWorker(join(root, 'cli'));
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ }, 60000);
+
+ afterEach(() => vi.unstubAllEnvs());
+ afterAll(async () => {
+ await stop();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('covers every repository fixture', async () => {
+ expect(
+ (await readdir(FIXTURES_DIRECTORY, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort(),
+ ).toEqual([...FIXTURES].sort());
+ });
+
+ it.each(FIXTURES)(
+ 'matches the manifest, file paths, errors and warnings for %s',
+ async (name) => {
+ const result = await compareManifest(await copyFixture(name));
+
+ expect(result.success).toBe(name !== 'invalid-app');
+ },
+ 60000,
+ );
+
+ it('matches a freshly initialized app and its server requirement', async () => {
+ const appPath = join(root, 'fresh-app');
+
+ await createAppProject({
+ appDirectory: appPath,
+ appName: 'fresh-app',
+ appDisplayName: 'Fresh app',
+ appDescription: 'Parity fixture',
+ signal: new AbortController().signal,
+ });
+ await symlink(join(root, 'node_modules'), join(appPath, 'node_modules'));
+ const result = await compareManifest(appPath);
+ const packageJson = JSON.parse(
+ await readFile(join(appPath, 'package.json'), 'utf8'),
+ );
+
+ expect(result.success).toBe(true);
+ if (result.success)
+ expect(result.manifest.application.requiredServerVersionRange).toBe(
+ packageJson.engines.twenty,
+ );
+ }, 60000);
+
+ it('matches authored and compiled translations and malformed catalog warnings', async () => {
+ const appPath = await copyFixture('minimal-app');
+
+ await mkdir(join(appPath, 'locales/compiled'), { recursive: true });
+ await writeFile(
+ join(appPath, 'locales/fr-FR.json'),
+ JSON.stringify({
+ Company: 'Entreprise',
+ door: { Open: 'Ouvrir' },
+ Empty: '',
+ }),
+ );
+ await writeFile(
+ join(appPath, 'locales/compiled/fr-FR.json'),
+ JSON.stringify({ orphan: 'Conservé' }),
+ );
+ await writeFile(join(appPath, 'locales/de-DE.json'), '{');
+ await writeFile(join(appPath, 'locales/klingon.json'), '{}');
+ await compareManifest(appPath);
+ }, 60000);
+
+ it('matches duplicate identifier diagnostics and empty lockfile failures', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const duplicate = join(appPath, 'duplicate.role.ts');
+
+ await cp(join(appPath, 'my.role.ts'), duplicate);
+ const duplicateResult = await compareManifest(appPath);
+
+ expect(duplicateResult.success).toBe(false);
+ if (!duplicateResult.success)
+ expect(duplicateResult.errors.join('\n')).toContain(
+ 'Duplicate universal identifiers',
+ );
+
+ await rm(duplicate);
+ await writeFile(join(appPath, 'yarn.lock'), '');
+ const lockResult = await compareManifest(appPath);
+
+ expect(lockResult).toEqual({
+ success: false,
+ errors: [
+ 'yarn.lock is empty. Run "yarn install" to regenerate it before building.',
+ ],
+ });
+ }, 60000);
+
+ it('keeps evaluated source output and workspace credentials outside the manifest result', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const applicationFiles = (await buildManifest(appPath)).filePaths
+ .application;
+ const filePath = join(appPath, applicationFiles[0]);
+
+ await writeFile(
+ filePath,
+ `console.log('manifest source output');
+if (process.env.TWENTY_API_KEY) throw new Error('workspace credential leaked');
+${await readFile(filePath, 'utf8')}`,
+ );
+ vi.stubEnv('TWENTY_API_KEY', 'must-not-reach-app');
+ const worker = await runAppWorker({
+ request: { type: 'buildManifest', appPath },
+ signal: new AbortController().signal,
+ });
+
+ expect(worker.result).toMatchObject({ success: true });
+ expect(JSON.stringify(worker.output)).toContain('manifest source output');
+ expect(JSON.stringify(worker.result)).not.toContain(
+ 'manifest source output',
+ );
+ }, 60000);
+});
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
new file mode 100644
index 00000000000..892a87da755
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
@@ -0,0 +1,1270 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getFieldUniversalIdentifier,
+ type ApplicationManifest,
+ type FieldManifest,
+ type Manifest,
+ type PageLayoutTabManifest,
+ type PageLayoutWidgetManifest,
+} from 'twenty-shared/application';
+import {
+ AggregateOperations,
+ FieldMetadataType,
+ PageLayoutTabLayoutMode,
+ PageLayoutType,
+ WidgetType,
+ PageLayoutWidgetVerticalListHeightBehavior,
+ RelationType,
+} from 'twenty-shared/types';
+import { addMissingFieldOptionIds } from '@/app/manifest/utils/add-missing-field-option-ids';
+import { manifestValidate } from '@/app/manifest/manifest-validate';
+
+const validApplication: ApplicationManifest = {
+ universalIdentifier: '8e8ee827-5a0b-46b0-bb63-c13ccd734ac6',
+ displayName: 'Test App',
+ description: 'Test app for Twenty',
+ defaultRoleUniversalIdentifier: '68bb56f3-8300-4cb5-8cc3-8da9ee66f1b2',
+ packageJsonChecksum: '98592af7-4be9-4655-b5c4-9bef307a996c',
+ yarnLockChecksum: '580ee05f-15fe-4146-bac2-6c382483c94e',
+};
+
+const validField: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440001',
+ type: FieldMetadataType.NUMBER,
+ name: 'healthScore',
+ label: 'Health Score',
+};
+
+const validManifest: Manifest = {
+ commandMenuItems: [],
+ timelineActivityTypes: [],
+ settingsMenuItems: [],
+ application: validApplication,
+ objects: [],
+ frontComponents: [],
+ fields: [],
+ logicFunctions: [],
+ permissionFlags: [],
+ roles: [],
+ skills: [],
+ agents: [],
+ publicAssets: [],
+ views: [],
+ viewFields: [],
+ navigationMenuItems: [],
+ pageLayouts: [],
+ pageLayoutTabs: [],
+ pageLayoutWidgets: [],
+};
+
+describe('manifestValidate', () => {
+ it('rejects options with colliding generated IDs before deployment', () => {
+ const field = addMissingFieldOptionIds({
+ universalIdentifier: validField.universalIdentifier,
+ objectUniversalIdentifier: validField.objectUniversalIdentifier,
+ name: 'status',
+ label: 'Status',
+ type: FieldMetadataType.SELECT,
+ options: [
+ { label: 'Same', value: 'FIRST', color: 'blue', position: 1 },
+ { label: 'Same', value: 'SECOND', color: 'blue', position: 2 },
+ ],
+ });
+ const result = manifestValidate({ ...validManifest, fields: [field] });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors.join(' ')).toContain('distinct explicit IDs');
+ });
+
+ it.each([
+ FieldMetadataType.SELECT,
+ FieldMetadataType.MULTI_SELECT,
+ FieldMetadataType.RATING,
+ ] as const)('rejects colliding and empty IDs in %s options', (type) => {
+ const options = [
+ {
+ id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ label: 'First',
+ value: 'FIRST',
+ color: 'blue' as const,
+ position: 1,
+ },
+ {
+ id: 'AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA',
+ label: 'Second',
+ value: 'SECOND',
+ color: 'blue' as const,
+ position: 2,
+ },
+ ];
+ const field = {
+ universalIdentifier: validField.universalIdentifier,
+ objectUniversalIdentifier: validField.objectUniversalIdentifier,
+ name: 'status',
+ label: 'Status',
+ type,
+ options,
+ } as FieldManifest<
+ | FieldMetadataType.SELECT
+ | FieldMetadataType.MULTI_SELECT
+ | FieldMetadataType.RATING
+ >;
+ expect(
+ manifestValidate({ ...validManifest, fields: [field] }).errors.join(' '),
+ ).toContain('duplicate option IDs');
+ const emptyIds = manifestValidate({
+ ...validManifest,
+ fields: [
+ { ...field, options: options.map((option) => ({ ...option, id: '' })) },
+ ],
+ });
+ expect(emptyIds.errors.join(' ')).toContain('empty option IDs');
+ expect(emptyIds.errors.join(' ')).toContain('duplicate option IDs');
+ expect(
+ manifestValidate({
+ ...validManifest,
+ fields: [{ ...field, options: [options[0]] }],
+ }).isValid,
+ ).toBe(true);
+ });
+
+ it('reports unresolved label references without rejecting server-owned fields', () => {
+ const object = {
+ universalIdentifier: validField.objectUniversalIdentifier,
+ nameSingular: 'company',
+ namePlural: 'companies',
+ labelSingular: 'Company',
+ labelPlural: 'Companies',
+ fields: [],
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ validField.universalIdentifier,
+ };
+ const manifest = { ...validManifest, objects: [object] };
+ expect(manifestValidate(manifest).warnings.join(' ')).toContain(
+ 'Check the identifier',
+ );
+ expect(
+ manifestValidate({ ...manifest, fields: [validField] }).warnings,
+ ).toEqual([]);
+ for (const name of ['id', 'searchVector']) {
+ expect(
+ manifestValidate({
+ ...manifest,
+ objects: [
+ {
+ ...object,
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ getFieldUniversalIdentifier({
+ applicationUniversalIdentifier:
+ validApplication.universalIdentifier,
+ objectUniversalIdentifier: object.universalIdentifier,
+ name,
+ }),
+ },
+ ],
+ }).warnings,
+ ).toEqual([]);
+ }
+ });
+
+ describe('valid object extensions', () => {
+ it('should pass validation with valid object extension by nameSingular', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validField],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should pass validation with valid object extension by universalIdentifier', () => {
+ const extensionByUuid: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440002',
+ type: FieldMetadataType.TEXT,
+ name: 'customNote',
+ label: 'Custom Note',
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [extensionByUuid],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should pass validation with multiple object extensions', () => {
+ const anotherExtension: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440003',
+ type: FieldMetadataType.TEXT,
+ name: 'nickname',
+ label: 'Nickname',
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validField, anotherExtension],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should pass validation with SELECT field having options', () => {
+ const extensionWithSelect: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440004',
+ type: FieldMetadataType.SELECT,
+ name: 'status',
+ label: 'Status',
+ options: [
+ { value: 'active', label: 'Active', color: 'green', position: 0 },
+ {
+ value: 'inactive',
+ label: 'Inactive',
+ color: 'red',
+ position: 1,
+ },
+ ],
+ };
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [extensionWithSelect],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+ });
+
+ describe('duplicate universalIdentifier detection', () => {
+ it('rejects differently cased copies of the same UUID', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [
+ validField,
+ {
+ ...validField,
+ name: 'otherScore',
+ universalIdentifier: validField.universalIdentifier.toUpperCase(),
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors.join(' ')).toContain(
+ 'Duplicate universal identifiers',
+ );
+ });
+
+ it('should fail when extension field has duplicate universalIdentifier', () => {
+ const duplicateId = '550e8400-e29b-41d4-a716-446655440001';
+
+ const fieldsWithDuplicates: FieldManifest[] = [
+ {
+ objectUniversalIdentifier: '91c5848c-36dc-4e7e-b9ee-aa78caeff5a8',
+ universalIdentifier: duplicateId,
+ type: FieldMetadataType.NUMBER,
+ name: 'field1',
+ label: 'Field 1',
+ },
+ {
+ objectUniversalIdentifier: '97931020-123c-435b-ad97-9e19a5b38f1f',
+ universalIdentifier: duplicateId,
+ type: FieldMetadataType.TEXT,
+ name: 'field2',
+ label: 'Field 2',
+ },
+ ];
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: fieldsWithDuplicates,
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain(
+ 'Duplicate universal identifiers: 550e8400-e29b-41d4-a716-446655440001',
+ );
+ });
+
+ it('should fail when extension field ID conflicts with object field ID', () => {
+ const sharedId = '550e8400-e29b-41d4-a716-446655440001';
+
+ const result = manifestValidate({
+ ...validManifest,
+ objects: [
+ {
+ universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
+ nameSingular: 'myObject',
+ namePlural: 'myObjects',
+ labelSingular: 'My Object',
+ labelPlural: 'My Objects',
+ labelIdentifierFieldMetadataUniversalIdentifier: sharedId,
+ fields: [
+ {
+ universalIdentifier: sharedId,
+ type: FieldMetadataType.TEXT,
+ name: 'existingField',
+ label: 'Existing Field',
+ },
+ ],
+ },
+ ],
+ fields: [
+ {
+ objectUniversalIdentifier: '91c5848c-36dc-4e7e-b9ee-aa78caeff5a8',
+ universalIdentifier: sharedId,
+ type: FieldMetadataType.NUMBER,
+ name: 'extensionField',
+ label: 'Extension Field',
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain(
+ 'Duplicate universal identifiers: 550e8400-e29b-41d4-a716-446655440001',
+ );
+ });
+
+ it.each(['onConnectLogicFunction', 'onDisconnectLogicFunction'] as const)(
+ 'should not flag a connection provider referencing a logic function via %s as a duplicate',
+ (lifecycleHookKey) => {
+ const logicFunctionId = '550e8400-e29b-41d4-a716-446655440040';
+
+ const logicFunction = {
+ universalIdentifier: logicFunctionId,
+ name: lifecycleHookKey,
+ sourceHandlerPath: 'src/logic-functions/lifecycle-hook.ts',
+ builtHandlerPath: 'dist/lifecycle-hook.js',
+ builtHandlerChecksum: '00000000-0000-4000-8000-000000000000',
+ handlerName: 'handler',
+ } as unknown as Manifest['logicFunctions'][number];
+
+ const connectionProvider = {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440041',
+ name: 'slack',
+ displayName: 'Slack',
+ type: 'oauth',
+ oauth: {},
+ [lifecycleHookKey]: { universalIdentifier: logicFunctionId },
+ } as unknown as NonNullable<Manifest['connectionProviders']>[number];
+
+ const result = manifestValidate({
+ ...validManifest,
+ logicFunctions: [logicFunction],
+ connectionProviders: [connectionProvider],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ },
+ );
+
+ it('should not flag a front component referenced via settingsFrontComponent as a duplicate', () => {
+ const frontComponentId = '550e8400-e29b-41d4-a716-446655440050';
+
+ const frontComponent = {
+ universalIdentifier: frontComponentId,
+ name: 'app-settings',
+ componentName: 'AppSettings',
+ sourceComponentPath: 'src/front-components/app-settings.tsx',
+ builtComponentPath: 'dist/app-settings.mjs',
+ builtComponentChecksum: '00000000-0000-4000-8000-000000000000',
+ isHeadless: false,
+ } as unknown as Manifest['frontComponents'][number];
+
+ const result = manifestValidate({
+ ...validManifest,
+ application: {
+ ...validApplication,
+ settingsFrontComponent: { universalIdentifier: frontComponentId },
+ },
+ frontComponents: [frontComponent],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+ });
+
+ describe('relation field validation', () => {
+ it('should fail when a RELATION field in fields is missing relationType', () => {
+ const relationFieldWithoutSettings = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440010',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ label: 'Company',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440011',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ } as unknown as FieldManifest;
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [relationFieldWithoutSettings],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors[0]).toContain('company');
+ expect(result.errors[0]).toContain('missing relationType');
+ });
+
+ it('should fail when a RELATION field in object fields is missing relationType', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ objects: [
+ {
+ universalIdentifier: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
+ nameSingular: 'recipient',
+ namePlural: 'recipients',
+ labelSingular: 'Recipient',
+ labelPlural: 'Recipients',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ '7c9e6679-7425-40de-944b-e07fc1f90ae7',
+ fields: [
+ {
+ universalIdentifier: '7c9e6679-7425-40de-944b-e07fc1f90ae7',
+ type: FieldMetadataType.TEXT,
+ name: 'name',
+ label: 'Name',
+ },
+ {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440012',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ label: 'Company',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440013',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ } as unknown as FieldManifest,
+ ],
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors[0]).toContain('company');
+ expect(result.errors[0]).toContain('missing relationType');
+ });
+
+ it('should pass when a RELATION field has valid universalSettings with relationType', () => {
+ const validRelationField = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440014',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ label: 'Company',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440015',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ universalSettings: {
+ relationType: RelationType.MANY_TO_ONE,
+ joinColumnName: 'companyId',
+ },
+ } as unknown as FieldManifest;
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validRelationField],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should fail when a MANY_TO_ONE field is missing joinColumnName', () => {
+ const manyToOneWithoutJoinColumn = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440018',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ label: 'Company',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440019',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ universalSettings: {
+ relationType: RelationType.MANY_TO_ONE,
+ },
+ } as unknown as FieldManifest;
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [manyToOneWithoutJoinColumn],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.isValid).toBe(false);
+ expect(result.errors[0]).toContain('company');
+ expect(result.errors[0]).toContain('missing joinColumnName');
+ });
+
+ it('should pass when a ONE_TO_MANY field has no joinColumnName', () => {
+ const oneToManyField = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440020',
+ type: FieldMetadataType.RELATION,
+ name: 'contacts',
+ label: 'Contacts',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440021',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ universalSettings: {
+ relationType: RelationType.ONE_TO_MANY,
+ },
+ } as unknown as FieldManifest;
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [oneToManyField],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should fail when a RELATION field has an invalid relationType', () => {
+ const relationFieldWithBadType = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440016',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ label: 'Company',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440017',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '20202020-b374-4779-a561-80086cb2e17f',
+ universalSettings: {
+ relationType: 'INVALID_TYPE',
+ },
+ } as unknown as FieldManifest;
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [relationFieldWithBadType],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors[0]).toContain('company');
+ expect(result.errors[0]).toContain('invalid relationType');
+ });
+ });
+
+ describe('UUID version validation', () => {
+ it('should pass with UUID v4 identifiers', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [validField],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should pass with UUID v5 identifiers', () => {
+ const v5Field: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: '21f7f8de-8051-5b89-8680-0195ef798b6a',
+ type: FieldMetadataType.TEXT,
+ name: 'v5Field',
+ label: 'V5 Field',
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [v5Field],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should fail with UUID v1 identifiers', () => {
+ const v1Uuid = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+ const v1Field: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: v1Uuid,
+ type: FieldMetadataType.TEXT,
+ name: 'v1Field',
+ label: 'V1 Field',
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [v1Field],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContainEqual(
+ expect.stringContaining(`"${v1Uuid}" is UUID version 1`),
+ );
+ expect(result.errors).toContainEqual(
+ expect.stringContaining('Only UUID version 4 or higher is allowed'),
+ );
+ });
+
+ it('should fail with UUID v3 identifiers', () => {
+ const v3Uuid = 'a3bb189e-8bf9-3888-9912-ace4e6543002';
+ const v3Field: FieldManifest = {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: v3Uuid,
+ type: FieldMetadataType.TEXT,
+ name: 'v3Field',
+ label: 'V3 Field',
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [v3Field],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContainEqual(
+ expect.stringContaining(`"${v3Uuid}" is UUID version 3`),
+ );
+ });
+
+ it('should fail with non-UUID universal identifiers', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ objects: [
+ {
+ universalIdentifier: 'not-a-uuid',
+ nameSingular: 'myObject',
+ namePlural: 'myObjects',
+ labelSingular: 'My Object',
+ labelPlural: 'My Objects',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ '550e8400-e29b-41d4-a716-446655440030',
+ fields: [
+ {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440030',
+ type: FieldMetadataType.TEXT,
+ name: 'name',
+ label: 'Name',
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContainEqual(
+ expect.stringContaining('"not-a-uuid" is not a valid UUID'),
+ );
+ });
+
+ it('should not report duplicate version errors for the same identifier', () => {
+ const v1Uuid = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+
+ const result = manifestValidate({
+ ...validManifest,
+ fields: [
+ {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: v1Uuid,
+ type: FieldMetadataType.TEXT,
+ name: 'field1',
+ label: 'Field 1',
+ },
+ {
+ objectUniversalIdentifier: '20202020-b374-4779-a561-80086cb2e17f',
+ universalIdentifier: v1Uuid,
+ type: FieldMetadataType.TEXT,
+ name: 'field2',
+ label: 'Field 2',
+ },
+ ],
+ });
+
+ const versionErrors = result.errors.filter((e) =>
+ e.includes('is UUID version 1'),
+ );
+
+ expect(versionErrors).toHaveLength(1);
+ });
+ });
+
+ describe('graph widget validation', () => {
+ const makeGraphWidgetTab = (
+ configuration: PageLayoutWidgetManifest['configuration'],
+ ): PageLayoutTabManifest => ({
+ universalIdentifier: 'b0a5f0f2-6c2e-4d1c-9d0b-2f8a4c3e1a01',
+ title: 'Dashboard',
+ position: 0,
+ widgets: [
+ {
+ universalIdentifier: 'b0a5f0f2-6c2e-4d1c-9d0b-2f8a4c3e1a02',
+ title: 'Total opportunities',
+ type: WidgetType.GRAPH,
+ configuration,
+ },
+ ],
+ });
+
+ it('should pass when a graph widget has aggregateFieldMetadataUniversalIdentifier', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [
+ makeGraphWidgetTab({
+ configurationType: 'AGGREGATE_CHART',
+ aggregateFieldMetadataUniversalIdentifier:
+ 'b0a5f0f2-6c2e-4d1c-9d0b-2f8a4c3e1a03',
+ aggregateOperation: AggregateOperations.COUNT,
+ }),
+ ],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should error when a graph widget is missing the aggregate field identifier', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [
+ makeGraphWidgetTab({
+ configurationType: 'AGGREGATE_CHART',
+ aggregateFieldMetadataUniversalIdentifier: null,
+ aggregateOperation: AggregateOperations.COUNT,
+ }),
+ ],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContainEqual(
+ expect.stringContaining(
+ 'is missing aggregateFieldMetadataUniversalIdentifier',
+ ),
+ );
+ });
+
+ it('should hint at the correct key when the raw aggregateFieldMetadataId was used', () => {
+ const configurationWithRawKey = {
+ configurationType: 'AGGREGATE_CHART',
+ aggregateFieldMetadataId: 'b0a5f0f2-6c2e-4d1c-9d0b-2f8a4c3e1a03',
+ aggregateOperation: AggregateOperations.COUNT,
+ } as unknown as PageLayoutWidgetManifest['configuration'];
+
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [makeGraphWidgetTab(configurationWithRawKey)],
+ });
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContainEqual(
+ expect.stringContaining('not "aggregateFieldMetadataId"'),
+ );
+ });
+
+ it('should ignore non-graph widgets that have no aggregate field', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [makeGraphWidgetTab({ configurationType: 'TIMELINE' })],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should not crash on a widget with a missing configuration', () => {
+ const nullConfiguration =
+ null as unknown as PageLayoutWidgetManifest['configuration'];
+
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [makeGraphWidgetTab(nullConfiguration)],
+ });
+
+ expect(result.isValid).toBe(true);
+ });
+ });
+
+ describe('page layout deprecation warnings', () => {
+ it.each(['nested', 'standalone'])(
+ 'warns without changing a legacy %s manifest',
+ (location) => {
+ const legacyTab: PageLayoutTabManifest = {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000012',
+ title: 'Legacy canvas',
+ position: 0,
+ layoutMode: PageLayoutTabLayoutMode.CANVAS,
+ widgets: [],
+ };
+ const manifest: Manifest = {
+ ...validManifest,
+ pageLayouts:
+ location === 'nested'
+ ? [
+ {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000010',
+ name: 'Record page',
+ type: PageLayoutType.RECORD_PAGE,
+ tabs: [legacyTab],
+ },
+ ]
+ : [],
+ pageLayoutTabs: location === 'standalone' ? [legacyTab] : [],
+ };
+ const original = JSON.stringify(manifest);
+ const result = manifestValidate(manifest);
+
+ expect(result.isValid).toBe(true);
+ expect(result.warnings).toEqual([
+ expect.stringContaining('uses deprecated CANVAS'),
+ ]);
+ expect(result.warnings[0]).toContain(
+ "heightBehavior to 'TAB_VIEWPORT'",
+ );
+ expect(JSON.stringify(manifest)).toBe(original);
+ },
+ );
+
+ it.each(['position', 'gridPosition'])(
+ 'warns about legacy %s with a replacement',
+ (positionKey) => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayoutTabs: [
+ {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000012',
+ title: 'Details',
+ position: 0,
+ layoutMode:
+ positionKey === 'position'
+ ? PageLayoutTabLayoutMode.VERTICAL_LIST
+ : PageLayoutTabLayoutMode.GRID,
+ widgets: [
+ {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000013',
+ title: 'Timeline',
+ type: WidgetType.TIMELINE,
+ configuration: { configurationType: 'TIMELINE' },
+ [positionKey]:
+ positionKey === 'position'
+ ? {
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ index: 99,
+ }
+ : { row: 2, column: 3, rowSpan: 4, columnSpan: 5 },
+ },
+ ],
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.warnings).toHaveLength(1);
+ expect(result.warnings[0]).toContain(
+ positionKey === 'position'
+ ? 'Order the widgets array by position.index'
+ : "Use position with layoutMode: 'GRID'",
+ );
+ },
+ );
+ });
+
+ describe('page layout widget height behavior validation', () => {
+ const makePageLayout = (
+ layoutMode: PageLayoutTabLayoutMode,
+ ): Manifest['pageLayouts'][number] => ({
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000010',
+ name: 'Record page',
+ type: PageLayoutType.RECORD_PAGE,
+ objectUniversalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000011',
+ tabs: [
+ {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000012',
+ title: 'Details',
+ position: 0,
+ layoutMode,
+ widgets: [
+ {
+ universalIdentifier: 'a0a1a2a3-a4a5-4000-8000-000000000013',
+ title: 'App',
+ type: WidgetType.FRONT_COMPONENT,
+ heightBehavior:
+ PageLayoutWidgetVerticalListHeightBehavior.TAB_VIEWPORT,
+ configuration: {
+ configurationType: 'FRONT_COMPONENT',
+ frontComponentUniversalIdentifier:
+ 'a0a1a2a3-a4a5-4000-8000-000000000014',
+ },
+ },
+ ],
+ },
+ ],
+ });
+
+ it('should accept heightBehavior on a VERTICAL_LIST tab', () => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayouts: [makePageLayout(PageLayoutTabLayoutMode.VERTICAL_LIST)],
+ });
+
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it.each(['nested', 'standalone'])(
+ 'rejects invalid heightBehavior in a %s tab',
+ (location) => {
+ const pageLayout = makePageLayout(
+ PageLayoutTabLayoutMode.VERTICAL_LIST,
+ );
+ const pageLayoutTab = {
+ ...pageLayout.tabs![0],
+ widgets: pageLayout.tabs![0].widgets!.map((widget) => ({
+ ...widget,
+ heightBehavior: 'TAB_VIEPORT',
+ })),
+ };
+ const manifest: Manifest = JSON.parse(
+ JSON.stringify({
+ ...validManifest,
+ pageLayouts: [
+ {
+ ...pageLayout,
+ tabs: location === 'nested' ? [pageLayoutTab] : [],
+ },
+ ],
+ pageLayoutTabs:
+ location === 'standalone'
+ ? [
+ {
+ ...pageLayoutTab,
+ pageLayoutUniversalIdentifier:
+ pageLayout.universalIdentifier,
+ },
+ ]
+ : [],
+ }),
+ );
+
+ const result = manifestValidate(manifest);
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain(
+ 'Page layout widget "App" defines unsupported heightBehavior "TAB_VIEPORT". Expected FIT_CONTENT or TAB_VIEWPORT.',
+ );
+ },
+ );
+
+ it.each([PageLayoutTabLayoutMode.GRID, PageLayoutTabLayoutMode.CANVAS])(
+ 'should reject heightBehavior on a %s tab',
+ (layoutMode) => {
+ const result = manifestValidate({
+ ...validManifest,
+ pageLayouts: [makePageLayout(layoutMode)],
+ });
+
+ expect(result.errors).toContain(
+ `Page layout widget "App" defines heightBehavior, but its parent tab "Details" uses ${layoutMode}. heightBehavior is only supported for VERTICAL_LIST tabs.`,
+ );
+ },
+ );
+ });
+
+ describe('timeline activity type validation', () => {
+ const sourceObjectUniversalIdentifier =
+ '1a111111-1111-4111-8111-111111111111';
+ const relationFieldUniversalIdentifier =
+ '2a222222-2222-4222-8222-222222222222';
+ const triggerFieldUniversalIdentifier =
+ '3a333333-3333-4333-8333-333333333333';
+ const frontComponentUniversalIdentifier =
+ '4a444444-4444-4444-8444-444444444444';
+
+ const buildTimelineManifest = (): Manifest => ({
+ ...validManifest,
+ objects: [
+ {
+ universalIdentifier: sourceObjectUniversalIdentifier,
+ nameSingular: 'deployment',
+ namePlural: 'deployments',
+ labelSingular: 'Deployment',
+ labelPlural: 'Deployments',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ triggerFieldUniversalIdentifier,
+ fields: [],
+ },
+ ],
+ fields: [
+ {
+ universalIdentifier: relationFieldUniversalIdentifier,
+ objectUniversalIdentifier: sourceObjectUniversalIdentifier,
+ type: FieldMetadataType.RELATION,
+ name: 'owner',
+ label: 'Owner',
+ relationTargetFieldMetadataUniversalIdentifier:
+ '5a555555-5555-4555-8555-555555555555',
+ relationTargetObjectMetadataUniversalIdentifier:
+ '6a666666-6666-4666-8666-666666666666',
+ universalSettings: {
+ relationType: RelationType.MANY_TO_ONE,
+ joinColumnName: 'ownerId',
+ },
+ },
+ {
+ universalIdentifier: triggerFieldUniversalIdentifier,
+ objectUniversalIdentifier: sourceObjectUniversalIdentifier,
+ type: FieldMetadataType.TEXT,
+ name: 'status',
+ label: 'Status',
+ },
+ ],
+ frontComponents: [
+ {
+ universalIdentifier: frontComponentUniversalIdentifier,
+ sourceComponentPath: 'src/front-components/deployment.tsx',
+ builtComponentPath: 'dist/front-components/deployment.mjs',
+ builtComponentChecksum: 'checksum',
+ componentName: 'DeploymentTimelineActivity',
+ },
+ ],
+ timelineActivityTypes: [
+ {
+ universalIdentifier: '7a777777-7777-4777-8777-777777777777',
+ name: 'deploymentUpdated',
+ label: 'updated a deployment',
+ emit: {
+ on: 'updated',
+ objectUniversalIdentifier: sourceObjectUniversalIdentifier,
+ through: {
+ relationFieldUniversalIdentifier,
+ triggerFieldUniversalIdentifiers: [
+ triggerFieldUniversalIdentifier,
+ ],
+ },
+ },
+ frontComponentUniversalIdentifier,
+ },
+ ],
+ });
+
+ it('accepts references to source metadata and front components in the application', () => {
+ const result = manifestValidate(buildTimelineManifest());
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('reports references that cannot be resolved inside the application', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.frontComponentUniversalIdentifier =
+ '8a888888-8888-4888-8888-888888888888';
+ timelineActivityType.emit!.through!.relationFieldUniversalIdentifier =
+ '9a999999-9999-4999-8999-999999999999';
+ timelineActivityType.emit!.through!.triggerFieldUniversalIdentifiers = [
+ '0aaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ ];
+
+ const result = manifestValidate(manifest);
+
+ expect(result.errors).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('references front component'),
+ expect.stringContaining('references relation field'),
+ expect.stringContaining('references trigger fields'),
+ ]),
+ );
+ });
+
+ it('requires external-object emitters to declare the type they replace', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.emit!.objectUniversalIdentifier =
+ '0bbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+
+ expect(manifestValidate(manifest).errors).toContainEqual(
+ expect.stringContaining(
+ 'must declare replacesTimelineActivityTypeUniversalIdentifier',
+ ),
+ );
+
+ timelineActivityType.replacesTimelineActivityTypeUniversalIdentifier =
+ '0ccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+ expect(manifestValidate(manifest).errors).toHaveLength(0);
+ });
+
+ it('validates external-object route identifiers without resolving their metadata', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.emit!.objectUniversalIdentifier =
+ '0bbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+ timelineActivityType.replacesTimelineActivityTypeUniversalIdentifier =
+ '0ccccccc-cccc-4ccc-8ccc-cccccccccccc';
+ timelineActivityType.emit!.through!.relationFieldUniversalIdentifier =
+ 'not-a-relation-field-uuid';
+ timelineActivityType.emit!.through!.triggerFieldUniversalIdentifiers = [
+ 'not-a-trigger-field-uuid',
+ ];
+
+ expect(manifestValidate(manifest).errors).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(
+ 'invalid through relation field universal identifier',
+ ),
+ expect.stringContaining(
+ 'invalid trigger field universal identifiers',
+ ),
+ ]),
+ );
+ });
+
+ it('rejects an invalid emit object universal identifier', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.emit!.objectUniversalIdentifier = 'POST_CARD_TYPO';
+ timelineActivityType.replacesTimelineActivityTypeUniversalIdentifier =
+ '0ccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+ expect(manifestValidate(manifest).errors).toContainEqual(
+ expect.stringContaining('invalid object universal identifier'),
+ );
+ });
+
+ it('rejects replacement contracts that cannot be valid locally', () => {
+ const explicitManifest = buildTimelineManifest();
+ const [explicitTimelineActivityType] =
+ explicitManifest.timelineActivityTypes;
+
+ explicitTimelineActivityType.emit = undefined;
+ explicitTimelineActivityType.replacesTimelineActivityTypeUniversalIdentifier =
+ '0ccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+ expect(manifestValidate(explicitManifest).errors).toContainEqual(
+ expect.stringContaining(
+ 'declares replacesTimelineActivityTypeUniversalIdentifier without an automatic emit contract',
+ ),
+ );
+
+ const localObjectManifest = buildTimelineManifest();
+ localObjectManifest.timelineActivityTypes[0].replacesTimelineActivityTypeUniversalIdentifier =
+ '0ccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+ expect(manifestValidate(localObjectManifest).errors).toContainEqual(
+ expect.stringContaining("must not replace another application's type"),
+ );
+
+ const invalidIdentifierManifest = buildTimelineManifest();
+ const invalidIdentifierTimelineActivityType =
+ invalidIdentifierManifest.timelineActivityTypes[0];
+
+ invalidIdentifierTimelineActivityType.emit!.objectUniversalIdentifier =
+ '0bbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+ invalidIdentifierTimelineActivityType.replacesTimelineActivityTypeUniversalIdentifier =
+ 'not-a-uuid';
+
+ expect(manifestValidate(invalidIdentifierManifest).errors).toContainEqual(
+ expect.stringContaining('invalid replacement universal identifier'),
+ );
+ });
+
+ it.each([
+ {
+ action: 'updated' as const,
+ triggerFieldUniversalIdentifiers: [],
+ },
+ {
+ action: 'updated' as const,
+ triggerFieldUniversalIdentifiers: [
+ triggerFieldUniversalIdentifier,
+ triggerFieldUniversalIdentifier,
+ ],
+ },
+ {
+ action: 'created' as const,
+ triggerFieldUniversalIdentifiers: [triggerFieldUniversalIdentifier],
+ },
+ ])(
+ 'rejects invalid trigger constraints for $action events',
+ ({ action, triggerFieldUniversalIdentifiers }) => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.emit!.on = action;
+ timelineActivityType.emit!.through!.triggerFieldUniversalIdentifiers =
+ triggerFieldUniversalIdentifiers;
+
+ expect(manifestValidate(manifest).errors).toContainEqual(
+ expect.stringContaining(
+ 'trigger fields must be a non-empty list of unique fields on an updated through event',
+ ),
+ );
+ },
+ );
+
+ it('requires linked and unlinked emitters to declare a through relation', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ timelineActivityType.emit!.on = 'linked';
+ timelineActivityType.emit!.through = undefined;
+
+ expect(manifestValidate(manifest).errors).toContainEqual(
+ expect.stringContaining('must declare emit.through for a linked event'),
+ );
+ });
+
+ it('rejects duplicate names and unsupported through relations', () => {
+ const manifest = buildTimelineManifest();
+ const [timelineActivityType] = manifest.timelineActivityTypes;
+
+ manifest.timelineActivityTypes.push({
+ ...timelineActivityType,
+ universalIdentifier: '0ddddddd-dddd-4ddd-8ddd-dddddddddddd',
+ });
+ manifest.fields[0].universalSettings = {
+ relationType: RelationType.ONE_TO_MANY,
+ };
+
+ const result = manifestValidate(manifest);
+
+ expect(result.errors).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining(
+ 'Timeline activity type name "deploymentUpdated" is used more than once',
+ ),
+ expect.stringContaining(
+ 'must route through a MANY_TO_ONE relation or a junction-backed ONE_TO_MANY relation',
+ ),
+ ]),
+ );
+ });
+
+ it('reports a relation with missing universal settings without crashing', () => {
+ const manifest = buildTimelineManifest();
+
+ manifest.fields[0].universalSettings = undefined as never;
+
+ expect(manifestValidate(manifest).errors).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('is missing relationType'),
+ expect.stringContaining(
+ 'must route through a MANY_TO_ONE relation or a junction-backed ONE_TO_MANY relation',
+ ),
+ ]),
+ );
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/build-and-validate-manifest.ts b/packages/twenty-cli/src/app/manifest/build-and-validate-manifest.ts
new file mode 100644
index 00000000000..73a6f18825b
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/build-and-validate-manifest.ts
@@ -0,0 +1,69 @@
+import { type EntityFilePaths } from '@/app/manifest/types/entity-file-paths.type';
+import { buildManifest } from '@/app/manifest/manifest-build';
+import { manifestValidate } from '@/app/manifest/manifest-validate';
+import { validatePackageJsonDependencies } from '@/app/manifest/utils/validate-package-json-dependencies';
+import { validateYarnLock } from '@/app/manifest/utils/validate-yarn-lock';
+import { type Manifest } from 'twenty-shared/application';
+
+export type BuildAndValidateManifestSuccess = {
+ success: true;
+ manifest: Manifest;
+ filePaths: EntityFilePaths;
+ warnings: string[];
+};
+
+export type BuildAndValidateManifestFailure = {
+ success: false;
+ errors: string[];
+};
+
+export type BuildAndValidateManifestResult =
+ | BuildAndValidateManifestSuccess
+ | BuildAndValidateManifestFailure;
+
+export const buildAndValidateManifest = async (
+ appPath: string,
+): Promise<BuildAndValidateManifestResult> => {
+ const result = await buildManifest(appPath);
+
+ if (result.errors.length > 0 || !result.manifest) {
+ return {
+ success: false,
+ errors:
+ result.errors.length > 0
+ ? result.errors
+ : ['Failed to build manifest.'],
+ };
+ }
+
+ const validation = manifestValidate(result.manifest);
+
+ if (!validation.isValid) {
+ return {
+ success: false,
+ errors: validation.errors,
+ };
+ }
+
+ const yarnLockErrors = await validateYarnLock(appPath);
+
+ if (yarnLockErrors.length > 0) {
+ return {
+ success: false,
+ errors: yarnLockErrors,
+ };
+ }
+
+ const packageJsonWarnings = await validatePackageJsonDependencies(appPath);
+
+ return {
+ success: true,
+ manifest: result.manifest,
+ filePaths: result.filePaths,
+ warnings: [
+ ...result.warnings,
+ ...validation.warnings,
+ ...packageJsonWarnings,
+ ],
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/get-engine-version-range.ts b/packages/twenty-cli/src/app/manifest/get-engine-version-range.ts
new file mode 100644
index 00000000000..8d9240b3c71
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/get-engine-version-range.ts
@@ -0,0 +1,18 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+export const getEngineVersionRange = (cwd: string): string | null => {
+ try {
+ const pkg = JSON.parse(
+ readFileSync(join(cwd, 'package.json'), 'utf-8'),
+ ) as { engines?: { twenty?: unknown } };
+
+ const range = pkg.engines?.twenty;
+
+ return typeof range === 'string' && range.trim() !== ''
+ ? range.trim()
+ : null;
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/twenty-cli/src/app/manifest/manifest-build.ts b/packages/twenty-cli/src/app/manifest/manifest-build.ts
new file mode 100644
index 00000000000..2be60ad7131
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/manifest-build.ts
@@ -0,0 +1,732 @@
+import { fromObjectConfigToObjectManifest } from '@/app/manifest/utils/from-object-config-to-object-manifest';
+import { fromLogicFunctionConfigToLogicFunctionManifest } from '@/app/manifest/utils/from-logic-function-config-to-logic-function-manifest';
+import { fromFrontComponentConfigToFrontComponentManifest } from '@/app/manifest/utils/from-front-component-config-to-front-component-manifest';
+import { listApplicationSourceFiles } from '@/app/source/list-application-source-files';
+import { type EntityFilePaths } from '@/app/manifest/types/entity-file-paths.type';
+import {
+ extractDefineEntity,
+ DEFINE_ENTITY_KEYS,
+} from '@/app/source/extract-define-entity';
+import { extractManifestFromFile } from '@/app/source/extract-manifest-from-file';
+import { addMissingFieldOptionIds } from '@/app/manifest/utils/add-missing-field-option-ids';
+import { fromRoleConfigToRoleManifest } from '@/app/manifest/utils/from-role-config-to-role-manifest';
+import { extractFrontComponentSharedDependencies } from '@/app/manifest/utils/extract-front-component-shared-dependencies';
+import { validateConditionalAvailabilityUsage } from '@/app/manifest/utils/validate-conditional-availability-usage';
+import { validateAgentRolesWithinApplicationRole } from '@/app/manifest/utils/validate-agent-roles-within-application-role';
+import { validateViewFilterOperands } from '@/app/manifest/utils/validate-view-filter-operands';
+import { getEngineVersionRange } from '@/app/manifest/get-engine-version-range';
+import { type ApplicationConfig } from '@/app/manifest/types/application-config.type';
+import { type LogicFunctionConfig } from '@/app/manifest/types/logic-function-config.type';
+import { type CommandMenuItemConfig } from '@/app/manifest/types/command-menu-item-config.type';
+import { type FrontComponentConfig } from '@/app/manifest/types/front-component-config.type';
+import { type IndexConfig } from '@/app/manifest/types/index-config.type';
+import { type PostInstallLogicFunctionConfig } from '@/app/manifest/types/post-install-logic-function-config.type';
+import { type PreInstallLogicFunctionConfig } from '@/app/manifest/types/pre-install-logic-function-config.type';
+import { type ObjectConfig } from '@/app/manifest/types/object-config.type';
+import { type PageLayoutConfig } from '@/app/manifest/types/page-layout-config.type';
+import { type PageLayoutTabConfig } from '@/app/manifest/types/page-layout-tab-config.type';
+import { type RoleConfig } from '@/app/manifest/types/role-config.type';
+import { type TimelineActivityTypeConfig } from '@/app/manifest/types/timeline-activity-type-config.type';
+import { type SettingsMenuItemConfig } from '@/app/manifest/types/settings-menu-item-config.type';
+import { type ViewConfig } from '@/app/manifest/types/view-config.type';
+import { readFile } from 'node:fs/promises';
+import { basename, extname, join, relative } from 'path';
+import { glob } from 'tinyglobby';
+import {
+ type AgentManifest,
+ type ApplicationManifest,
+ type AssetManifest,
+ ASSETS_DIR,
+ type CommandMenuItemManifest,
+ type ConnectionProviderManifest,
+ type FieldManifest,
+ type FrontComponentManifest,
+ type IndexManifest,
+ type LogicFunctionManifest,
+ type Manifest,
+ type NavigationMenuItemManifest,
+ type ObjectManifest,
+ type PageLayoutManifest,
+ type PageLayoutTabManifest,
+ type PermissionFlagManifest,
+ type PostInstallLogicFunctionApplicationManifest,
+ type PreInstallLogicFunctionApplicationManifest,
+ type UninstallLogicFunctionApplicationManifest,
+ type HealthCheckLogicFunctionApplicationManifest,
+ type RoleManifest,
+ type SkillManifest,
+ type StandalonePageLayoutWidgetManifest,
+ type StandaloneViewFieldManifest,
+ type SettingsMenuItemManifest,
+ type TimelineActivityTypeManifest,
+ type ViewManifest,
+} from 'twenty-shared/application';
+import { assertUnreachable, isDefined } from 'twenty-shared/utils';
+
+const loadSources = (appPath: string): Promise<string[]> =>
+ listApplicationSourceFiles(appPath);
+
+const loadAssets = async (appPath: string) => {
+ const assetPaths = await glob([`${ASSETS_DIR}/**/*`], {
+ cwd: appPath,
+ absolute: true,
+ onlyFiles: true,
+ });
+
+ return assetPaths.sort();
+};
+
+const loadReadme = async (appPath: string): Promise<string | undefined> => {
+ try {
+ const content = await readFile(join(appPath, 'README.md'), 'utf-8');
+
+ return content.trim().length > 0 ? content : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const buildManifest = async (
+ appPath: string,
+): Promise<{
+ manifest: Manifest | null;
+ filePaths: EntityFilePaths;
+ errors: string[];
+ warnings: string[];
+}> => {
+ const filePaths = await loadSources(appPath);
+ const readmeContent = await loadReadme(appPath);
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ let applicationConfig: ApplicationConfig | undefined;
+ const objectConfigs: ObjectConfig[] = [];
+ const roleConfigs: RoleConfig[] = [];
+ const objects: ObjectManifest[] = [];
+ const fields: FieldManifest[] = [];
+ const indexes: IndexManifest[] = [];
+ const permissionFlags: PermissionFlagManifest[] = [];
+ const roles: RoleManifest[] = [];
+ const skills: SkillManifest[] = [];
+ const agents: AgentManifest[] = [];
+ const connectionProviders: ConnectionProviderManifest[] = [];
+ const logicFunctions: LogicFunctionManifest[] = [];
+ const frontComponents: FrontComponentManifest[] = [];
+ const publicAssets: AssetManifest[] = [];
+ const views: ViewManifest[] = [];
+ const viewFields: StandaloneViewFieldManifest[] = [];
+ const navigationMenuItems: NavigationMenuItemManifest[] = [];
+ const pageLayouts: PageLayoutManifest[] = [];
+ const pageLayoutTabs: PageLayoutTabManifest[] = [];
+ const pageLayoutWidgets: StandalonePageLayoutWidgetManifest[] = [];
+ const commandMenuItems: CommandMenuItemManifest[] = [];
+ const timelineActivityTypes: TimelineActivityTypeManifest[] = [];
+ const settingsMenuItems: SettingsMenuItemManifest[] = [];
+ const postInstallLogicFunctions: PostInstallLogicFunctionApplicationManifest[] =
+ [];
+ const preInstallLogicFunctions: PreInstallLogicFunctionApplicationManifest[] =
+ [];
+ const uninstallLogicFunctions: UninstallLogicFunctionApplicationManifest[] =
+ [];
+ const healthCheckLogicFunctions: HealthCheckLogicFunctionApplicationManifest[] =
+ [];
+ const settingsFrontComponentUniversalIdentifiers: string[] = [];
+ const applicationRoleUniversalIdentifiers: string[] = [];
+ const applicationFilePaths: string[] = [];
+ const objectsFilePaths: string[] = [];
+ const fieldsFilePaths: string[] = [];
+ const indexesFilePaths: string[] = [];
+ const permissionFlagsFilePaths: string[] = [];
+ const rolesFilePaths: string[] = [];
+ const skillsFilePaths: string[] = [];
+ const agentsFilePaths: string[] = [];
+ const connectionProvidersFilePaths: string[] = [];
+ const logicFunctionsFilePaths: string[] = [];
+ const frontComponentsFilePaths: string[] = [];
+ const publicAssetsFilePaths: string[] = [];
+ const viewsFilePaths: string[] = [];
+ const viewFieldsFilePaths: string[] = [];
+ const navigationMenuItemsFilePaths: string[] = [];
+ const pageLayoutsFilePaths: string[] = [];
+ const pageLayoutTabsFilePaths: string[] = [];
+ const pageLayoutWidgetsFilePaths: string[] = [];
+ const commandMenuItemsFilePaths: string[] = [];
+ const timelineActivityTypesFilePaths: string[] = [];
+ const settingsMenuItemsFilePaths: string[] = [];
+
+ for (const filePath of filePaths) {
+ const fileContent = await readFile(filePath, 'utf-8');
+ const relativePath = relative(appPath, filePath);
+
+ errors.push(
+ ...validateConditionalAvailabilityUsage(fileContent, relativePath),
+ );
+
+ const targetFunctionName = extractDefineEntity(fileContent);
+
+ if (!targetFunctionName) {
+ continue;
+ }
+
+ const entity = DEFINE_ENTITY_KEYS[targetFunctionName];
+
+ switch (entity) {
+ case 'application': {
+ const extract = await extractManifestFromFile<ApplicationConfig>({
+ appPath,
+ filePath,
+ });
+
+ applicationConfig = extract.config;
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ applicationFilePaths.push(relativePath);
+ break;
+ }
+ case 'objects': {
+ const extract = await extractManifestFromFile<ObjectConfig>({
+ appPath,
+ filePath,
+ });
+
+ objectConfigs.push(extract.config);
+
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ objectsFilePaths.push(relativePath);
+ break;
+ }
+ case 'fields': {
+ const extract = await extractManifestFromFile<FieldManifest>({
+ appPath,
+ filePath,
+ });
+ const fieldConfig = addMissingFieldOptionIds(extract.config);
+ fields.push(fieldConfig);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ fieldsFilePaths.push(relativePath);
+ break;
+ }
+ case 'permissionFlags': {
+ const extract = await extractManifestFromFile<PermissionFlagManifest>({
+ appPath,
+ filePath,
+ });
+ permissionFlags.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ permissionFlagsFilePaths.push(relativePath);
+ break;
+ }
+ case 'roles': {
+ const extract = await extractManifestFromFile<RoleConfig>({
+ appPath,
+ filePath,
+ });
+ roleConfigs.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ rolesFilePaths.push(relativePath);
+
+ if (targetFunctionName === 'defineApplicationRole') {
+ applicationRoleUniversalIdentifiers.push(
+ extract.config.universalIdentifier,
+ );
+ }
+
+ break;
+ }
+ case 'skills': {
+ const extract = await extractManifestFromFile<SkillManifest>({
+ appPath,
+ filePath,
+ });
+ skills.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ skillsFilePaths.push(relativePath);
+ break;
+ }
+ case 'agents': {
+ const extract = await extractManifestFromFile<AgentManifest>({
+ appPath,
+ filePath,
+ });
+ agents.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ agentsFilePaths.push(relativePath);
+ break;
+ }
+ case 'connectionProviders': {
+ const extract =
+ await extractManifestFromFile<ConnectionProviderManifest>({
+ appPath,
+ filePath,
+ });
+ connectionProviders.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ connectionProvidersFilePaths.push(relativePath);
+ break;
+ }
+ case 'logicFunctions': {
+ const extract = await extractManifestFromFile<LogicFunctionConfig>({
+ appPath,
+ filePath,
+ });
+
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+
+ if (
+ targetFunctionName === 'definePreInstallLogicFunction' &&
+ isDefined(extract.config.serverRouteTriggerSettings)
+ ) {
+ errors.push(
+ `${relativePath}: pre-install logic functions cannot define serverRouteTriggerSettings.`,
+ );
+ }
+
+ const config = await fromLogicFunctionConfigToLogicFunctionManifest({
+ logicFunctionConfig: extract.config,
+ sourceCode: fileContent,
+ sourcePath: relativePath,
+ });
+
+ logicFunctions.push(config);
+ logicFunctionsFilePaths.push(relativePath);
+
+ if (targetFunctionName === 'definePostInstallLogicFunction') {
+ const postInstallHookConfig =
+ extract.config as PostInstallLogicFunctionConfig;
+
+ postInstallLogicFunctions.push({
+ universalIdentifier: extract.config.universalIdentifier,
+ shouldRunOnVersionUpgrade:
+ postInstallHookConfig.shouldRunOnVersionUpgrade ?? false,
+ shouldRunSynchronously:
+ postInstallHookConfig.shouldRunSynchronously ?? false,
+ });
+ }
+
+ if (targetFunctionName === 'definePreInstallLogicFunction') {
+ const preInstallHookConfig =
+ extract.config as PreInstallLogicFunctionConfig;
+
+ preInstallLogicFunctions.push({
+ universalIdentifier: extract.config.universalIdentifier,
+ shouldRunOnVersionUpgrade:
+ preInstallHookConfig.shouldRunOnVersionUpgrade ?? false,
+ });
+ }
+
+ if (targetFunctionName === 'defineUninstallLogicFunction') {
+ uninstallLogicFunctions.push({
+ universalIdentifier: extract.config.universalIdentifier,
+ });
+ }
+
+ if (targetFunctionName === 'defineHealthCheck') {
+ healthCheckLogicFunctions.push({
+ universalIdentifier: extract.config.universalIdentifier,
+ });
+ }
+
+ break;
+ }
+ case 'frontComponents': {
+ const extract = await extractManifestFromFile<FrontComponentConfig>({
+ appPath,
+ filePath,
+ });
+
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+
+ const config = fromFrontComponentConfigToFrontComponentManifest({
+ frontComponentConfig: extract.config,
+ sourcePath: relativePath,
+ });
+
+ frontComponents.push(config);
+ frontComponentsFilePaths.push(relativePath);
+
+ if (targetFunctionName === 'defineSettingsFrontComponent') {
+ settingsFrontComponentUniversalIdentifiers.push(
+ extract.config.universalIdentifier,
+ );
+ }
+
+ break;
+ }
+ case 'views': {
+ const extract = await extractManifestFromFile<ViewConfig>({
+ appPath,
+ filePath,
+ });
+
+ const viewManifest: ViewManifest = {
+ ...extract.config,
+ };
+
+ views.push(viewManifest);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ viewsFilePaths.push(relativePath);
+ break;
+ }
+ case 'viewFields': {
+ const extract =
+ await extractManifestFromFile<StandaloneViewFieldManifest>({
+ appPath,
+ filePath,
+ });
+
+ viewFields.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ viewFieldsFilePaths.push(relativePath);
+ break;
+ }
+ case 'navigationMenuItems': {
+ const extract =
+ await extractManifestFromFile<NavigationMenuItemManifest>({
+ appPath,
+ filePath,
+ });
+ navigationMenuItems.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ navigationMenuItemsFilePaths.push(relativePath);
+ break;
+ }
+ case 'pageLayouts': {
+ const extract = await extractManifestFromFile<PageLayoutConfig>({
+ appPath,
+ filePath,
+ });
+
+ const pageLayoutManifest: PageLayoutManifest = {
+ ...extract.config,
+ };
+
+ pageLayouts.push(pageLayoutManifest);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ pageLayoutsFilePaths.push(relativePath);
+ break;
+ }
+ case 'indexes': {
+ const extract = await extractManifestFromFile<IndexConfig>({
+ appPath,
+ filePath,
+ });
+
+ const indexManifest: IndexManifest = {
+ ...extract.config,
+ };
+
+ indexes.push(indexManifest);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ indexesFilePaths.push(relativePath);
+ break;
+ }
+ case 'pageLayoutTabs': {
+ const extract = await extractManifestFromFile<PageLayoutTabConfig>({
+ appPath,
+ filePath,
+ });
+
+ const pageLayoutTabManifest: PageLayoutTabManifest = {
+ ...extract.config,
+ };
+
+ pageLayoutTabs.push(pageLayoutTabManifest);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ pageLayoutTabsFilePaths.push(relativePath);
+ break;
+ }
+ case 'pageLayoutWidgets': {
+ const extract =
+ await extractManifestFromFile<StandalonePageLayoutWidgetManifest>({
+ appPath,
+ filePath,
+ });
+
+ pageLayoutWidgets.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ pageLayoutWidgetsFilePaths.push(relativePath);
+ break;
+ }
+ case 'commandMenuItems': {
+ const extract = await extractManifestFromFile<CommandMenuItemConfig>({
+ appPath,
+ filePath,
+ });
+
+ commandMenuItems.push(
+ extract.config as unknown as CommandMenuItemManifest,
+ );
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ commandMenuItemsFilePaths.push(relativePath);
+ break;
+ }
+ case 'timelineActivityTypes': {
+ const extract =
+ await extractManifestFromFile<TimelineActivityTypeConfig>({
+ appPath,
+ filePath,
+ });
+
+ timelineActivityTypes.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ timelineActivityTypesFilePaths.push(relativePath);
+ break;
+ }
+ case 'settingsMenuItems': {
+ const extract = await extractManifestFromFile<SettingsMenuItemConfig>({
+ appPath,
+ filePath,
+ });
+
+ settingsMenuItems.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ settingsMenuItemsFilePaths.push(relativePath);
+ break;
+ }
+ default: {
+ assertUnreachable(entity);
+ }
+ }
+ }
+
+ const assetFiles = await loadAssets(appPath);
+
+ for (const assetFile of assetFiles) {
+ const relativePath = relative(appPath, assetFile);
+ publicAssets.push({
+ filePath: relativePath,
+ fileName: basename(assetFile),
+ fileType: extname(assetFile).replace(/^\./, ''),
+ checksum: null,
+ });
+ publicAssetsFilePaths.push(relativePath);
+ }
+
+ if (!applicationConfig) {
+ errors.push(
+ 'Cannot build application, please export default defineApplication() to define an application',
+ );
+ }
+
+ if (applicationConfig) {
+ for (const objectConfig of objectConfigs) {
+ const { objectManifest, errors: objectErrors } =
+ fromObjectConfigToObjectManifest({
+ objectConfig,
+ applicationUniversalIdentifier: applicationConfig.universalIdentifier,
+ });
+
+ errors.push(...objectErrors);
+
+ if (!objectManifest) {
+ continue;
+ }
+
+ objects.push(objectManifest);
+ }
+
+ for (const roleConfig of roleConfigs) {
+ roles.push(
+ fromRoleConfigToRoleManifest({
+ roleConfig,
+ applicationUniversalIdentifier: applicationConfig.universalIdentifier,
+ }),
+ );
+ }
+ }
+
+ if (postInstallLogicFunctions.length > 1) {
+ errors.push(
+ 'Only one post install logic function is allowed per application',
+ );
+ }
+
+ if (preInstallLogicFunctions.length > 1) {
+ errors.push(
+ 'Only one pre install logic function is allowed per application',
+ );
+ }
+
+ if (uninstallLogicFunctions.length > 1) {
+ errors.push('Only one uninstall logic function is allowed per application');
+ }
+
+ if (healthCheckLogicFunctions.length > 1) {
+ errors.push('Only one health check is allowed per application');
+ }
+
+ if (settingsFrontComponentUniversalIdentifiers.length > 1) {
+ errors.push('Only one settings front component is allowed per application');
+ }
+
+ if (applicationRoleUniversalIdentifiers.length > 1) {
+ errors.push('Only one defineApplicationRole is allowed per application');
+ }
+
+ const { sharedDependencies, errors: sharedDependenciesErrors } =
+ await extractFrontComponentSharedDependencies(appPath);
+
+ errors.push(...sharedDependenciesErrors);
+
+ const resolvedDefaultRoleUniversalIdentifier =
+ applicationConfig?.defaultRoleUniversalIdentifier ??
+ (applicationRoleUniversalIdentifiers.length === 1
+ ? applicationRoleUniversalIdentifiers[0]
+ : undefined);
+
+ if (applicationConfig && !resolvedDefaultRoleUniversalIdentifier) {
+ errors.push(
+ 'Application must declare a default role: either pass `defaultRoleUniversalIdentifier` to defineApplication() or mark a role file with defineApplicationRole()',
+ );
+ }
+
+ errors.push(
+ ...validateViewFilterOperands({
+ views,
+ objects,
+ fields,
+ }),
+ );
+
+ if (
+ isDefined(applicationConfig) &&
+ isDefined(resolvedDefaultRoleUniversalIdentifier)
+ ) {
+ errors.push(
+ ...validateAgentRolesWithinApplicationRole({
+ agents,
+ roles,
+ objects,
+ permissionFlags,
+ defaultRoleUniversalIdentifier: resolvedDefaultRoleUniversalIdentifier,
+ }),
+ );
+ }
+
+ const application: ApplicationManifest | undefined =
+ applicationConfig && resolvedDefaultRoleUniversalIdentifier
+ ? (() => {
+ const {
+ logoUrl: _logoUrl,
+ screenshots: _screenshots,
+ ...applicationConfigRest
+ } = applicationConfig;
+
+ return {
+ ...applicationConfigRest,
+ logo: applicationConfig.logo,
+ galleryImages: applicationConfig.galleryImages ?? [],
+ defaultRoleUniversalIdentifier:
+ resolvedDefaultRoleUniversalIdentifier,
+ aboutDescription: readmeContent,
+ yarnLockChecksum: null,
+ packageJsonChecksum: null,
+ requiredServerVersionRange: getEngineVersionRange(appPath),
+ ...(postInstallLogicFunctions.length >= 1
+ ? { postInstallLogicFunction: postInstallLogicFunctions[0] }
+ : {}),
+ ...(preInstallLogicFunctions.length >= 1
+ ? { preInstallLogicFunction: preInstallLogicFunctions[0] }
+ : {}),
+ ...(uninstallLogicFunctions.length >= 1
+ ? { uninstallLogicFunction: uninstallLogicFunctions[0] }
+ : {}),
+ ...(healthCheckLogicFunctions.length >= 1
+ ? { healthCheckLogicFunction: healthCheckLogicFunctions[0] }
+ : {}),
+ ...(settingsFrontComponentUniversalIdentifiers.length >= 1
+ ? {
+ settingsFrontComponent: {
+ universalIdentifier:
+ settingsFrontComponentUniversalIdentifiers[0],
+ },
+ }
+ : {}),
+ ...(isDefined(sharedDependencies)
+ ? { frontComponentSharedDependencies: sharedDependencies }
+ : {}),
+ };
+ })()
+ : undefined;
+
+ const byId = <TEntity extends { universalIdentifier: string }>(
+ a: TEntity,
+ b: TEntity,
+ ) => a.universalIdentifier.localeCompare(b.universalIdentifier);
+
+ const byPath = <TEntity extends { filePath: string }>(
+ a: TEntity,
+ b: TEntity,
+ ) => a.filePath.localeCompare(b.filePath);
+
+ const manifest: Manifest | null = !application
+ ? null
+ : {
+ application,
+ objects: objects.sort(byId),
+ fields: fields.sort(byId),
+ indexes: indexes.sort(byId),
+ permissionFlags: permissionFlags.sort(byId),
+ roles: roles.sort(byId),
+ skills: skills.sort(byId),
+ agents: agents.sort(byId),
+ connectionProviders: connectionProviders.sort(byId),
+ logicFunctions: logicFunctions.sort(byId),
+ frontComponents: frontComponents.sort(byId),
+ publicAssets: publicAssets.sort(byPath),
+ views: views.sort(byId),
+ viewFields: viewFields.sort(byId),
+ navigationMenuItems: navigationMenuItems.sort(byId),
+ pageLayouts: pageLayouts.sort(byId),
+ pageLayoutTabs: pageLayoutTabs.sort(byId),
+ pageLayoutWidgets: pageLayoutWidgets.sort(byId),
+ commandMenuItems: commandMenuItems.sort(byId),
+ timelineActivityTypes: timelineActivityTypes.sort(byId),
+ settingsMenuItems: settingsMenuItems.sort(byId),
+ };
+
+ const entityFilePaths: EntityFilePaths = {
+ application: applicationFilePaths,
+ objects: objectsFilePaths,
+ fields: fieldsFilePaths,
+ indexes: indexesFilePaths,
+ permissionFlags: permissionFlagsFilePaths,
+ roles: rolesFilePaths,
+ skills: skillsFilePaths,
+ agents: agentsFilePaths,
+ connectionProviders: connectionProvidersFilePaths,
+ logicFunctions: logicFunctionsFilePaths,
+ frontComponents: frontComponentsFilePaths,
+ publicAssets: publicAssetsFilePaths,
+ views: viewsFilePaths,
+ viewFields: viewFieldsFilePaths,
+ navigationMenuItems: navigationMenuItemsFilePaths,
+ pageLayouts: pageLayoutsFilePaths,
+ pageLayoutTabs: pageLayoutTabsFilePaths,
+ pageLayoutWidgets: pageLayoutWidgetsFilePaths,
+ commandMenuItems: commandMenuItemsFilePaths,
+ timelineActivityTypes: timelineActivityTypesFilePaths,
+ settingsMenuItems: settingsMenuItemsFilePaths,
+ };
+
+ return { manifest, filePaths: entityFilePaths, errors, warnings };
+};
diff --git a/packages/twenty-cli/src/app/manifest/manifest-update-checksums.ts b/packages/twenty-cli/src/app/manifest/manifest-update-checksums.ts
new file mode 100644
index 00000000000..58b4af64a00
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/manifest-update-checksums.ts
@@ -0,0 +1,127 @@
+import { relative } from 'path';
+import { type Manifest, OUTPUT_DIR } from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import type { EntityFilePaths } from '@/app/manifest/types/entity-file-paths.type';
+
+export type ManifestBuildResult = {
+ manifest: Manifest | null;
+ filePaths: EntityFilePaths;
+ error?: string;
+};
+
+export type UpdateManifestChecksumParams = {
+ outputDir?: string;
+ manifest: Manifest;
+ builtFileInfos: Map<
+ string,
+ {
+ checksum: string;
+ builtPath: string;
+ fileFolder: FileFolder;
+ usesSdkClient?: boolean;
+ }
+ >;
+};
+
+export const manifestUpdateChecksums = ({
+ manifest,
+ builtFileInfos,
+ outputDir = OUTPUT_DIR,
+}: UpdateManifestChecksumParams): Manifest => {
+ let result = structuredClone(manifest);
+ for (const [
+ builtPath,
+ { fileFolder, checksum },
+ ] of builtFileInfos.entries()) {
+ const rootBuiltPath = relative(outputDir, builtPath);
+ if (fileFolder === FileFolder.BuiltLogicFunction) {
+ const logicFunctions = result.logicFunctions;
+ const fnIndex = logicFunctions.findIndex(
+ (f) => f.builtHandlerPath === rootBuiltPath,
+ );
+ if (fnIndex === -1) {
+ continue;
+ }
+ result = {
+ ...result,
+ logicFunctions: logicFunctions.map((fn, index) =>
+ index === fnIndex ? { ...fn, builtHandlerChecksum: checksum } : fn,
+ ),
+ };
+ }
+
+ if (fileFolder === FileFolder.PublicAsset) {
+ const assets = result.publicAssets;
+ const assetIndex = assets.findIndex((a) => a.filePath === rootBuiltPath);
+ if (assetIndex === -1) {
+ continue;
+ }
+ result = {
+ ...result,
+ publicAssets: assets.map((asset, index) =>
+ index === assetIndex ? { ...asset, checksum } : asset,
+ ),
+ };
+ continue;
+ }
+
+ if (fileFolder === FileFolder.BuiltFrontComponent) {
+ const sharedDependencies =
+ result.application.frontComponentSharedDependencies;
+
+ if (
+ isDefined(sharedDependencies) &&
+ sharedDependencies.builtPath === rootBuiltPath
+ ) {
+ result = {
+ ...result,
+ application: {
+ ...result.application,
+ frontComponentSharedDependencies: {
+ ...sharedDependencies,
+ builtChecksum: checksum,
+ },
+ },
+ };
+ continue;
+ }
+
+ const frontComponents = result.frontComponents;
+ const componentIndex =
+ frontComponents.findIndex(
+ (c) => c.builtComponentPath === rootBuiltPath,
+ ) ?? -1;
+ if (componentIndex === -1) {
+ continue;
+ }
+ const builtFileInfo = builtFileInfos.get(builtPath);
+
+ result = {
+ ...result,
+ frontComponents: frontComponents.map((component, index) =>
+ index === componentIndex
+ ? {
+ ...component,
+ builtComponentChecksum: checksum,
+ usesSdkClient: builtFileInfo?.usesSdkClient ?? false,
+ }
+ : component,
+ ),
+ };
+ }
+
+ if (fileFolder === FileFolder.Dependencies) {
+ if (rootBuiltPath === 'package.json') {
+ result.application.packageJsonChecksum = checksum;
+ }
+
+ if (rootBuiltPath === 'yarn.lock') {
+ result.application.yarnLockChecksum = checksum;
+ }
+ }
+ }
+
+ return result;
+};
diff --git a/packages/twenty-cli/src/app/manifest/manifest-validate.ts b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
new file mode 100644
index 00000000000..82e94595ca1
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
@@ -0,0 +1,321 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { validate as uuidValidate, version as uuidVersion } from 'uuid';
+
+import {
+ MINIMUM_UNIVERSAL_IDENTIFIER_UUID_VERSION,
+ type Manifest,
+ type PageLayoutManifest,
+ type PageLayoutTabManifest,
+ type PageLayoutWidgetManifest,
+ isValidUniversalIdentifier,
+ normalizePageLayoutTabManifest,
+} from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ GRAPH_WIDGET_CONFIGURATION_TYPES,
+ type GraphWidgetConfigurationType,
+ type PageLayoutWidgetUniversalConfiguration,
+ RelationType,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ getDuplicateValues,
+ type ManifestField,
+ isRelationFieldManifest,
+} from '@/app/manifest/utils/manifest-validation-helpers';
+import { getPageLayoutDeprecationWarnings } from '@/app/manifest/utils/get-page-layout-deprecation-warnings';
+import { getUnresolvedLabelIdentifierWarnings } from '@/app/manifest/utils/get-unresolved-label-identifier-warnings';
+import { validateTimelineActivityTypes } from '@/app/manifest/utils/validate-timeline-activity-types';
+
+const VALID_RELATION_TYPES: string[] = [
+ RelationType.MANY_TO_ONE,
+ RelationType.ONE_TO_MANY,
+];
+
+const RAW_AGGREGATE_FIELD_METADATA_ID_KEY = 'aggregateFieldMetadataId';
+
+type GraphPageLayoutWidgetUniversalConfiguration = Extract<
+ PageLayoutWidgetUniversalConfiguration,
+ { configurationType: GraphWidgetConfigurationType }
+>;
+
+const isGraphWidgetConfiguration = (
+ configuration: PageLayoutWidgetUniversalConfiguration | null | undefined,
+): configuration is GraphPageLayoutWidgetUniversalConfiguration =>
+ isDefined(configuration) &&
+ GRAPH_WIDGET_CONFIGURATION_TYPES.some(
+ (configurationType) =>
+ configurationType === configuration.configurationType,
+ );
+
+const findUniversalIdentifiers = (obj: object): string[] => {
+ const universalIdentifiers: string[] = [];
+
+ if (!obj) {
+ return [];
+ }
+
+ for (const [key, val] of Object.entries(obj)) {
+ if (key === 'universalIdentifier' && typeof val === 'string') {
+ universalIdentifiers.push(val);
+ }
+
+ if (
+ key === 'postInstallLogicFunction' ||
+ key === 'preInstallLogicFunction' ||
+ key === 'uninstallLogicFunction' ||
+ key === 'healthCheckLogicFunction' ||
+ key === 'onConnectLogicFunction' ||
+ key === 'onDisconnectLogicFunction' ||
+ key === 'settingsFrontComponent'
+ ) {
+ continue;
+ }
+
+ if (typeof val === 'object') {
+ universalIdentifiers.push(...findUniversalIdentifiers(val));
+ }
+ }
+
+ return universalIdentifiers;
+};
+
+const validateRelationFields = (fields: ManifestField[]): string[] => {
+ const errors: string[] = [];
+
+ for (const field of fields) {
+ if (!isRelationFieldManifest(field)) {
+ continue;
+ }
+
+ const settings = field.universalSettings;
+
+ if (!settings?.relationType) {
+ errors.push(
+ `Relation field "${field.name}" is missing relationType. ` +
+ `${field.type} fields must declare a relationType (${VALID_RELATION_TYPES.join(' or ')}) in universalSettings.`,
+ );
+ continue;
+ }
+
+ if (!VALID_RELATION_TYPES.includes(settings.relationType)) {
+ errors.push(
+ `Relation field "${field.name}" has invalid relationType "${settings.relationType}". ` +
+ `Expected ${VALID_RELATION_TYPES.join(' or ')}.`,
+ );
+ continue;
+ }
+
+ if (
+ settings.relationType === RelationType.MANY_TO_ONE &&
+ !settings.joinColumnName
+ ) {
+ errors.push(
+ `MANY_TO_ONE relation field "${field.name}" is missing joinColumnName. ` +
+ `MANY_TO_ONE relations must declare a joinColumnName in universalSettings.`,
+ );
+ }
+ }
+
+ return errors;
+};
+
+const collectPageLayoutWidgets = (
+ manifest: Pick<
+ Manifest,
+ 'pageLayouts' | 'pageLayoutTabs' | 'pageLayoutWidgets'
+ >,
+): PageLayoutWidgetManifest[] => {
+ const widgetsFromPageLayouts = manifest.pageLayouts.flatMap(
+ (pageLayout) => pageLayout.tabs?.flatMap((tab) => tab.widgets ?? []) ?? [],
+ );
+
+ const widgetsFromStandaloneTabs = manifest.pageLayoutTabs.flatMap(
+ (tab) => tab.widgets ?? [],
+ );
+
+ return [
+ ...widgetsFromPageLayouts,
+ ...widgetsFromStandaloneTabs,
+ ...(manifest.pageLayoutWidgets ?? []),
+ ];
+};
+
+const validateGraphWidgets = (
+ widgets: PageLayoutWidgetManifest[],
+): string[] => {
+ const errors: string[] = [];
+
+ for (const widget of widgets) {
+ const configuration = widget.configuration;
+
+ if (!isGraphWidgetConfiguration(configuration)) {
+ continue;
+ }
+
+ if (
+ !isNonEmptyString(configuration.aggregateFieldMetadataUniversalIdentifier)
+ ) {
+ const usedRawKey = RAW_AGGREGATE_FIELD_METADATA_ID_KEY in configuration;
+
+ const hint = usedRawKey
+ ? ` Reference the aggregate field with "aggregateFieldMetadataUniversalIdentifier" (not "${RAW_AGGREGATE_FIELD_METADATA_ID_KEY}").`
+ : '';
+
+ errors.push(
+ `Graph widget "${widget.title}" is missing aggregateFieldMetadataUniversalIdentifier.${hint}`,
+ );
+ }
+ }
+
+ return errors;
+};
+
+const validatePageLayoutTab = ({
+ pageLayoutTab,
+ pageLayoutType,
+}: {
+ pageLayoutTab: PageLayoutTabManifest;
+ pageLayoutType: PageLayoutManifest['type'] | undefined;
+}): string[] => {
+ const result = normalizePageLayoutTabManifest({
+ pageLayoutTabManifest: pageLayoutTab,
+ pageLayoutType,
+ });
+
+ return result.status === 'fail' ? result.errors : [];
+};
+
+const validatePageLayoutTabs = (
+ manifest: Pick<Manifest, 'pageLayouts' | 'pageLayoutTabs'>,
+): string[] => {
+ const pageLayoutTypeByUniversalIdentifier = new Map(
+ manifest.pageLayouts.map((pageLayout) => [
+ pageLayout.universalIdentifier,
+ pageLayout.type,
+ ]),
+ );
+
+ const nestedTabErrors = manifest.pageLayouts.flatMap((pageLayout) =>
+ (pageLayout.tabs ?? []).flatMap((pageLayoutTab) =>
+ validatePageLayoutTab({
+ pageLayoutTab,
+ pageLayoutType: pageLayout.type,
+ }),
+ ),
+ );
+
+ const standaloneTabErrors = manifest.pageLayoutTabs.flatMap((pageLayoutTab) =>
+ validatePageLayoutTab({
+ pageLayoutTab,
+ pageLayoutType: isDefined(pageLayoutTab.pageLayoutUniversalIdentifier)
+ ? pageLayoutTypeByUniversalIdentifier.get(
+ pageLayoutTab.pageLayoutUniversalIdentifier,
+ )
+ : undefined,
+ }),
+ );
+
+ return [...nestedTabErrors, ...standaloneTabErrors];
+};
+
+const invalidUniversalIdentifierVersions = (
+ identifiers: string[],
+): string[] => {
+ const errors: string[] = [];
+ const seen = new Set<string>();
+
+ for (const identifier of identifiers) {
+ if (seen.has(identifier)) {
+ continue;
+ }
+ seen.add(identifier);
+
+ if (!uuidValidate(identifier)) {
+ errors.push(`Universal identifier "${identifier}" is not a valid UUID.`);
+ continue;
+ }
+
+ const version = uuidVersion(identifier);
+
+ if (!isValidUniversalIdentifier(identifier)) {
+ errors.push(
+ `Universal identifier "${identifier}" is UUID version ${version}. ` +
+ `Only UUID version ${MINIMUM_UNIVERSAL_IDENTIFIER_UUID_VERSION} or higher is allowed.`,
+ );
+ }
+ }
+
+ return errors;
+};
+
+export const manifestValidate = (manifest: Manifest) => {
+ const errors: string[] = [];
+ const warnings = [
+ ...getPageLayoutDeprecationWarnings(manifest),
+ ...getUnresolvedLabelIdentifierWarnings(manifest),
+ ];
+
+ const universalIdentifiers = findUniversalIdentifiers(manifest);
+
+ const duplicates = getDuplicateValues(
+ universalIdentifiers.map((identifier) => identifier.toLowerCase()),
+ );
+
+ if (duplicates.length > 0) {
+ errors.push(`Duplicate universal identifiers: ${duplicates.join(', ')}`);
+ }
+
+ const invalidUniversalIdentifiers =
+ invalidUniversalIdentifierVersions(universalIdentifiers);
+
+ if (invalidUniversalIdentifiers.length > 0) {
+ errors.push(
+ `Invalid universal identifiers: ${invalidUniversalIdentifiers.join(', ')}`,
+ );
+ }
+
+ const allFields: ManifestField[] = [
+ ...manifest.fields,
+ ...manifest.objects.flatMap((object) => object.fields),
+ ];
+
+ for (const field of allFields) {
+ if (
+ (field.type === FieldMetadataType.SELECT ||
+ field.type === FieldMetadataType.MULTI_SELECT ||
+ field.type === FieldMetadataType.RATING) &&
+ isDefined(field.options)
+ ) {
+ if (
+ field.options.some(({ id }) => isDefined(id) && !isNonEmptyString(id))
+ ) {
+ errors.push(
+ `Field "${field.name}" has empty option IDs. Set distinct non-empty IDs on these options.`,
+ );
+ }
+
+ const duplicateIds = getDuplicateValues(
+ field.options
+ .map((option) => option.id)
+ .filter(isDefined)
+ .map((id) => id.toLowerCase()),
+ );
+
+ if (duplicateIds.length > 0)
+ errors.push(
+ `Field "${field.name}" has duplicate option IDs: ${duplicateIds.join(', ')}. Set distinct explicit IDs on these options.`,
+ );
+ }
+ }
+
+ errors.push(...validateRelationFields(allFields));
+
+ errors.push(...validatePageLayoutTabs(manifest));
+
+ errors.push(...validateGraphWidgets(collectPageLayoutWidgets(manifest)));
+
+ errors.push(...validateTimelineActivityTypes(manifest));
+
+ return { errors, warnings, isValid: errors.length === 0 };
+};
diff --git a/packages/twenty-cli/src/app/manifest/manifest-writer.ts b/packages/twenty-cli/src/app/manifest/manifest-writer.ts
new file mode 100644
index 00000000000..bec034bda4e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/manifest-writer.ts
@@ -0,0 +1,22 @@
+import path from 'path';
+
+import { ensureDir, writeJson } from '@/app/fs-utils';
+import { type Manifest, OUTPUT_DIR } from 'twenty-shared/application';
+
+export const writeManifestToOutput = async ({
+ appPath,
+ manifest,
+ relativeOutputDir = OUTPUT_DIR,
+}: {
+ appPath: string;
+ manifest: Manifest;
+ relativeOutputDir?: string;
+}): Promise<string> => {
+ const outputDir = path.join(appPath, relativeOutputDir);
+ await ensureDir(outputDir);
+
+ const manifestPath = path.join(outputDir, 'manifest.json');
+ await writeJson(manifestPath, manifest);
+
+ return manifestPath;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/app-manifest.type.ts b/packages/twenty-cli/src/app/manifest/types/app-manifest.type.ts
new file mode 100644
index 00000000000..57a1f7f1f23
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/app-manifest.type.ts
@@ -0,0 +1,8 @@
+import { type Manifest } from 'twenty-shared/application';
+
+import { type EntityFilePaths } from '@/app/manifest/types/entity-file-paths.type';
+
+export type AppManifest = {
+ manifest: Manifest;
+ filePaths: EntityFilePaths;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/application-config.type.ts b/packages/twenty-cli/src/app/manifest/types/application-config.type.ts
new file mode 100644
index 00000000000..1ac23f4d712
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/application-config.type.ts
@@ -0,0 +1,15 @@
+import { type ApplicationManifest } from 'twenty-shared/application';
+
+export type ApplicationConfig = Omit<
+ ApplicationManifest,
+ | 'packageJsonChecksum'
+ | 'yarnLockChecksum'
+ | 'requiredServerVersionRange'
+ | 'postInstallLogicFunction'
+ | 'preInstallLogicFunction'
+ | 'settingsFrontComponent'
+ | 'defaultRoleUniversalIdentifier'
+ | 'aboutDescription'
+> & {
+ defaultRoleUniversalIdentifier?: string;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/command-menu-item-config.type.ts b/packages/twenty-cli/src/app/manifest/types/command-menu-item-config.type.ts
new file mode 100644
index 00000000000..477d8600409
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/command-menu-item-config.type.ts
@@ -0,0 +1,8 @@
+import { type CommandMenuItemManifest } from 'twenty-shared/application';
+
+export type CommandMenuItemConfig = Omit<
+ CommandMenuItemManifest,
+ 'conditionalAvailabilityExpression'
+> & {
+ conditionalAvailabilityExpression?: boolean | string;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/entity-file-paths.type.ts b/packages/twenty-cli/src/app/manifest/types/entity-file-paths.type.ts
new file mode 100644
index 00000000000..91bebd3be15
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/entity-file-paths.type.ts
@@ -0,0 +1,6 @@
+import { type ManifestEntityKey } from '@/app/source/extract-define-entity';
+
+export type EntityFilePaths = Record<
+ ManifestEntityKey | 'publicAssets',
+ string[]
+>;
diff --git a/packages/twenty-cli/src/app/manifest/types/front-component-config.type.ts b/packages/twenty-cli/src/app/manifest/types/front-component-config.type.ts
new file mode 100644
index 00000000000..a7ce6cad0bd
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/front-component-config.type.ts
@@ -0,0 +1,14 @@
+import { type FrontComponentManifest } from 'twenty-shared/application';
+
+export type FrontComponentType = { name: string };
+
+export type FrontComponentConfig = Omit<
+ FrontComponentManifest,
+ | 'sourceComponentPath'
+ | 'builtComponentPath'
+ | 'builtComponentChecksum'
+ | 'componentName'
+ | 'usesSdkClient'
+> & {
+ component: FrontComponentType;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/index-config.type.ts b/packages/twenty-cli/src/app/manifest/types/index-config.type.ts
new file mode 100644
index 00000000000..d6ce9da01bf
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/index-config.type.ts
@@ -0,0 +1,3 @@
+import { type IndexManifest } from 'twenty-shared/application';
+
+export type IndexConfig = IndexManifest;
diff --git a/packages/twenty-cli/src/app/manifest/types/install-payload.type.ts b/packages/twenty-cli/src/app/manifest/types/install-payload.type.ts
new file mode 100644
index 00000000000..19e7c50fdf2
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/install-payload.type.ts
@@ -0,0 +1,6 @@
+export type InstallPayload = {
+ previousVersion?: string;
+ newVersion: string;
+};
+
+export type InstallHandler = (payload: InstallPayload) => unknown;
diff --git a/packages/twenty-cli/src/app/manifest/types/logic-function-config.type.ts b/packages/twenty-cli/src/app/manifest/types/logic-function-config.type.ts
new file mode 100644
index 00000000000..ab51c95477e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/logic-function-config.type.ts
@@ -0,0 +1,46 @@
+import {
+ type LogicFunctionManifest,
+ type ServerRouteDispatchResult,
+ type ServerRouteTriggerSettings,
+} from 'twenty-shared/application';
+import { type LogicFunctionExecutionContext } from 'twenty-shared/logic-function';
+import { type LogicFunctionHttpResponse } from 'twenty-shared/types';
+
+export type LogicFunctionHandler<TPayload = never> = (
+ payload: TPayload,
+ context: LogicFunctionExecutionContext,
+) => unknown;
+
+// A resolver attached to `serverRouteTriggerSettings` runs in the owner workspace and is the single
+// point of authorization: the URL only carries the resolver's universalIdentifier. Returning a
+// dispatch result enqueues the target, returning a `Response` answers the caller synchronously
+// instead, for providers whose webhook URL requires a handshake reply.
+export type ServerRouteResolverResult =
+ | ServerRouteDispatchResult
+ | LogicFunctionHttpResponse;
+
+export type ServerRouteResolverHandler<TPayload = never> = (
+ payload: TPayload,
+ context: LogicFunctionExecutionContext,
+) => ServerRouteResolverResult | Promise<ServerRouteResolverResult>;
+
+type LogicFunctionConfigBase = Omit<
+ LogicFunctionManifest,
+ | 'sourceHandlerPath'
+ | 'builtHandlerPath'
+ | 'builtHandlerChecksum'
+ | 'handlerName'
+ | 'serverRouteTriggerSettings'
+>;
+
+export type LogicFunctionConfig = LogicFunctionConfigBase &
+ (
+ | {
+ serverRouteTriggerSettings?: undefined;
+ handler: LogicFunctionHandler;
+ }
+ | {
+ serverRouteTriggerSettings: ServerRouteTriggerSettings;
+ handler: ServerRouteResolverHandler;
+ }
+ );
diff --git a/packages/twenty-cli/src/app/manifest/types/object-config.type.ts b/packages/twenty-cli/src/app/manifest/types/object-config.type.ts
new file mode 100644
index 00000000000..ad5c14d7789
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/object-config.type.ts
@@ -0,0 +1,8 @@
+import { type ObjectManifest } from 'twenty-shared/application';
+
+export type ObjectConfig = Omit<
+ ObjectManifest,
+ 'labelIdentifierFieldMetadataUniversalIdentifier'
+> & {
+ labelIdentifierFieldMetadataUniversalIdentifier?: string;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/page-layout-config.type.ts b/packages/twenty-cli/src/app/manifest/types/page-layout-config.type.ts
new file mode 100644
index 00000000000..abf956f07b1
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/page-layout-config.type.ts
@@ -0,0 +1,3 @@
+import { type PageLayoutManifest } from 'twenty-shared/application';
+
+export type PageLayoutConfig = PageLayoutManifest;
diff --git a/packages/twenty-cli/src/app/manifest/types/page-layout-tab-config.type.ts b/packages/twenty-cli/src/app/manifest/types/page-layout-tab-config.type.ts
new file mode 100644
index 00000000000..7756f6ddd6e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/page-layout-tab-config.type.ts
@@ -0,0 +1,8 @@
+import { type PageLayoutTabManifest } from 'twenty-shared/application';
+
+export type PageLayoutTabConfig = Omit<
+ PageLayoutTabManifest,
+ 'pageLayoutUniversalIdentifier'
+> & {
+ pageLayoutUniversalIdentifier: string;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/post-install-logic-function-config.type.ts b/packages/twenty-cli/src/app/manifest/types/post-install-logic-function-config.type.ts
new file mode 100644
index 00000000000..5c213a7abea
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/post-install-logic-function-config.type.ts
@@ -0,0 +1,5 @@
+import { type PreInstallLogicFunctionConfig } from '@/app/manifest/types/pre-install-logic-function-config.type';
+
+export type PostInstallLogicFunctionConfig = PreInstallLogicFunctionConfig & {
+ shouldRunSynchronously?: boolean;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/pre-install-logic-function-config.type.ts b/packages/twenty-cli/src/app/manifest/types/pre-install-logic-function-config.type.ts
new file mode 100644
index 00000000000..7d3b7262c59
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/pre-install-logic-function-config.type.ts
@@ -0,0 +1,16 @@
+import type { InstallHandler } from '@/app/manifest/types/install-payload.type';
+import type { LogicFunctionConfig } from '@/app/manifest/types/logic-function-config.type';
+
+export type PreInstallLogicFunctionConfig = Omit<
+ LogicFunctionConfig,
+ | 'cronTriggerSettings'
+ | 'databaseEventTriggerSettings'
+ | 'httpRouteTriggerSettings'
+ | 'serverRouteTriggerSettings'
+ | 'toolTriggerSettings'
+ | 'workflowActionTriggerSettings'
+ | 'handler'
+> & {
+ handler: InstallHandler;
+ shouldRunOnVersionUpgrade?: boolean;
+};
diff --git a/packages/twenty-cli/src/app/manifest/types/role-config.type.ts b/packages/twenty-cli/src/app/manifest/types/role-config.type.ts
new file mode 100644
index 00000000000..ef02c7b3055
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/role-config.type.ts
@@ -0,0 +1,3 @@
+import type { RoleManifest } from 'twenty-shared/application';
+
+export type RoleConfig = RoleManifest;
diff --git a/packages/twenty-cli/src/app/manifest/types/settings-menu-item-config.type.ts b/packages/twenty-cli/src/app/manifest/types/settings-menu-item-config.type.ts
new file mode 100644
index 00000000000..90a1ad72525
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/settings-menu-item-config.type.ts
@@ -0,0 +1,3 @@
+import { type SettingsMenuItemManifest } from 'twenty-shared/application';
+
+export type SettingsMenuItemConfig = SettingsMenuItemManifest;
diff --git a/packages/twenty-cli/src/app/manifest/types/timeline-activity-type-config.type.ts b/packages/twenty-cli/src/app/manifest/types/timeline-activity-type-config.type.ts
new file mode 100644
index 00000000000..6098fb2c037
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/timeline-activity-type-config.type.ts
@@ -0,0 +1,3 @@
+import { type TimelineActivityTypeManifest } from 'twenty-shared/application';
+
+export type TimelineActivityTypeConfig = TimelineActivityTypeManifest;
diff --git a/packages/twenty-cli/src/app/manifest/types/view-config.type.ts b/packages/twenty-cli/src/app/manifest/types/view-config.type.ts
new file mode 100644
index 00000000000..15d8e220749
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/types/view-config.type.ts
@@ -0,0 +1,3 @@
+import { type ViewManifest } from 'twenty-shared/application';
+
+export type ViewConfig = ViewManifest;
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/add-missing-field-option-ids.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/add-missing-field-option-ids.spec.ts
new file mode 100644
index 00000000000..ef9a3f51c87
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/add-missing-field-option-ids.spec.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from 'vitest';
+
+import { addMissingFieldOptionIds } from '@/app/manifest/utils/add-missing-field-option-ids';
+import { type FieldManifest } from 'twenty-shared/application';
+import { FieldMetadataType } from 'twenty-shared/types';
+import { validate } from 'uuid';
+
+const buildSelectField = (
+ options: FieldManifest<FieldMetadataType.SELECT>['options'],
+): FieldManifest<FieldMetadataType.SELECT> => ({
+ universalIdentifier: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa',
+ objectUniversalIdentifier: 'bbbbbbbb-bbbb-4bbb-bbbb-bbbbbbbbbbbb',
+ name: 'status',
+ label: 'Status',
+ type: FieldMetadataType.SELECT,
+ options,
+});
+
+describe('addMissingFieldOptionIds', () => {
+ it('should add a deterministic UUID id to every option that is missing one for a SELECT field', () => {
+ const fieldManifest = buildSelectField([
+ { color: 'green', label: 'Open', value: 'OPEN', position: 1 },
+ { color: 'red', label: 'Closed', value: 'CLOSED', position: 2 },
+ ]);
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ expect(
+ addMissingFieldOptionIds(structuredClone(fieldManifest)).options,
+ ).toEqual(result.options);
+ expect(result.options).toHaveLength(2);
+ for (const option of result.options ?? []) {
+ expect(validate(option.id)).toBe(true);
+ }
+ });
+
+ it('should preserve existing ids on options that already have one', () => {
+ const existingId = 'cccccccc-cccc-4ccc-cccc-cccccccccccc';
+ const fieldManifest = buildSelectField([
+ {
+ id: existingId,
+ color: 'green',
+ label: 'Open',
+ value: 'OPEN',
+ position: 1,
+ },
+ { color: 'red', label: 'Closed', value: 'CLOSED', position: 2 },
+ ]);
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ expect(result.options?.[0].id).toBe(existingId);
+ expect(validate(result.options?.[1].id)).toBe(true);
+ expect(result.options?.[1].id).not.toBe(existingId);
+ });
+
+ it('should also process MULTI_SELECT fields', () => {
+ const fieldManifest: FieldManifest<FieldMetadataType.MULTI_SELECT> = {
+ universalIdentifier: 'dddddddd-dddd-4ddd-dddd-dddddddddddd',
+ objectUniversalIdentifier: 'eeeeeeee-eeee-4eee-eeee-eeeeeeeeeeee',
+ name: 'tags',
+ label: 'Tags',
+ type: FieldMetadataType.MULTI_SELECT,
+ options: [
+ { color: 'blue', label: 'Urgent', value: 'URGENT', position: 1 },
+ ],
+ };
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ expect(validate(result.options?.[0].id)).toBe(true);
+ });
+
+ it('should return the field manifest unchanged when type is not SELECT or MULTI_SELECT', () => {
+ const fieldManifest: FieldManifest<FieldMetadataType.TEXT> = {
+ universalIdentifier: 'ffffffff-ffff-4fff-ffff-ffffffffffff',
+ objectUniversalIdentifier: '11111111-1111-4111-1111-111111111111',
+ name: 'description',
+ label: 'Description',
+ type: FieldMetadataType.TEXT,
+ };
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ expect(result).toBe(fieldManifest);
+ });
+
+ it('should return the field manifest unchanged when options is undefined', () => {
+ const fieldManifest = buildSelectField(undefined);
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ expect(result).toBe(fieldManifest);
+ });
+
+ it('should not mutate the original field manifest or its options', () => {
+ const originalOptions = [
+ { color: 'green' as const, label: 'Open', value: 'OPEN', position: 1 },
+ { color: 'red' as const, label: 'Closed', value: 'CLOSED', position: 2 },
+ ];
+ const fieldManifest = buildSelectField([...originalOptions]);
+
+ addMissingFieldOptionIds(fieldManifest);
+
+ expect(fieldManifest.options).toEqual(originalOptions);
+ for (const option of fieldManifest.options ?? []) {
+ expect(option.id).toBeUndefined();
+ }
+ });
+
+ it('should generate distinct ids for different missing options', () => {
+ const fieldManifest = buildSelectField([
+ { color: 'green', label: 'A', value: 'A', position: 1 },
+ { color: 'red', label: 'B', value: 'B', position: 2 },
+ { color: 'blue', label: 'C', value: 'C', position: 3 },
+ ]);
+
+ const result = addMissingFieldOptionIds(fieldManifest);
+
+ const ids = result.options?.map((option) => option.id) ?? [];
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+ it('keeps explicit option identities across label edits and duplicate labels', () => {
+ const before = addMissingFieldOptionIds(
+ buildSelectField([
+ { color: 'green', label: 'Open', value: 'OPEN', position: 1 },
+ { color: 'red', label: 'Closed', value: 'CLOSED', position: 2 },
+ ]),
+ );
+ const after = addMissingFieldOptionIds(
+ buildSelectField(
+ before.options?.map((option) => ({ ...option, label: 'Status' })),
+ ),
+ );
+
+ expect(after.options?.map(({ id }) => id)).toEqual(
+ before.options?.map(({ id }) => id),
+ );
+ expect(after.options?.[0].id).not.toBe(after.options?.[1].id);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/extract-front-component-shared-dependencies.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/extract-front-component-shared-dependencies.spec.ts
new file mode 100644
index 00000000000..0a726aa63c8
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/extract-front-component-shared-dependencies.spec.ts
@@ -0,0 +1,93 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { extractFrontComponentSharedDependencies } from '@/app/manifest/utils/extract-front-component-shared-dependencies';
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_BUILT_PATH } from 'twenty-shared/application';
+
+const scratchDirs: string[] = [];
+
+const writeAppPackageJson = async (packageJson: unknown): Promise<string> => {
+ const appPath = await mkdtemp(join(tmpdir(), 'shared-dependencies-extract-'));
+
+ scratchDirs.push(appPath);
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify(packageJson),
+ 'utf-8',
+ );
+
+ return appPath;
+};
+
+describe('extractFrontComponentSharedDependencies', () => {
+ afterEach(async () => {
+ await Promise.all(
+ scratchDirs
+ .splice(0)
+ .map((dir) => rm(dir, { recursive: true, force: true })),
+ );
+ });
+
+ it('extracts and normalizes the declared dependencies', async () => {
+ const appPath = await writeAppPackageJson({
+ frontComponentSharedDependencies: ['react', 'react-dom/client'],
+ });
+
+ const { sharedDependencies, errors } =
+ await extractFrontComponentSharedDependencies(appPath);
+
+ expect(errors).toEqual([]);
+ expect(sharedDependencies).toEqual({
+ dependencies: ['react', 'react-dom/client', 'react/jsx-runtime'],
+ builtPath: FRONT_COMPONENT_SHARED_DEPENDENCIES_BUILT_PATH,
+ builtChecksum: null,
+ });
+ });
+
+ it.each([
+ ['an absent key', {}],
+ ['an empty array', { frontComponentSharedDependencies: [] }],
+ ])('returns no bundle and no error for %s', async (_label, packageJson) => {
+ const appPath = await writeAppPackageJson(packageJson);
+
+ const { sharedDependencies, errors } =
+ await extractFrontComponentSharedDependencies(appPath);
+
+ expect(errors).toEqual([]);
+ expect(sharedDependencies).toBeUndefined();
+ });
+
+ it('rejects a value that is not an array', async () => {
+ const appPath = await writeAppPackageJson({
+ frontComponentSharedDependencies: { react: '^19' },
+ });
+
+ const { sharedDependencies, errors } =
+ await extractFrontComponentSharedDependencies(appPath);
+
+ expect(sharedDependencies).toBeUndefined();
+ expect(errors[0]).toContain('must be an array of package specifiers');
+ });
+
+ it.each([
+ ['a relative path', ['./local-module']],
+ ['a Windows absolute path', ['C:\\lib']],
+ ['a Windows network path', ['\\\\server\\share']],
+ ['a reserved package', ['twenty-sdk/define']],
+ ['a duplicated dependency', ['react', 'react']],
+ ['a non-string entry', ['react', 42]],
+ ])('rejects %s', async (_label, dependencies) => {
+ const appPath = await writeAppPackageJson({
+ frontComponentSharedDependencies: dependencies,
+ });
+
+ const { sharedDependencies, errors } =
+ await extractFrontComponentSharedDependencies(appPath);
+
+ expect(sharedDependencies).toBeUndefined();
+ expect(errors).not.toEqual([]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/from-role-config-to-role-manifest.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/from-role-config-to-role-manifest.spec.ts
new file mode 100644
index 00000000000..3088ee5b6cd
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/from-role-config-to-role-manifest.spec.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from 'vitest';
+
+import { fromRoleConfigToRoleManifest } from '@/app/manifest/utils/from-role-config-to-role-manifest';
+import { type RoleConfig } from '@/app/manifest/types/role-config.type';
+import {
+ RowLevelPermissionPredicateGroupLogicalOperator,
+ RowLevelPermissionPredicateOperand,
+} from 'twenty-shared/types';
+import {
+ getFieldPermissionUniversalIdentifier,
+ getObjectPermissionUniversalIdentifier,
+} from 'twenty-shared/application';
+
+const APPLICATION_UNIVERSAL_IDENTIFIER = '5a0c6f3e-8d2b-4c1a-9e7f-3b4d5c6e7f80';
+const ROLE_UNIVERSAL_IDENTIFIER = 'c3c1dc2e-1a08-4de5-abb7-2139b3d99343';
+const OBJECT_UNIVERSAL_IDENTIFIER = '39101b39-1c16-4148-9e82-45dc271bb90d';
+const FIELD_UNIVERSAL_IDENTIFIER = '0e49f2e4-1e45-433d-bf49-79acc0b06d0e';
+const PREDICATE_UNIVERSAL_IDENTIFIER = '22222222-0000-4000-8000-000000000000';
+const GROUP_UNIVERSAL_IDENTIFIER = '11111111-0000-4000-8000-000000000000';
+const OBJECT_PERMISSION_UNIVERSAL_IDENTIFIER =
+ '33333333-0000-4000-8000-000000000000';
+const FIELD_PERMISSION_UNIVERSAL_IDENTIFIER =
+ '44444444-0000-4000-8000-000000000000';
+
+const baseConfig: RoleConfig = {
+ universalIdentifier: ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Partner',
+};
+
+const convert = (roleConfig: RoleConfig) =>
+ fromRoleConfigToRoleManifest({
+ roleConfig,
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ });
+
+describe('fromRoleConfigToRoleManifest', () => {
+ it('derives the universalIdentifier of object and field permissions that omit it', () => {
+ const manifest = convert({
+ ...baseConfig,
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ fieldUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
+ canReadFieldValue: false,
+ },
+ ],
+ });
+
+ expect(manifest.objectPermissions?.[0]?.universalIdentifier).toBe(
+ getObjectPermissionUniversalIdentifier({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ roleUniversalIdentifier: ROLE_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ }),
+ );
+ expect(manifest.fieldPermissions?.[0]?.universalIdentifier).toBe(
+ getFieldPermissionUniversalIdentifier({
+ applicationUniversalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,
+ roleUniversalIdentifier: ROLE_UNIVERSAL_IDENTIFIER,
+ fieldUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
+ }),
+ );
+ });
+
+ it('keeps the universalIdentifier an object or field permission provides', () => {
+ const manifest = convert({
+ ...baseConfig,
+ objectPermissions: [
+ {
+ universalIdentifier: OBJECT_PERMISSION_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ },
+ ],
+ fieldPermissions: [
+ {
+ universalIdentifier: FIELD_PERMISSION_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ fieldUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
+ },
+ ],
+ });
+
+ expect(manifest.objectPermissions?.[0]?.universalIdentifier).toBe(
+ OBJECT_PERMISSION_UNIVERSAL_IDENTIFIER,
+ );
+ expect(manifest.fieldPermissions?.[0]?.universalIdentifier).toBe(
+ FIELD_PERMISSION_UNIVERSAL_IDENTIFIER,
+ );
+ });
+
+ it('passes predicates through with their explicit universalIdentifier', () => {
+ const config: RoleConfig = {
+ ...baseConfig,
+ rowLevelPermissionPredicates: [
+ {
+ universalIdentifier: PREDICATE_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ fieldUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,
+ operand: RowLevelPermissionPredicateOperand.IS,
+ },
+ ],
+ };
+
+ const manifest = convert(config);
+ const predicate = manifest.rowLevelPermissionPredicates?.[0];
+
+ expect(predicate?.universalIdentifier).toBe(PREDICATE_UNIVERSAL_IDENTIFIER);
+ expect(predicate?.objectUniversalIdentifier).toBe(
+ OBJECT_UNIVERSAL_IDENTIFIER,
+ );
+ expect(predicate?.fieldUniversalIdentifier).toBe(
+ FIELD_UNIVERSAL_IDENTIFIER,
+ );
+ expect(predicate?.operand).toBe(RowLevelPermissionPredicateOperand.IS);
+ });
+
+ it('passes predicate groups through with their explicit universalIdentifier', () => {
+ const config: RoleConfig = {
+ ...baseConfig,
+ rowLevelPermissionPredicateGroups: [
+ {
+ universalIdentifier: GROUP_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_UNIVERSAL_IDENTIFIER,
+ logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator.OR,
+ },
+ ],
+ };
+
+ const manifest = convert(config);
+
+ expect(manifest.rowLevelPermissionPredicateGroups).toHaveLength(1);
+ expect(
+ manifest.rowLevelPermissionPredicateGroups?.[0]?.universalIdentifier,
+ ).toBe(GROUP_UNIVERSAL_IDENTIFIER);
+ });
+
+ it('defaults predicate collections to empty arrays', () => {
+ const manifest = convert(baseConfig);
+
+ expect(manifest.rowLevelPermissionPredicates).toEqual([]);
+ expect(manifest.rowLevelPermissionPredicateGroups).toEqual([]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/get-default-fields-in-object-fields.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/get-default-fields-in-object-fields.spec.ts
new file mode 100644
index 00000000000..0fef6b1ba0a
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/get-default-fields-in-object-fields.spec.ts
@@ -0,0 +1,137 @@
+import { isEngineDerivedLabelIdentifier } from '../../../../../../twenty-sdk/src/sdk/define/objects/is-engine-derived-label-identifier';
+import { getDefaultFieldsInObjectFields } from '@/app/manifest/utils/get-default-fields-in-object-fields';
+import { type ObjectConfig } from '@/app/manifest/types/object-config.type';
+import { getFieldUniversalIdentifier } from 'twenty-shared/application';
+import { FieldMetadataType } from 'twenty-shared/types';
+import { describe, expect, it } from 'vitest';
+
+const APP_UID = '11111111-1111-4111-8111-111111111111';
+const OBJECT_UID = '22222222-2222-4222-8222-222222222222';
+const RELATION_FIELD_UID = '33333333-3333-4333-8333-333333333333';
+
+const buildObjectConfig = (overrides: Partial<ObjectConfig>): ObjectConfig =>
+ ({
+ universalIdentifier: OBJECT_UID,
+ nameSingular: 'petCareAgreement',
+ namePlural: 'petCareAgreements',
+ labelSingular: 'Pet care agreement',
+ labelPlural: 'Pet care agreements',
+ fields: [
+ {
+ universalIdentifier: RELATION_FIELD_UID,
+ name: 'pet',
+ label: 'Pet',
+ type: FieldMetadataType.RELATION,
+ },
+ ],
+ ...overrides,
+ }) as unknown as ObjectConfig;
+
+describe('getDefaultFieldsInObjectFields', () => {
+ it.each([
+ 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ 'AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA',
+ ])(
+ 'matches SDK default-field inference for label reference %s',
+ (identifier) => {
+ const objectConfig = buildObjectConfig({
+ fields: [
+ {
+ universalIdentifier: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
+ name: 'title',
+ label: 'Title',
+ type: FieldMetadataType.TEXT,
+ },
+ ],
+ labelIdentifierFieldMetadataUniversalIdentifier: identifier,
+ });
+ const input = { objectConfig, applicationUniversalIdentifier: APP_UID };
+ expect(
+ getDefaultFieldsInObjectFields(input).objectFields.map(
+ ({ name }) => name,
+ ),
+ ).toEqual(
+ isEngineDerivedLabelIdentifier({
+ fields: objectConfig.fields ?? [],
+ labelIdentifierFieldMetadataUniversalIdentifier: identifier,
+ })
+ ? ['title']
+ : ['title', 'name'],
+ );
+ },
+ );
+
+ it('adds the default name field when fields is omitted', () => {
+ const { objectFields } = getDefaultFieldsInObjectFields({
+ objectConfig: buildObjectConfig({ fields: undefined }),
+ applicationUniversalIdentifier: APP_UID,
+ });
+
+ expect(objectFields.map(({ name }) => name)).toEqual(['name']);
+ });
+
+ it('should append a name field when the object declares none', () => {
+ const { objectFields } = getDefaultFieldsInObjectFields({
+ objectConfig: buildObjectConfig({}),
+ applicationUniversalIdentifier: APP_UID,
+ });
+
+ const nameField = objectFields.find((field) => field.name === 'name');
+
+ expect(nameField?.universalIdentifier).toBe(
+ getFieldUniversalIdentifier({
+ applicationUniversalIdentifier: APP_UID,
+ objectUniversalIdentifier: OBJECT_UID,
+ name: 'name',
+ }),
+ );
+ });
+
+ it('should keep the name field the object declares itself', () => {
+ const { objectFields } = getDefaultFieldsInObjectFields({
+ objectConfig: buildObjectConfig({
+ fields: [
+ {
+ universalIdentifier: 'a-hand-written-identifier',
+ name: 'name',
+ label: 'Name',
+ type: FieldMetadataType.TEXT,
+ },
+ ],
+ } as unknown as Partial<ObjectConfig>),
+ applicationUniversalIdentifier: APP_UID,
+ });
+
+ expect(objectFields).toHaveLength(1);
+ expect(objectFields[0].universalIdentifier).toBe(
+ 'a-hand-written-identifier',
+ );
+ });
+
+ it('should not append a name field when the label identifier names an engine-derived field', () => {
+ const { objectFields } = getDefaultFieldsInObjectFields({
+ objectConfig: buildObjectConfig({
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ getFieldUniversalIdentifier({
+ applicationUniversalIdentifier: APP_UID,
+ objectUniversalIdentifier: OBJECT_UID,
+ name: 'id',
+ }),
+ }),
+ applicationUniversalIdentifier: APP_UID,
+ });
+
+ expect(objectFields.map((field) => field.name)).toEqual(['pet']);
+ });
+
+ it('should still append a name field when the label identifier names one of its own fields', () => {
+ const { objectFields } = getDefaultFieldsInObjectFields({
+ objectConfig: buildObjectConfig({
+ labelIdentifierFieldMetadataUniversalIdentifier: RELATION_FIELD_UID,
+ }),
+ applicationUniversalIdentifier: APP_UID,
+ });
+
+ expect(objectFields.map((field) => field.name)).toEqual(['pet', 'name']);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts
new file mode 100644
index 00000000000..be2c98688e7
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-agent-roles-within-application-role.spec.ts
@@ -0,0 +1,219 @@
+import { describe, expect, it } from 'vitest';
+
+import { validateAgentRolesWithinApplicationRole } from '@/app/manifest/utils/validate-agent-roles-within-application-role';
+import {
+ type AgentManifest,
+ type RoleManifest,
+} from 'twenty-shared/application';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+
+const APPLICATION_ROLE_UNIVERSAL_IDENTIFIER = 'application-role';
+const AGENT_ROLE_UNIVERSAL_IDENTIFIER = 'agent-role';
+const CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER = 'custom-object';
+const PERSON_UNIVERSAL_IDENTIFIER = STANDARD_OBJECTS.person.universalIdentifier;
+
+const buildRole = (overrides: Partial<RoleManifest> = {}): RoleManifest => ({
+ universalIdentifier: AGENT_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Agent role',
+ ...overrides,
+});
+
+const applicationRole = buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+});
+
+const buildAgent = (overrides: Partial<AgentManifest> = {}): AgentManifest => ({
+ universalIdentifier: 'agent',
+ name: 'assistant',
+ label: 'Assistant',
+ prompt: 'Help.',
+ roleUniversalIdentifier: AGENT_ROLE_UNIVERSAL_IDENTIFIER,
+ ...overrides,
+});
+
+const customObject = {
+ universalIdentifier: CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER,
+ nameSingular: 'ticket',
+};
+
+describe('validateAgentRolesWithinApplicationRole', () => {
+ it('accepts an agent role the application role covers', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ applicationRole,
+ buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('ignores agents without a role and agents on the application role', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [
+ buildAgent({ roleUniversalIdentifier: undefined }),
+ buildAgent({
+ roleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ }),
+ ],
+ roles: [applicationRole],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('reports every grant an agent role has beyond the application role', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent(), buildAgent({ name: 'second-assistant' })],
+ roles: [
+ applicationRole,
+ buildRole({
+ objectPermissions: [
+ {
+ objectUniversalIdentifier: PERSON_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ canUpdateObjectRecords: true,
+ },
+ {
+ objectUniversalIdentifier: CUSTOM_OBJECT_UNIVERSAL_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.AI,
+ SystemPermissionFlag.WORKFLOWS,
+ ],
+ }),
+ ],
+ objects: [customObject],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Role "Agent role" used by agent "assistant", "second-assistant" grants more than the application role "Application role": permission flag WORKFLOWS, update person records, read ticket records. The application role must cover every permission an agent role grants.',
+ ]);
+ });
+
+ it('treats a custom permission flag without a permission type as a tool flag, like the server does', () => {
+ const customToolFlagUniversalIdentifier = 'custom-tool-flag';
+
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ canAccessAllTools: true,
+ }),
+ buildRole({
+ permissionFlagUniversalIdentifiers: [
+ customToolFlagUniversalIdentifier,
+ ],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [
+ {
+ universalIdentifier: customToolFlagUniversalIdentifier,
+ key: 'CUSTOM_TOOL',
+ },
+ ],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('reports a custom settings flag that access to all tools does not cover', () => {
+ const customSettingsFlagUniversalIdentifier = 'custom-settings-flag';
+
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent()],
+ roles: [
+ buildRole({
+ universalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ label: 'Application role',
+ canAccessAllTools: true,
+ }),
+ buildRole({
+ permissionFlagUniversalIdentifiers: [
+ customSettingsFlagUniversalIdentifier,
+ ],
+ }),
+ ],
+ objects: [],
+ permissionFlags: [
+ {
+ universalIdentifier: customSettingsFlagUniversalIdentifier,
+ key: 'CUSTOM_SETTINGS',
+ permissionType: 'settings',
+ },
+ ],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Role "Agent role" used by agent "assistant" grants more than the application role "Application role": permission flag CUSTOM_SETTINGS. The application role must cover every permission an agent role grants.',
+ ]);
+ });
+
+ it('reports an agent role that is not defined by the application', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [buildAgent({ roleUniversalIdentifier: 'missing-role' })],
+ roles: [applicationRole],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Agent "assistant" references role "missing-role", which is not defined by this application.',
+ ]);
+ });
+
+ it('reports a missing application role and still checks agent role references', () => {
+ const errors = validateAgentRolesWithinApplicationRole({
+ agents: [
+ buildAgent(),
+ buildAgent({
+ name: 'lost-assistant',
+ roleUniversalIdentifier: 'missing-role',
+ }),
+ ],
+ roles: [buildRole({ canReadAllObjectRecords: true })],
+ objects: [],
+ permissionFlags: [],
+ defaultRoleUniversalIdentifier: APPLICATION_ROLE_UNIVERSAL_IDENTIFIER,
+ });
+
+ expect(errors).toEqual([
+ 'Application default role "application-role" is not defined by this application.',
+ 'Agent "lost-assistant" references role "missing-role", which is not defined by this application.',
+ ]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-conditional-availability-usage.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-conditional-availability-usage.spec.ts
new file mode 100644
index 00000000000..6423335f211
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-conditional-availability-usage.spec.ts
@@ -0,0 +1,279 @@
+import { CONDITIONAL_AVAILABILITY_VARIABLE_NAMES as SDK_VARIABLE_NAMES } from '../../../../../../twenty-sdk/src/sdk/define/conditional-availability/conditional-availability-variable-names';
+import { CONDITIONAL_AVAILABILITY_VARIABLE_NAMES } from '@/app/manifest/utils/conditional-availability-variable-names';
+import { describe, expect, it } from 'vitest';
+
+import { validateConditionalAvailabilityUsage } from '@/app/manifest/utils/validate-conditional-availability-usage';
+
+const validate = (
+ source: string,
+ filename = 'src/example.front-component.tsx',
+) => validateConditionalAvailabilityUsage(source, filename);
+
+describe('validateConditionalAvailabilityUsage', () => {
+ it('recognizes every placeholder exported by the SDK', () => {
+ expect(CONDITIONAL_AVAILABILITY_VARIABLE_NAMES).toEqual(SDK_VARIABLE_NAMES);
+ });
+ it.each([
+ "import { objectMetadataItem } from 'twenty-sdk/define'; export const Component = () => null;",
+ "import { objectMetadataItem } from 'twenty-sdk/define'; export type Metadata = typeof objectMetadataItem;",
+ "import { objectMetadataItem as item } from 'twenty-sdk/define'; export const read = (item: { name: string }) => item.name;",
+ "import * as sdk from 'twenty-sdk/define'; export const read = (sdk: { objectMetadataItem: string }) => sdk.objectMetadataItem;",
+ ])('allows unused or shadowed placeholders: %s', (source) => {
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('rejects a runtime shorthand reference to an aliased placeholder', () => {
+ expect(
+ validate(
+ "import { objectMetadataItem as item } from 'twenty-sdk/define'; export const value = { item };",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it.each(['src\\example.ts', 'C:\\app\\src\\example.ts'])(
+ 'rejects runtime placeholders in Windows paths: %s',
+ (filename) => {
+ expect(
+ validate(
+ "import { objectMetadataItem } from 'twenty-sdk/define'; export const value = objectMetadataItem.nameSingular;",
+ filename,
+ ),
+ ).toHaveLength(1);
+ },
+ );
+
+ describe('valid usage', () => {
+ it('should allow a variable inside a bare conditionalAvailabilityExpression', () => {
+ const source = `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ export default defineCommandMenuItem({
+ universalIdentifier: 'x',
+ label: 'X',
+ frontComponentUniversalIdentifier: 'y',
+ conditionalAvailabilityExpression:
+ objectMetadataItem.nameSingular === 'pullRequest',
+ });
+ `;
+
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('should allow a variable inside a nested command.conditionalAvailabilityExpression', () => {
+ const source = `
+ import { defineFrontComponent } from 'twenty-sdk/define';
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ export default defineFrontComponent({
+ universalIdentifier: 'x',
+ component: () => null,
+ command: {
+ universalIdentifier: 'z',
+ label: 'Z',
+ conditionalAvailabilityExpression:
+ objectMetadataItem.nameSingular === 'issue',
+ },
+ });
+ `;
+
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('should allow operators inside the expression', () => {
+ const source = `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { objectPermissions, everyEquals } from 'twenty-sdk/define';
+
+ export default defineCommandMenuItem({
+ conditionalAvailabilityExpression: everyEquals(
+ objectPermissions,
+ 'canUpdateObjectRecords',
+ true,
+ ),
+ });
+ `;
+
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('should not flag same-named helpers imported from twenty-shared/utils', () => {
+ const source = `
+ import { isDefined } from 'twenty-shared/utils';
+
+ export const useThing = (value: unknown) => {
+ if (isDefined(value)) {
+ return value;
+ }
+
+ return null;
+ };
+ `;
+
+ expect(validate(source, 'src/use-thing.ts')).toEqual([]);
+ });
+
+ it('should not flag Array.prototype.includes property access', () => {
+ const source = `
+ import { includes } from 'twenty-sdk/define';
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+
+ const items: string[] = [];
+ export const hasItem = items.includes('a');
+
+ export default defineCommandMenuItem({
+ conditionalAvailabilityExpression: includes(items, 'a'),
+ });
+ `;
+
+ expect(validate(source, 'src/has-item.ts')).toEqual([]);
+ });
+
+ it('should trust files that define an expression (runtime placeholder is the backstop for in-file misuse)', () => {
+ const source = `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { numberOfSelectedRecords } from 'twenty-sdk/define';
+
+ export default defineCommandMenuItem({
+ label: numberOfSelectedRecords,
+ conditionalAvailabilityExpression: numberOfSelectedRecords >= 2,
+ });
+ `;
+
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('should trust an expression declared with a string-literal property key', () => {
+ const source = `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ export default defineCommandMenuItem({
+ 'conditionalAvailabilityExpression':
+ objectMetadataItem.nameSingular === 'pullRequest',
+ });
+ `;
+
+ expect(validate(source)).toEqual([]);
+ });
+
+ it('should not flag a type-only import declaration', () => {
+ const source = `
+ import type { objectMetadataItem } from 'twenty-sdk/define';
+
+ export type Thing = typeof objectMetadataItem;
+ `;
+
+ expect(validate(source, 'src/thing.ts')).toEqual([]);
+ });
+
+ it('should not flag an inline type-only import specifier', () => {
+ const source = `
+ import { type objectMetadataItem } from 'twenty-sdk/define';
+
+ export type Thing = typeof objectMetadataItem;
+ `;
+
+ expect(validate(source, 'src/thing.ts')).toEqual([]);
+ });
+ });
+
+ describe('invalid usage', () => {
+ it('should flag a variable used in a component body', () => {
+ const source = `
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ export const Component = () => {
+ const name = objectMetadataItem.nameSingular;
+ return name;
+ };
+ `;
+
+ const errors = validate(source);
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('objectMetadataItem');
+ expect(errors[0]).toContain('conditionalAvailabilityExpression');
+ });
+
+ it('should flag a variable imported in a file with no expression', () => {
+ const source = `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { numberOfSelectedRecords } from 'twenty-sdk/define';
+
+ export default defineCommandMenuItem({
+ label: numberOfSelectedRecords,
+ });
+ `;
+
+ const errors = validate(source);
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('numberOfSelectedRecords');
+ });
+
+ it('should flag an operator called at runtime', () => {
+ const source = `
+ import { isDefined } from 'twenty-sdk/define';
+
+ export const check = (value: unknown) => isDefined(value);
+ `;
+
+ const errors = validate(source, 'src/check.ts');
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('isDefined');
+ });
+
+ it('should flag a variable imported from the twenty-sdk root entry', () => {
+ const source = `
+ import { objectMetadataItem } from 'twenty-sdk';
+
+ export const label = objectMetadataItem.labelSingular;
+ `;
+
+ expect(validate(source, 'src/label.ts')).toHaveLength(1);
+ });
+
+ it('should flag misuse when conditionalAvailabilityExpression appears only in a comment', () => {
+ const source = `
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ // TODO: move this into a conditionalAvailabilityExpression later
+ export const Component = () => objectMetadataItem.nameSingular;
+ `;
+
+ const errors = validate(source);
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('objectMetadataItem');
+ });
+
+ it('should flag misuse when conditionalAvailabilityExpression appears only in a string literal', () => {
+ const source = `
+ import { objectMetadataItem } from 'twenty-sdk/define';
+
+ export const doc = 'conditionalAvailabilityExpression';
+ export const Component = () => objectMetadataItem.nameSingular;
+ `;
+
+ const errors = validate(source);
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('objectMetadataItem');
+ });
+
+ it('should flag namespace-import runtime use with no expression', () => {
+ const source = `
+ import * as sdk from 'twenty-sdk/define';
+
+ export const label = sdk.objectMetadataItem.labelSingular;
+ `;
+
+ const errors = validate(source, 'src/label.ts');
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('objectMetadataItem');
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-package-json-dependencies.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-package-json-dependencies.spec.ts
new file mode 100644
index 00000000000..8c248603143
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-package-json-dependencies.spec.ts
@@ -0,0 +1,118 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { validatePackageJsonDependencies } from '@/app/manifest/utils/validate-package-json-dependencies';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const writeTempPackageJson = async (
+ packageJson: Record<string, unknown> | null,
+): Promise<string> => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-sdk-deps-'));
+
+ if (packageJson !== null) {
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify(packageJson, null, 2),
+ );
+ }
+
+ return appPath;
+};
+
+describe('validatePackageJsonDependencies', () => {
+ let appPath: string;
+
+ afterEach(async () => {
+ if (appPath) {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ });
+
+ it('warns about production SDK dependencies in optionalDependencies', async () => {
+ appPath = await writeTempPackageJson({
+ optionalDependencies: {
+ 'twenty-sdk': '^2.8.0',
+ 'twenty-client-sdk': '^2.8.0',
+ },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toHaveLength(2);
+ expect(
+ warnings.every((warning) => warning.includes('"optionalDependencies"')),
+ ).toBe(true);
+ });
+
+ it('should warn when twenty-sdk is listed under dependencies', async () => {
+ appPath = await writeTempPackageJson({
+ dependencies: { 'twenty-sdk': '^2.8.0' },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('twenty-sdk');
+ expect(warnings[0]).toContain('devDependencies');
+ });
+
+ it('should warn when twenty-client-sdk is listed under dependencies', async () => {
+ appPath = await writeTempPackageJson({
+ dependencies: { 'twenty-client-sdk': '^2.8.0' },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('twenty-client-sdk');
+ expect(warnings[0]).toContain('devDependencies');
+ });
+
+ it('should warn for both SDK packages when both are listed under dependencies', async () => {
+ appPath = await writeTempPackageJson({
+ dependencies: { 'twenty-sdk': '^2.8.0', 'twenty-client-sdk': '^2.8.0' },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toHaveLength(2);
+ expect(warnings.some((warning) => warning.includes('twenty-sdk'))).toBe(
+ true,
+ );
+ expect(
+ warnings.some((warning) => warning.includes('twenty-client-sdk')),
+ ).toBe(true);
+ });
+
+ it('should not warn when both SDK packages are listed under devDependencies', async () => {
+ appPath = await writeTempPackageJson({
+ devDependencies: {
+ 'twenty-sdk': '^2.8.0',
+ 'twenty-client-sdk': '^2.8.0',
+ },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toEqual([]);
+ });
+
+ it('should not warn when the SDK packages are absent from dependencies', async () => {
+ appPath = await writeTempPackageJson({
+ dependencies: { 'some-other-package': '^1.0.0' },
+ });
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toEqual([]);
+ });
+
+ it('should not warn when package.json is missing', async () => {
+ appPath = await writeTempPackageJson(null);
+
+ const warnings = await validatePackageJsonDependencies(appPath);
+
+ expect(warnings).toEqual([]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-view-filter-operands.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-view-filter-operands.spec.ts
new file mode 100644
index 00000000000..3e3a222e066
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-view-filter-operands.spec.ts
@@ -0,0 +1,316 @@
+import { describe, expect, it } from 'vitest';
+
+import { validateViewFilterOperands } from '@/app/manifest/utils/validate-view-filter-operands';
+import {
+ type FieldManifest,
+ type ObjectFieldManifest,
+ type ObjectManifest,
+ type ViewManifest,
+} from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ ViewFilterOperand,
+ ViewType,
+} from 'twenty-shared/types';
+
+const buildField = <T extends FieldMetadataType>({
+ universalIdentifier,
+ type,
+ name = 'field',
+ label = 'Field',
+}: {
+ universalIdentifier: string;
+ type: T;
+ name?: string;
+ label?: string;
+}): FieldManifest<T> =>
+ ({
+ universalIdentifier,
+ objectUniversalIdentifier: 'object-uid',
+ name,
+ label,
+ type,
+ }) as FieldManifest<T>;
+
+const buildRelationField = ({
+ universalIdentifier,
+ relationTargetFieldMetadataUniversalIdentifier,
+ name = 'relation',
+ label = 'Relation',
+}: {
+ universalIdentifier: string;
+ relationTargetFieldMetadataUniversalIdentifier: string;
+ name?: string;
+ label?: string;
+}): FieldManifest<FieldMetadataType.RELATION> =>
+ ({
+ universalIdentifier,
+ objectUniversalIdentifier: 'object-uid',
+ name,
+ label,
+ type: FieldMetadataType.RELATION,
+ relationTargetFieldMetadataUniversalIdentifier,
+ relationTargetObjectMetadataUniversalIdentifier: 'target-object-uid',
+ universalSettings: {},
+ }) as FieldManifest<FieldMetadataType.RELATION>;
+
+const buildView = (filters: ViewManifest['filters']): ViewManifest => ({
+ universalIdentifier: 'view-uid',
+ name: 'View',
+ objectUniversalIdentifier: 'object-uid',
+ type: ViewType.TABLE,
+ filters,
+});
+
+const buildObject = (fields: ObjectFieldManifest[]): ObjectManifest =>
+ ({
+ universalIdentifier: 'object-uid',
+ nameSingular: 'company',
+ namePlural: 'companies',
+ labelSingular: 'Company',
+ labelPlural: 'Companies',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ fields[0]?.universalIdentifier ?? '',
+ fields,
+ }) as ObjectManifest;
+
+describe('validateViewFilterOperands', () => {
+ it('should return no errors when operand is valid for the field type', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ operand: ViewFilterOperand.CONTAINS,
+ value: 'acme',
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [
+ buildField({
+ universalIdentifier: 'field-uid',
+ type: FieldMetadataType.TEXT,
+ name: 'company',
+ }),
+ ],
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('should return an error when operand is invalid for the field type', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ operand: ViewFilterOperand.CONTAINS,
+ value: '5',
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [
+ buildField({
+ universalIdentifier: 'field-uid',
+ type: FieldMetadataType.NUMBER,
+ name: 'rating',
+ }),
+ ],
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('CONTAINS');
+ expect(errors[0]).toContain('rating');
+ expect(errors[0]).toContain('NUMBER');
+ });
+
+ it('should resolve relation fields against their target field type', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'relation-field-uid',
+ operand: ViewFilterOperand.IS,
+ value: ['target-record-uid'],
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [
+ buildRelationField({
+ universalIdentifier: 'relation-field-uid',
+ relationTargetFieldMetadataUniversalIdentifier: 'target-field-uid',
+ name: 'company',
+ }),
+ buildField({
+ universalIdentifier: 'target-field-uid',
+ type: FieldMetadataType.UUID,
+ name: 'id',
+ }),
+ ],
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('should fallback to RELATION operands when relation target field is missing', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'relation-field-uid',
+ operand: ViewFilterOperand.IS,
+ value: ['target-record-uid'],
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [
+ buildRelationField({
+ universalIdentifier: 'relation-field-uid',
+ relationTargetFieldMetadataUniversalIdentifier: 'missing-target-uid',
+ name: 'company',
+ }),
+ ],
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('should look up fields nested under objects', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ operand: ViewFilterOperand.GREATER_THAN_OR_EQUAL,
+ value: '5',
+ },
+ ]),
+ ],
+ objects: [
+ buildObject([
+ buildField({
+ universalIdentifier: 'field-uid',
+ type: FieldMetadataType.TEXT,
+ name: 'company',
+ }),
+ ]),
+ ],
+ fields: [],
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('GREATER_THAN_OR_EQUAL');
+ expect(errors[0]).toContain('TEXT');
+ });
+
+ it('should skip filters that reference unknown fields', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'unknown-field-uid',
+ operand: ViewFilterOperand.CONTAINS,
+ value: 'acme',
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [],
+ });
+
+ expect(errors).toEqual([]);
+ });
+
+ it('should respect CURRENCY subFieldName when checking operands', () => {
+ const errors = validateViewFilterOperands({
+ views: [
+ buildView([
+ {
+ universalIdentifier: 'filter-uid',
+ fieldMetadataUniversalIdentifier: 'amount-uid',
+ operand: ViewFilterOperand.CONTAINS,
+ value: 'USD',
+ subFieldName: 'currencyCode',
+ },
+ ]),
+ ],
+ objects: [],
+ fields: [
+ buildField({
+ universalIdentifier: 'amount-uid',
+ type: FieldMetadataType.CURRENCY,
+ name: 'amount',
+ }),
+ ],
+ });
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('CONTAINS');
+ expect(errors[0]).toContain('CURRENCY');
+ });
+
+ it('should return an empty array when no views are defined', () => {
+ expect(
+ validateViewFilterOperands({ views: [], objects: [], fields: [] }),
+ ).toEqual([]);
+ });
+ it.each([FieldMetadataType.RELATION, FieldMetadataType.MORPH_RELATION])(
+ 'uses the selected target field for %s filters',
+ (type) => {
+ const relation = {
+ ...buildRelationField({
+ universalIdentifier: 'relation',
+ relationTargetFieldMetadataUniversalIdentifier: 'paired-field',
+ }),
+ type,
+ } as FieldManifest;
+ const filter = {
+ universalIdentifier: 'filter',
+ fieldMetadataUniversalIdentifier: 'relation',
+ relationTargetFieldMetadataUniversalIdentifier: 'target-name',
+ operand: ViewFilterOperand.CONTAINS,
+ value: 'Acme',
+ };
+ const fields = [
+ relation,
+ buildField({
+ universalIdentifier: 'paired-field',
+ type: FieldMetadataType.NUMBER,
+ }),
+ buildField({
+ universalIdentifier: 'target-name',
+ type: FieldMetadataType.TEXT,
+ }),
+ ];
+
+ expect(
+ validateViewFilterOperands({
+ views: [buildView([filter])],
+ objects: [],
+ fields,
+ }),
+ ).toEqual([]);
+ expect(
+ validateViewFilterOperands({
+ views: [
+ buildView([
+ { ...filter, operand: ViewFilterOperand.GREATER_THAN_OR_EQUAL },
+ ]),
+ ],
+ objects: [],
+ fields,
+ }),
+ ).toHaveLength(1);
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-yarn-lock.spec.ts b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-yarn-lock.spec.ts
new file mode 100644
index 00000000000..7ed46c8373c
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/__tests__/validate-yarn-lock.spec.ts
@@ -0,0 +1,50 @@
+import {
+ validateYarnLock,
+ validateYarnLockFile,
+} from '@/app/manifest/utils/validate-yarn-lock';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+describe('validateYarnLock', () => {
+ let appPath: string;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'validate-yarn-lock-'));
+ });
+
+ afterEach(async () => {
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('should accept a project without a lockfile', async () => {
+ expect(await validateYarnLock(appPath)).toEqual([]);
+ });
+
+ it('should accept a lockfile with content', async () => {
+ await writeFile(join(appPath, 'yarn.lock'), '__metadata:\n version: 8\n');
+
+ expect(await validateYarnLock(appPath)).toEqual([]);
+ });
+
+ it('should check the file it is given rather than the project lockfile', async () => {
+ await writeFile(join(appPath, 'yarn.lock'), '__metadata:\n version: 8\n');
+ await writeFile(join(appPath, 'copy.lock'), '');
+
+ expect(await validateYarnLock(appPath)).toEqual([]);
+ expect(await validateYarnLockFile(join(appPath, 'copy.lock'))).toHaveLength(
+ 1,
+ );
+ });
+
+ it('should refuse an empty lockfile and say how to regenerate it', async () => {
+ await writeFile(join(appPath, 'yarn.lock'), '');
+
+ const errors = await validateYarnLock(appPath);
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toMatch(/^yarn\.lock is empty\./);
+ expect(errors[0]).toContain('yarn install');
+ });
+});
diff --git a/packages/twenty-cli/src/app/manifest/utils/add-missing-field-option-ids.ts b/packages/twenty-cli/src/app/manifest/utils/add-missing-field-option-ids.ts
new file mode 100644
index 00000000000..a9f42a2c58d
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/add-missing-field-option-ids.ts
@@ -0,0 +1,38 @@
+import type {
+ FieldManifest,
+ ObjectFieldManifest,
+} from 'twenty-shared/application';
+import { FieldMetadataType } from 'twenty-shared/types';
+import { v5 } from 'uuid';
+
+const OPTION_ID_NAMESPACE = 'a80ff791-b940-4c47-a522-2bb478515415';
+
+export const addMissingFieldOptionIds = <
+ TEntity extends FieldManifest | ObjectFieldManifest,
+>(
+ fieldManifest: TEntity,
+): TEntity => {
+ if (
+ fieldManifest.type !== FieldMetadataType.SELECT &&
+ fieldManifest.type !== FieldMetadataType.MULTI_SELECT
+ ) {
+ return fieldManifest;
+ }
+
+ if (fieldManifest.options === undefined || fieldManifest.options === null) {
+ return fieldManifest;
+ }
+
+ return {
+ ...fieldManifest,
+ options: fieldManifest.options.map((option) => ({
+ ...option,
+ id:
+ option.id ??
+ v5(
+ `${option.label}-${fieldManifest.universalIdentifier}`,
+ OPTION_ID_NAMESPACE,
+ ),
+ })),
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/conditional-availability-variable-names.ts b/packages/twenty-cli/src/app/manifest/utils/conditional-availability-variable-names.ts
new file mode 100644
index 00000000000..f4cf61ab8cb
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/conditional-availability-variable-names.ts
@@ -0,0 +1,33 @@
+export const CONDITIONAL_AVAILABILITY_VARIABLE_NAMES = [
+ 'pageType',
+ 'isInSidePanel',
+ 'isDashboardPageLayoutInEditMode',
+ 'isLayoutCustomizationModeEnabled',
+ 'favoriteRecordIds',
+ 'isSelectAll',
+ 'hasAnySoftDeleteFilterOnView',
+ 'numberOfSelectedRecords',
+ 'objectPermissions',
+ 'selectedRecords',
+ 'featureFlags',
+ 'targetObjectReadPermissions',
+ 'targetObjectWritePermissions',
+ 'canImpersonate',
+ 'canAccessFullAdminPanel',
+ 'objectMetadataItem',
+ 'objectMetadataLabel',
+ 'isDefined',
+ 'isNonEmptyString',
+ 'includes',
+ 'every',
+ 'everyDefined',
+ 'everyEquals',
+ 'some',
+ 'someDefined',
+ 'someEquals',
+ 'none',
+ 'noneDefined',
+ 'noneEquals',
+ 'someNonEmptyString',
+ 'includesEvery',
+] as const;
diff --git a/packages/twenty-cli/src/app/manifest/utils/extract-front-component-shared-dependencies.ts b/packages/twenty-cli/src/app/manifest/utils/extract-front-component-shared-dependencies.ts
new file mode 100644
index 00000000000..2a5a005bbed
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/extract-front-component-shared-dependencies.ts
@@ -0,0 +1,117 @@
+import { normalizeFrontComponentSharedDependencies } from '@/app/manifest/utils/normalize-front-component-shared-dependencies';
+import { pathExists, readJson } from '@/app/fs-utils';
+import { isNonEmptyArray, isNonEmptyString } from '@sniptt/guards';
+import path from 'path';
+import {
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_BUILT_PATH,
+ type FrontComponentSharedDependenciesManifest,
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,
+} from 'twenty-shared/application';
+
+const RESERVED_DEPENDENCY_PREFIXES = ['twenty-client-sdk', 'twenty-sdk'];
+
+type PackageJsonWithSharedDependencies = {
+ frontComponentSharedDependencies?: unknown;
+};
+
+const getSharedDependenciesErrors = (dependencies: string[]): string[] => {
+ const errors: string[] = [];
+ const seenDependencies = new Set<string>();
+
+ for (const dependency of dependencies) {
+ if (!isNonEmptyString(dependency)) {
+ errors.push(
+ '"frontComponentSharedDependencies" entries in package.json must be non-empty strings',
+ );
+ continue;
+ }
+
+ if (
+ dependency.startsWith('.') ||
+ path.posix.isAbsolute(dependency) ||
+ path.win32.isAbsolute(dependency)
+ ) {
+ errors.push(
+ `Shared dependency "${dependency}" must be a package specifier, not a relative or absolute path`,
+ );
+ continue;
+ }
+
+ if (dependency === FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER) {
+ errors.push(
+ `Shared dependency "${dependency}" is reserved and cannot be shared`,
+ );
+ continue;
+ }
+
+ if (
+ RESERVED_DEPENDENCY_PREFIXES.some(
+ (prefix) =>
+ dependency === prefix || dependency.startsWith(`${prefix}/`),
+ )
+ ) {
+ errors.push(
+ `Shared dependency "${dependency}" is already served separately and cannot be shared`,
+ );
+ continue;
+ }
+
+ if (seenDependencies.has(dependency)) {
+ errors.push(`Shared dependency "${dependency}" is declared twice`);
+ continue;
+ }
+
+ seenDependencies.add(dependency);
+ }
+
+ return errors;
+};
+
+export const extractFrontComponentSharedDependencies = async (
+ appPath: string,
+): Promise<{
+ sharedDependencies?: FrontComponentSharedDependenciesManifest;
+ errors: string[];
+}> => {
+ const packageJsonPath = path.join(appPath, 'package.json');
+
+ if (!(await pathExists(packageJsonPath))) {
+ return { errors: [] };
+ }
+
+ const packageJson =
+ await readJson<PackageJsonWithSharedDependencies>(packageJsonPath);
+ const declaredDependencies = packageJson.frontComponentSharedDependencies;
+
+ if (declaredDependencies === undefined) {
+ return { errors: [] };
+ }
+
+ if (!Array.isArray(declaredDependencies)) {
+ return {
+ errors: [
+ '"frontComponentSharedDependencies" in package.json must be an array of package specifiers',
+ ],
+ };
+ }
+
+ if (!isNonEmptyArray(declaredDependencies)) {
+ return { errors: [] };
+ }
+
+ const errors = getSharedDependenciesErrors(declaredDependencies);
+
+ if (isNonEmptyArray(errors)) {
+ return { errors };
+ }
+
+ return {
+ sharedDependencies: {
+ dependencies:
+ normalizeFrontComponentSharedDependencies(declaredDependencies),
+ builtPath: FRONT_COMPONENT_SHARED_DEPENDENCIES_BUILT_PATH,
+ builtChecksum: null,
+ },
+ errors: [],
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/from-front-component-config-to-front-component-manifest.ts b/packages/twenty-cli/src/app/manifest/utils/from-front-component-config-to-front-component-manifest.ts
new file mode 100644
index 00000000000..f5111455b0e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/from-front-component-config-to-front-component-manifest.ts
@@ -0,0 +1,21 @@
+import { type FrontComponentConfig } from '@/app/manifest/types/front-component-config.type';
+import { type FrontComponentManifest } from 'twenty-shared/application';
+
+export const fromFrontComponentConfigToFrontComponentManifest = ({
+ frontComponentConfig,
+ sourcePath,
+}: {
+ frontComponentConfig: FrontComponentConfig;
+ sourcePath: string;
+}): FrontComponentManifest => {
+ const { component, ...rest } = frontComponentConfig;
+
+ return {
+ ...rest,
+ componentName: component.name,
+ sourceComponentPath: sourcePath,
+ builtComponentPath: sourcePath.replace(/\.tsx?$/, '.mjs'),
+ builtComponentChecksum: '',
+ isHeadless: rest.isHeadless ?? false,
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/from-logic-function-config-to-logic-function-manifest.ts b/packages/twenty-cli/src/app/manifest/utils/from-logic-function-config-to-logic-function-manifest.ts
new file mode 100644
index 00000000000..d979f7655ec
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/from-logic-function-config-to-logic-function-manifest.ts
@@ -0,0 +1,56 @@
+import { type LogicFunctionConfig } from '@/app/manifest/types/logic-function-config.type';
+import { type LogicFunctionManifest } from 'twenty-shared/application';
+import {
+ getInputSchemaFromSourceCode,
+ jsonSchemaToInputSchema,
+} from 'twenty-shared/logic-function';
+
+export const fromLogicFunctionConfigToLogicFunctionManifest = async ({
+ logicFunctionConfig,
+ sourceCode,
+ sourcePath,
+}: {
+ logicFunctionConfig: LogicFunctionConfig;
+ sourceCode: string;
+ sourcePath: string;
+}): Promise<LogicFunctionManifest> => {
+ const { handler: _, ...rest } = logicFunctionConfig;
+
+ const inferredJsonSchema =
+ (rest.toolTriggerSettings && !rest.toolTriggerSettings.inputSchema) ||
+ (rest.workflowActionTriggerSettings &&
+ !rest.workflowActionTriggerSettings.inputSchema)
+ ? await getInputSchemaFromSourceCode(sourceCode)
+ : null;
+
+ const toolTriggerSettings = rest.toolTriggerSettings
+ ? {
+ ...rest.toolTriggerSettings,
+ inputSchema:
+ rest.toolTriggerSettings.inputSchema ??
+ inferredJsonSchema ??
+ undefined,
+ }
+ : undefined;
+
+ const workflowActionTriggerSettings = rest.workflowActionTriggerSettings
+ ? {
+ ...rest.workflowActionTriggerSettings,
+ inputSchema:
+ rest.workflowActionTriggerSettings.inputSchema ??
+ (inferredJsonSchema
+ ? jsonSchemaToInputSchema(inferredJsonSchema)
+ : undefined),
+ }
+ : undefined;
+
+ return {
+ ...rest,
+ ...(toolTriggerSettings ? { toolTriggerSettings } : {}),
+ ...(workflowActionTriggerSettings ? { workflowActionTriggerSettings } : {}),
+ handlerName: 'default.config.handler',
+ sourceHandlerPath: sourcePath,
+ builtHandlerPath: sourcePath.replace(/\.tsx?$/, '.mjs'),
+ builtHandlerChecksum: '[default-checksum]',
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/from-object-config-to-object-manifest.ts b/packages/twenty-cli/src/app/manifest/utils/from-object-config-to-object-manifest.ts
new file mode 100644
index 00000000000..883f50f65e2
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/from-object-config-to-object-manifest.ts
@@ -0,0 +1,40 @@
+import { type ObjectConfig } from '@/app/manifest/types/object-config.type';
+import { addMissingFieldOptionIds } from '@/app/manifest/utils/add-missing-field-option-ids';
+import { getDefaultFieldsInObjectFields } from '@/app/manifest/utils/get-default-fields-in-object-fields';
+import { type ObjectManifest } from 'twenty-shared/application';
+
+export const fromObjectConfigToObjectManifest = ({
+ objectConfig,
+ applicationUniversalIdentifier,
+}: {
+ objectConfig: ObjectConfig;
+ applicationUniversalIdentifier: string;
+}): { objectManifest: ObjectManifest | null; errors: string[] } => {
+ const { objectFields: objectFieldsWithDefaults } =
+ getDefaultFieldsInObjectFields({
+ objectConfig,
+ applicationUniversalIdentifier,
+ });
+
+ const labelIdentifierFieldMetadataUniversalIdentifier =
+ objectConfig.labelIdentifierFieldMetadataUniversalIdentifier ??
+ objectFieldsWithDefaults.find((field) => field.name === 'name')
+ ?.universalIdentifier;
+
+ if (!labelIdentifierFieldMetadataUniversalIdentifier) {
+ return {
+ objectManifest: null,
+ errors: [
+ `No label identifier field found for object ${objectConfig.nameSingular}. Please add a field with name "name" to your object.`,
+ ],
+ };
+ }
+
+ const objectManifest: ObjectManifest = {
+ ...objectConfig,
+ fields: objectFieldsWithDefaults.map(addMissingFieldOptionIds),
+ labelIdentifierFieldMetadataUniversalIdentifier,
+ };
+
+ return { objectManifest, errors: [] };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/from-role-config-to-role-manifest.ts b/packages/twenty-cli/src/app/manifest/utils/from-role-config-to-role-manifest.ts
new file mode 100644
index 00000000000..4dbcf214c6b
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/from-role-config-to-role-manifest.ts
@@ -0,0 +1,48 @@
+import { type RoleConfig } from '@/app/manifest/types/role-config.type';
+import {
+ getFieldPermissionUniversalIdentifier,
+ getObjectPermissionUniversalIdentifier,
+ type RoleManifest,
+} from 'twenty-shared/application';
+
+export const fromRoleConfigToRoleManifest = ({
+ roleConfig,
+ applicationUniversalIdentifier,
+}: {
+ roleConfig: RoleConfig;
+ applicationUniversalIdentifier: string;
+}): RoleManifest => {
+ return {
+ ...roleConfig,
+ objectPermissions: (roleConfig.objectPermissions ?? []).map(
+ (objectPermission) => ({
+ ...objectPermission,
+ universalIdentifier:
+ objectPermission.universalIdentifier ??
+ getObjectPermissionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ roleUniversalIdentifier: roleConfig.universalIdentifier,
+ objectUniversalIdentifier:
+ objectPermission.objectUniversalIdentifier,
+ }),
+ }),
+ ),
+ fieldPermissions: (roleConfig.fieldPermissions ?? []).map(
+ (fieldPermission) => ({
+ ...fieldPermission,
+ universalIdentifier:
+ fieldPermission.universalIdentifier ??
+ getFieldPermissionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ roleUniversalIdentifier: roleConfig.universalIdentifier,
+ fieldUniversalIdentifier: fieldPermission.fieldUniversalIdentifier,
+ }),
+ }),
+ ),
+ rowLevelPermissionPredicateGroups:
+ roleConfig.rowLevelPermissionPredicateGroups ?? [],
+ rowLevelPermissionPredicates: roleConfig.rowLevelPermissionPredicates ?? [],
+ permissionFlagUniversalIdentifiers:
+ roleConfig.permissionFlagUniversalIdentifiers ?? [],
+ };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/get-default-fields-in-object-fields.ts b/packages/twenty-cli/src/app/manifest/utils/get-default-fields-in-object-fields.ts
new file mode 100644
index 00000000000..081c32ee113
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/get-default-fields-in-object-fields.ts
@@ -0,0 +1,62 @@
+import { isLabelFieldDefinedOutsideObject } from '@/app/manifest/utils/is-label-field-defined-outside-object';
+import type { ObjectConfig } from '@/app/manifest/types/object-config.type';
+import {
+ getFieldUniversalIdentifier,
+ type ObjectFieldManifest,
+} from 'twenty-shared/application';
+import { FieldMetadataType } from 'twenty-shared/types';
+
+const getDefaultNameObjectField = ({
+ objectConfig,
+ applicationUniversalIdentifier,
+}: {
+ objectConfig: ObjectConfig;
+ applicationUniversalIdentifier: string;
+}): ObjectFieldManifest => ({
+ name: 'name',
+ label: 'Name',
+ description: 'Name',
+ icon: 'IconAbc',
+ isNullable: true,
+ defaultValue: null,
+ type: FieldMetadataType.TEXT,
+ universalIdentifier: getFieldUniversalIdentifier({
+ applicationUniversalIdentifier,
+ objectUniversalIdentifier: objectConfig.universalIdentifier,
+ name: 'name',
+ }),
+});
+
+export const getDefaultFieldsInObjectFields = ({
+ objectConfig,
+ applicationUniversalIdentifier,
+}: {
+ objectConfig: ObjectConfig;
+ applicationUniversalIdentifier: string;
+}): { objectFields: ObjectFieldManifest[] } => {
+ const objectConfigFieldNames = (objectConfig.fields ?? []).map(
+ (field) => field.name,
+ );
+
+ const objectFieldsWithDefaults = [...(objectConfig.fields ?? [])];
+
+ const defaultNameObjectField = getDefaultNameObjectField({
+ objectConfig,
+ applicationUniversalIdentifier,
+ });
+
+ const labelFieldIsDefinedOutsideObject = isLabelFieldDefinedOutsideObject({
+ fields: objectConfig.fields ?? [],
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ objectConfig.labelIdentifierFieldMetadataUniversalIdentifier,
+ });
+
+ if (
+ !objectConfigFieldNames.includes(defaultNameObjectField.name) &&
+ !labelFieldIsDefinedOutsideObject
+ ) {
+ objectFieldsWithDefaults.push(defaultNameObjectField);
+ }
+
+ return { objectFields: objectFieldsWithDefaults };
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/get-page-layout-deprecation-warnings.ts b/packages/twenty-cli/src/app/manifest/utils/get-page-layout-deprecation-warnings.ts
new file mode 100644
index 00000000000..29bf7e6b7b6
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/get-page-layout-deprecation-warnings.ts
@@ -0,0 +1,39 @@
+import { type Manifest } from 'twenty-shared/application';
+import { PageLayoutTabLayoutMode } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+export const getPageLayoutDeprecationWarnings = (
+ manifest: Pick<Manifest, 'pageLayouts' | 'pageLayoutTabs'>,
+): string[] => {
+ const warnings: string[] = [];
+ const tabs = [
+ ...manifest.pageLayouts.flatMap(({ tabs }) => tabs ?? []),
+ ...manifest.pageLayoutTabs,
+ ];
+
+ for (const tab of tabs) {
+ if (tab.layoutMode === PageLayoutTabLayoutMode.CANVAS) {
+ warnings.push(
+ `Page layout tab "${tab.title}" uses deprecated CANVAS. For a full-height widget, use VERTICAL_LIST and set the widget's heightBehavior to 'TAB_VIEWPORT'. Existing Canvas layouts remain supported and are not converted.`,
+ );
+ }
+
+ for (const widget of tab.widgets ?? []) {
+ if (
+ widget.position?.layoutMode === PageLayoutTabLayoutMode.VERTICAL_LIST
+ ) {
+ warnings.push(
+ `Page layout widget "${widget.title}" uses a deprecated vertical-list position. Order the widgets array by position.index, remove position, and move any position.heightBehavior to heightBehavior. Existing positions remain supported and keep their indices.`,
+ );
+ }
+
+ if ('gridPosition' in widget && isDefined(widget.gridPosition)) {
+ warnings.push(
+ `Page layout widget "${widget.title}" uses deprecated gridPosition. If position is already set, it takes precedence; remove the ignored gridPosition. Use position with layoutMode: 'GRID' and the same row, column, rowSpan and columnSpan only when position is absent. Existing gridPosition remains supported as a fallback.`,
+ );
+ }
+ }
+ }
+
+ return warnings;
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/get-unresolved-label-identifier-warnings.ts b/packages/twenty-cli/src/app/manifest/utils/get-unresolved-label-identifier-warnings.ts
new file mode 100644
index 00000000000..b6d4a798435
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/get-unresolved-label-identifier-warnings.ts
@@ -0,0 +1,53 @@
+import {
+ getFieldUniversalIdentifier,
+ type Manifest,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+const ENGINE_FIELD_NAMES = [
+ 'id',
+ 'createdAt',
+ 'createdBy',
+ 'updatedAt',
+ 'updatedBy',
+ 'deletedAt',
+ 'position',
+ 'searchVector',
+];
+
+export const getUnresolvedLabelIdentifierWarnings = (
+ manifest: Manifest,
+): string[] =>
+ manifest.objects.flatMap((object) => {
+ const identifier =
+ object.labelIdentifierFieldMetadataUniversalIdentifier?.toLowerCase();
+
+ if (!isDefined(identifier)) return [];
+
+ const knownIdentifiers = [
+ ...(object.fields ?? []).map((field) =>
+ field.universalIdentifier.toLowerCase(),
+ ),
+ ...manifest.fields
+ .filter(
+ (field) =>
+ field.objectUniversalIdentifier.toLowerCase() ===
+ object.universalIdentifier.toLowerCase(),
+ )
+ .map((field) => field.universalIdentifier.toLowerCase()),
+ ...ENGINE_FIELD_NAMES.map((name) =>
+ getFieldUniversalIdentifier({
+ applicationUniversalIdentifier:
+ manifest.application.universalIdentifier,
+ objectUniversalIdentifier: object.universalIdentifier,
+ name,
+ }),
+ ),
+ ];
+
+ return knownIdentifiers.includes(identifier)
+ ? []
+ : [
+ `Object "${object.nameSingular}" references label field ${identifier}, which is not declared in this app or a recognized generated field. Check the identifier; the server must resolve this reference before applying.`,
+ ];
+ });
diff --git a/packages/twenty-cli/src/app/manifest/utils/is-label-field-defined-outside-object.ts b/packages/twenty-cli/src/app/manifest/utils/is-label-field-defined-outside-object.ts
new file mode 100644
index 00000000000..2d99ab68e4e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/is-label-field-defined-outside-object.ts
@@ -0,0 +1,15 @@
+import { isDefined } from 'twenty-shared/utils';
+
+export const isLabelFieldDefinedOutsideObject = ({
+ fields,
+ labelIdentifierFieldMetadataUniversalIdentifier,
+}: {
+ fields: { universalIdentifier?: string }[];
+ labelIdentifierFieldMetadataUniversalIdentifier?: string;
+}): boolean =>
+ isDefined(labelIdentifierFieldMetadataUniversalIdentifier) &&
+ !fields.some(
+ (field) =>
+ field.universalIdentifier ===
+ labelIdentifierFieldMetadataUniversalIdentifier,
+ );
diff --git a/packages/twenty-cli/src/app/manifest/utils/manifest-validation-helpers.ts b/packages/twenty-cli/src/app/manifest/utils/manifest-validation-helpers.ts
new file mode 100644
index 00000000000..95c2617869e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/manifest-validation-helpers.ts
@@ -0,0 +1,38 @@
+import { type Manifest } from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ type RelationAndMorphRelationFieldMetadataType,
+} from 'twenty-shared/types';
+
+const RELATION_FIELD_TYPES: FieldMetadataType[] = [
+ FieldMetadataType.RELATION,
+ FieldMetadataType.MORPH_RELATION,
+];
+
+export type ManifestField =
+ | Manifest['fields'][number]
+ | Manifest['objects'][number]['fields'][number];
+
+type RelationManifestField = Extract<
+ ManifestField,
+ { type: RelationAndMorphRelationFieldMetadataType }
+>;
+
+export const isRelationFieldManifest = (
+ field: ManifestField,
+): field is RelationManifestField => RELATION_FIELD_TYPES.includes(field.type);
+
+export const getDuplicateValues = (values: string[]): string[] => {
+ const seen = new Set<string>();
+ const duplicates = new Set<string>();
+
+ for (const value of values) {
+ if (seen.has(value)) {
+ duplicates.add(value);
+ } else {
+ seen.add(value);
+ }
+ }
+
+ return Array.from(duplicates);
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/normalize-front-component-shared-dependencies.ts b/packages/twenty-cli/src/app/manifest/utils/normalize-front-component-shared-dependencies.ts
new file mode 100644
index 00000000000..c05544766df
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/normalize-front-component-shared-dependencies.ts
@@ -0,0 +1,11 @@
+export const normalizeFrontComponentSharedDependencies = (
+ dependencies: string[],
+): string[] => {
+ const normalizedDependencies = new Set(dependencies);
+
+ if (normalizedDependencies.has('react')) {
+ normalizedDependencies.add('react/jsx-runtime');
+ }
+
+ return [...normalizedDependencies].sort();
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-agent-roles-within-application-role.ts b/packages/twenty-cli/src/app/manifest/utils/validate-agent-roles-within-application-role.ts
new file mode 100644
index 00000000000..c5ac19079e5
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-agent-roles-within-application-role.ts
@@ -0,0 +1,245 @@
+import {
+ type AgentManifest,
+ getRoleManifestGrantsNotCoveredBy,
+ type ObjectManifest,
+ type PermissionFlagManifest,
+ type RoleManifest,
+ type RoleManifestGrant,
+} from 'twenty-shared/application';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+type ObjectDescriptor = Pick<
+ ObjectManifest,
+ 'universalIdentifier' | 'nameSingular'
+>;
+
+type PermissionFlagDescriptor = Pick<
+ PermissionFlagManifest,
+ 'universalIdentifier' | 'key' | 'permissionType'
+>;
+
+type AgentNamesByRoleUniversalIdentifier = Map<string, string[]>;
+
+const OBJECT_ACTION_LABELS = {
+ canReadObjectRecords: 'read',
+ canUpdateObjectRecords: 'update',
+ canSoftDeleteObjectRecords: 'soft-delete',
+ canDestroyObjectRecords: 'destroy',
+} as const;
+
+const SYSTEM_PERMISSION_FLAG_KEY_BY_UNIVERSAL_IDENTIFIER = Object.fromEntries(
+ Object.entries(SystemPermissionFlag).map(([key, universalIdentifier]) => [
+ universalIdentifier,
+ key,
+ ]),
+);
+
+const STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER = Object.fromEntries(
+ Object.entries(STANDARD_OBJECTS).map(([name, { universalIdentifier }]) => [
+ universalIdentifier,
+ name,
+ ]),
+);
+
+const describeGrant = ({
+ grant,
+ objects,
+ permissionFlags,
+}: {
+ grant: RoleManifestGrant;
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+}): string => {
+ const describeObject = (objectUniversalIdentifier: string) =>
+ objects.find(
+ (object) => object.universalIdentifier === objectUniversalIdentifier,
+ )?.nameSingular ??
+ STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER[objectUniversalIdentifier] ??
+ objectUniversalIdentifier;
+
+ switch (grant.type) {
+ case 'ALL_OBJECT_RECORDS':
+ return `${OBJECT_ACTION_LABELS[grant.action]} all object records`;
+ case 'ALL_SETTINGS':
+ return 'update all settings';
+ case 'ALL_TOOLS':
+ return 'access all tools';
+ case 'PERMISSION_FLAG': {
+ const flagKey =
+ permissionFlags.find(
+ (flag) =>
+ flag.universalIdentifier ===
+ grant.permissionFlagUniversalIdentifier,
+ )?.key ??
+ SYSTEM_PERMISSION_FLAG_KEY_BY_UNIVERSAL_IDENTIFIER[
+ grant.permissionFlagUniversalIdentifier
+ ] ??
+ grant.permissionFlagUniversalIdentifier;
+
+ return `permission flag ${flagKey}`;
+ }
+ case 'OBJECT_RECORDS':
+ return `${OBJECT_ACTION_LABELS[grant.action]} ${describeObject(grant.objectUniversalIdentifier)} records`;
+ case 'FIELD_VALUE':
+ return `${grant.action === 'canReadFieldValue' ? 'read' : 'update'} field ${grant.fieldUniversalIdentifier} of ${describeObject(grant.objectUniversalIdentifier)}`;
+ case 'ROW_LEVEL_RESTRICTION':
+ return `${describeObject(grant.objectUniversalIdentifier)} records without the row-level restriction`;
+ }
+};
+
+const describeAgentList = (agentNames: string[]): string =>
+ agentNames.map((name) => `"${name}"`).join(', ');
+
+const groupAgentNamesByRoleUniversalIdentifier = ({
+ agents,
+ defaultRoleUniversalIdentifier,
+}: {
+ agents: AgentManifest[];
+ defaultRoleUniversalIdentifier: string;
+}): AgentNamesByRoleUniversalIdentifier => {
+ const agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier =
+ new Map();
+
+ for (const agent of agents) {
+ if (
+ !isDefined(agent.roleUniversalIdentifier) ||
+ agent.roleUniversalIdentifier === defaultRoleUniversalIdentifier
+ ) {
+ continue;
+ }
+
+ agentNamesByRoleUniversalIdentifier.set(agent.roleUniversalIdentifier, [
+ ...(agentNamesByRoleUniversalIdentifier.get(
+ agent.roleUniversalIdentifier,
+ ) ?? []),
+ agent.name,
+ ]);
+ }
+
+ return agentNamesByRoleUniversalIdentifier;
+};
+
+const validateApplicationDefaultRoleIsDefined = ({
+ applicationRole,
+ defaultRoleUniversalIdentifier,
+}: {
+ applicationRole: RoleManifest | undefined;
+ defaultRoleUniversalIdentifier: string;
+}): string[] =>
+ isDefined(applicationRole)
+ ? []
+ : [
+ `Application default role "${defaultRoleUniversalIdentifier}" is not defined by this application.`,
+ ];
+
+const validateAgentRolesAreDefined = ({
+ agentNamesByRoleUniversalIdentifier,
+ roles,
+}: {
+ agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier;
+ roles: RoleManifest[];
+}): string[] =>
+ [...agentNamesByRoleUniversalIdentifier]
+ .filter(
+ ([roleUniversalIdentifier]) =>
+ !roles.some(
+ (role) => role.universalIdentifier === roleUniversalIdentifier,
+ ),
+ )
+ .map(
+ ([roleUniversalIdentifier, agentNames]) =>
+ `Agent ${describeAgentList(agentNames)} references role "${roleUniversalIdentifier}", which is not defined by this application.`,
+ );
+
+const validateAgentRolesAreCoveredByApplicationRole = ({
+ agentNamesByRoleUniversalIdentifier,
+ applicationRole,
+ roles,
+ objects,
+ permissionFlags,
+}: {
+ agentNamesByRoleUniversalIdentifier: AgentNamesByRoleUniversalIdentifier;
+ applicationRole: RoleManifest;
+ roles: RoleManifest[];
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+}): string[] => {
+ const toolPermissionFlagUniversalIdentifiers = permissionFlags
+ .filter((flag) => (flag.permissionType ?? 'tool') === 'tool')
+ .map((flag) => flag.universalIdentifier);
+
+ return [...agentNamesByRoleUniversalIdentifier].flatMap(
+ ([roleUniversalIdentifier, agentNames]) => {
+ const agentRole = roles.find(
+ (role) => role.universalIdentifier === roleUniversalIdentifier,
+ );
+
+ if (!isDefined(agentRole)) {
+ return [];
+ }
+
+ const uncoveredGrants = getRoleManifestGrantsNotCoveredBy({
+ role: agentRole,
+ superset: applicationRole,
+ toolPermissionFlagUniversalIdentifiers,
+ });
+
+ if (uncoveredGrants.length === 0) {
+ return [];
+ }
+
+ const grantList = uncoveredGrants
+ .map((grant) => describeGrant({ grant, objects, permissionFlags }))
+ .join(', ');
+
+ return [
+ `Role "${agentRole.label}" used by agent ${describeAgentList(agentNames)} grants more than the application role "${applicationRole.label}": ${grantList}. The application role must cover every permission an agent role grants.`,
+ ];
+ },
+ );
+};
+
+export const validateAgentRolesWithinApplicationRole = ({
+ agents,
+ roles,
+ objects,
+ permissionFlags,
+ defaultRoleUniversalIdentifier,
+}: {
+ agents: AgentManifest[];
+ roles: RoleManifest[];
+ objects: ObjectDescriptor[];
+ permissionFlags: PermissionFlagDescriptor[];
+ defaultRoleUniversalIdentifier: string;
+}): string[] => {
+ const applicationRole = roles.find(
+ (role) => role.universalIdentifier === defaultRoleUniversalIdentifier,
+ );
+ const agentNamesByRoleUniversalIdentifier =
+ groupAgentNamesByRoleUniversalIdentifier({
+ agents,
+ defaultRoleUniversalIdentifier,
+ });
+
+ return [
+ ...validateApplicationDefaultRoleIsDefined({
+ applicationRole,
+ defaultRoleUniversalIdentifier,
+ }),
+ ...validateAgentRolesAreDefined({
+ agentNamesByRoleUniversalIdentifier,
+ roles,
+ }),
+ ...(isDefined(applicationRole)
+ ? validateAgentRolesAreCoveredByApplicationRole({
+ agentNamesByRoleUniversalIdentifier,
+ applicationRole,
+ roles,
+ objects,
+ permissionFlags,
+ })
+ : []),
+ ];
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-conditional-availability-usage.ts b/packages/twenty-cli/src/app/manifest/utils/validate-conditional-availability-usage.ts
new file mode 100644
index 00000000000..a169070204e
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-conditional-availability-usage.ts
@@ -0,0 +1,189 @@
+import { CONDITIONAL_AVAILABILITY_VARIABLE_NAMES } from '@/app/manifest/utils/conditional-availability-variable-names';
+import { isDefined } from 'twenty-shared/utils';
+import ts from 'typescript';
+
+const CONDITIONAL_AVAILABILITY_EXPRESSION_PROPERTY =
+ 'conditionalAvailabilityExpression';
+
+const EXPRESSION_VARIABLE_MODULE_SPECIFIERS = [
+ 'twenty-sdk/define',
+ 'twenty-sdk',
+];
+
+const EXPRESSION_VARIABLE_NAMES = new Set<string>(
+ CONDITIONAL_AVAILABILITY_VARIABLE_NAMES,
+);
+
+type ImportedExpressionVariable = {
+ importedName: string;
+ node: ts.Node;
+};
+
+const collectImportedExpressionVariables = (
+ sourceFile: ts.SourceFile,
+ checker: ts.TypeChecker,
+): ImportedExpressionVariable[] => {
+ const imported: ImportedExpressionVariable[] = [];
+
+ for (const statement of sourceFile.statements) {
+ if (
+ !ts.isImportDeclaration(statement) ||
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
+ !EXPRESSION_VARIABLE_MODULE_SPECIFIERS.includes(
+ statement.moduleSpecifier.text,
+ )
+ ) {
+ continue;
+ }
+
+ const importClause = statement.importClause;
+
+ if (
+ !isDefined(importClause) ||
+ importClause.phaseModifier === ts.SyntaxKind.TypeKeyword
+ ) {
+ continue;
+ }
+
+ const namedBindings = importClause.namedBindings;
+
+ if (!isDefined(namedBindings)) {
+ continue;
+ }
+
+ if (ts.isNamespaceImport(namedBindings)) {
+ const namespaceSymbol = checker.getSymbolAtLocation(namedBindings.name);
+
+ const collectNamespaceMemberUsages = (node: ts.Node): void => {
+ if (ts.isImportDeclaration(node) || ts.isTypeNode(node)) return;
+ if (
+ ts.isPropertyAccessExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ checker.getSymbolAtLocation(node.expression) === namespaceSymbol &&
+ EXPRESSION_VARIABLE_NAMES.has(node.name.text)
+ ) {
+ imported.push({ importedName: node.name.text, node });
+ }
+
+ ts.forEachChild(node, collectNamespaceMemberUsages);
+ };
+
+ collectNamespaceMemberUsages(sourceFile);
+ continue;
+ }
+
+ if (!ts.isNamedImports(namedBindings)) {
+ continue;
+ }
+
+ for (const element of namedBindings.elements) {
+ if (element.isTypeOnly) {
+ continue;
+ }
+
+ const importedName = (element.propertyName ?? element.name).text;
+
+ if (EXPRESSION_VARIABLE_NAMES.has(importedName)) {
+ const importedSymbol = checker.getSymbolAtLocation(element.name);
+ let usage: ts.Node | undefined;
+ const findUsage = (node: ts.Node): void => {
+ if (
+ isDefined(usage) ||
+ ts.isImportDeclaration(node) ||
+ ts.isTypeNode(node)
+ )
+ return;
+
+ if (ts.isIdentifier(node)) {
+ const symbol = ts.isShorthandPropertyAssignment(node.parent)
+ ? checker.getShorthandAssignmentValueSymbol(node.parent)
+ : checker.getSymbolAtLocation(node);
+
+ if (isDefined(importedSymbol) && symbol === importedSymbol)
+ usage = node;
+ }
+ ts.forEachChild(node, findUsage);
+ };
+
+ findUsage(sourceFile);
+ if (isDefined(usage)) imported.push({ importedName, node: usage });
+ }
+ }
+ }
+
+ return imported;
+};
+
+const hasConditionalAvailabilityExpressionProperty = (
+ sourceFile: ts.SourceFile,
+): boolean => {
+ let found = false;
+
+ const findExpressionProperty = (node: ts.Node): void => {
+ if (found) {
+ return;
+ }
+
+ if (
+ (ts.isPropertyAssignment(node) ||
+ ts.isShorthandPropertyAssignment(node)) &&
+ (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) &&
+ node.name.text === CONDITIONAL_AVAILABILITY_EXPRESSION_PROPERTY
+ ) {
+ found = true;
+ return;
+ }
+
+ ts.forEachChild(node, findExpressionProperty);
+ };
+
+ findExpressionProperty(sourceFile);
+
+ return found;
+};
+
+export const validateConditionalAvailabilityUsage = (
+ fileContent: string,
+ relativePath: string,
+): string[] => {
+ if (
+ !CONDITIONAL_AVAILABILITY_VARIABLE_NAMES.some((name) =>
+ fileContent.includes(name),
+ )
+ ) {
+ return [];
+ }
+
+ const sourceFile = ts.createSourceFile(
+ relativePath,
+ fileContent,
+ ts.ScriptTarget.Latest,
+ true,
+ relativePath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
+ );
+
+ if (hasConditionalAvailabilityExpressionProperty(sourceFile)) {
+ return [];
+ }
+
+ const options: ts.CompilerOptions = { noLib: true, noResolve: true };
+ const host = ts.createCompilerHost(options);
+
+ host.getSourceFile = (name) =>
+ name === sourceFile.fileName ? sourceFile : undefined;
+ const checker = ts
+ .createProgram([sourceFile.fileName], options, host)
+ .getTypeChecker();
+ const importedExpressionVariables = collectImportedExpressionVariables(
+ sourceFile,
+ checker,
+ );
+
+ return importedExpressionVariables.map(({ importedName, node }) => {
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(
+ node.getStart(sourceFile),
+ );
+
+ return `${relativePath}:${line + 1}:${character + 1} - "${importedName}" is a conditional-availability expression variable from twenty-sdk but this file has no ${CONDITIONAL_AVAILABILITY_EXPRESSION_PROPERTY}. These variables can only be used inside a command's ${CONDITIONAL_AVAILABILITY_EXPRESSION_PROPERTY}, not at runtime.`;
+ });
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-package-json-dependencies.ts b/packages/twenty-cli/src/app/manifest/utils/validate-package-json-dependencies.ts
new file mode 100644
index 00000000000..7b8bb282c74
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-package-json-dependencies.ts
@@ -0,0 +1,40 @@
+import { pathExists, readJson } from '@/app/fs-utils';
+import path from 'path';
+import { isDefined } from 'twenty-shared/utils';
+
+type PackageJsonDependencies = {
+ dependencies?: Record<string, string>;
+ optionalDependencies?: Record<string, string>;
+};
+
+// SDK authoring code is handled by the build, and Twenty supplies the client SDK
+// at runtime. Listing either as a dependency adds it to the Lambda deps layer.
+const BUILD_TIME_DEPENDENCY_WARNINGS: Record<string, string> = {
+ 'twenty-sdk':
+ '"twenty-sdk" is listed under "dependencies" in package.json. It is a build-time only tool and should be moved to "devDependencies".',
+ 'twenty-client-sdk':
+ '"twenty-client-sdk" is listed under "dependencies" in package.json. It is provided at runtime by Twenty\'s injected SDK and should be moved to "devDependencies".',
+};
+
+export const validatePackageJsonDependencies = async (
+ appPath: string,
+): Promise<string[]> => {
+ const packageJsonPath = path.join(appPath, 'package.json');
+
+ if (!(await pathExists(packageJsonPath))) {
+ return [];
+ }
+
+ const packageJson = await readJson<PackageJsonDependencies>(packageJsonPath);
+
+ return (['dependencies', 'optionalDependencies'] as const).flatMap(
+ (section) =>
+ Object.entries(BUILD_TIME_DEPENDENCY_WARNINGS)
+ .filter(([packageName]) =>
+ isDefined(packageJson[section]?.[packageName]),
+ )
+ .map(([, warning]) =>
+ warning.replace('"dependencies"', `"${section}"`),
+ ),
+ );
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-timeline-activity-types.ts b/packages/twenty-cli/src/app/manifest/utils/validate-timeline-activity-types.ts
new file mode 100644
index 00000000000..2f23c6c9c74
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-timeline-activity-types.ts
@@ -0,0 +1,215 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import {
+ type Manifest,
+ isValidUniversalIdentifier,
+} from 'twenty-shared/application';
+import { RelationType } from 'twenty-shared/types';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import {
+ getDuplicateValues,
+ isRelationFieldManifest,
+} from '@/app/manifest/utils/manifest-validation-helpers';
+
+export const validateTimelineActivityTypes = (
+ manifest: Pick<
+ Manifest,
+ 'fields' | 'frontComponents' | 'objects' | 'timelineActivityTypes'
+ >,
+): string[] => {
+ const errors: string[] = [];
+ const duplicateNames = getDuplicateValues(
+ manifest.timelineActivityTypes.map(
+ (timelineActivityType) => timelineActivityType.name,
+ ),
+ );
+ const frontComponentUniversalIdentifiers = new Set(
+ manifest.frontComponents.map(
+ (frontComponent) => frontComponent.universalIdentifier,
+ ),
+ );
+
+ for (const duplicateName of duplicateNames) {
+ errors.push(
+ `Timeline activity type name "${duplicateName}" is used more than once. Names must be unique within an application.`,
+ );
+ }
+
+ for (const timelineActivityType of manifest.timelineActivityTypes) {
+ if (
+ isDefined(timelineActivityType.frontComponentUniversalIdentifier) &&
+ !frontComponentUniversalIdentifiers.has(
+ timelineActivityType.frontComponentUniversalIdentifier,
+ )
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references front component "${timelineActivityType.frontComponentUniversalIdentifier}", which is not defined by this application.`,
+ );
+ }
+
+ const emit = timelineActivityType.emit;
+ const replacementUniversalIdentifier =
+ timelineActivityType.replacesTimelineActivityTypeUniversalIdentifier;
+
+ if (!isDefined(emit)) {
+ if (isDefined(replacementUniversalIdentifier)) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" declares replacesTimelineActivityTypeUniversalIdentifier without an automatic emit contract.`,
+ );
+ }
+
+ continue;
+ }
+
+ const through = emit.through;
+ const triggerFieldUniversalIdentifiers =
+ through?.triggerFieldUniversalIdentifiers;
+ const hasValidObjectUniversalIdentifier = isValidUniversalIdentifier(
+ emit.objectUniversalIdentifier,
+ );
+
+ if (!hasValidObjectUniversalIdentifier) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references an invalid object universal identifier "${emit.objectUniversalIdentifier}".`,
+ );
+ }
+
+ if (
+ (emit.on === 'linked' || emit.on === 'unlinked') &&
+ !isDefined(through)
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" must declare emit.through for a ${emit.on} event.`,
+ );
+ }
+
+ if (isDefined(triggerFieldUniversalIdentifiers)) {
+ if (
+ emit.on !== 'updated' ||
+ !isNonEmptyArray(triggerFieldUniversalIdentifiers) ||
+ new Set(triggerFieldUniversalIdentifiers).size !==
+ triggerFieldUniversalIdentifiers.length
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" trigger fields must be a non-empty list of unique fields on an updated through event.`,
+ );
+ }
+ }
+
+ const sourceObject = hasValidObjectUniversalIdentifier
+ ? manifest.objects.find(
+ (object) =>
+ object.universalIdentifier === emit.objectUniversalIdentifier,
+ )
+ : undefined;
+
+ if (!isDefined(sourceObject)) {
+ if (
+ hasValidObjectUniversalIdentifier &&
+ !isDefined(replacementUniversalIdentifier)
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" targets object "${emit.objectUniversalIdentifier}", which is not defined by this application. Types targeting another application's object must declare replacesTimelineActivityTypeUniversalIdentifier.`,
+ );
+ }
+
+ if (
+ isDefined(replacementUniversalIdentifier) &&
+ !isValidUniversalIdentifier(replacementUniversalIdentifier)
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references an invalid replacement universal identifier "${replacementUniversalIdentifier}".`,
+ );
+ }
+
+ if (
+ isDefined(through) &&
+ !isValidUniversalIdentifier(through.relationFieldUniversalIdentifier)
+ ) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references an invalid through relation field universal identifier "${through.relationFieldUniversalIdentifier}".`,
+ );
+ }
+
+ const invalidTriggerFieldUniversalIdentifiers =
+ triggerFieldUniversalIdentifiers?.filter(
+ (universalIdentifier) =>
+ !isValidUniversalIdentifier(universalIdentifier),
+ ) ?? [];
+
+ if (invalidTriggerFieldUniversalIdentifiers.length > 0) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references invalid trigger field universal identifiers: ${invalidTriggerFieldUniversalIdentifiers.join(', ')}.`,
+ );
+ }
+
+ continue;
+ }
+
+ if (isDefined(replacementUniversalIdentifier)) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" targets an object defined by this application and must not replace another application's type.`,
+ );
+ }
+
+ const sourceFields = [
+ ...sourceObject.fields,
+ ...manifest.fields.filter(
+ (field) =>
+ field.objectUniversalIdentifier === sourceObject.universalIdentifier,
+ ),
+ ];
+
+ if (!isDefined(through)) {
+ continue;
+ }
+
+ const relationField = sourceFields.find(
+ (field) =>
+ field.universalIdentifier === through.relationFieldUniversalIdentifier,
+ );
+
+ if (!isDefined(relationField)) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references relation field "${through.relationFieldUniversalIdentifier}", which is not defined on object "${sourceObject.nameSingular}".`,
+ );
+ } else {
+ const hasSupportedRelationShape =
+ isRelationFieldManifest(relationField) &&
+ isDefined(relationField.universalSettings) &&
+ (relationField.universalSettings.relationType ===
+ RelationType.MANY_TO_ONE ||
+ (relationField.universalSettings.relationType ===
+ RelationType.ONE_TO_MANY &&
+ isNonEmptyString(
+ relationField.universalSettings
+ .junctionTargetFieldUniversalIdentifier,
+ )));
+
+ if (!hasSupportedRelationShape) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" must route through a MANY_TO_ONE relation or a junction-backed ONE_TO_MANY relation.`,
+ );
+ }
+ }
+
+ if (isDefined(triggerFieldUniversalIdentifiers)) {
+ const sourceFieldUniversalIdentifiers = new Set(
+ sourceFields.map((field) => field.universalIdentifier),
+ );
+ const missingTriggerFieldUniversalIdentifiers =
+ triggerFieldUniversalIdentifiers.filter(
+ (universalIdentifier) =>
+ !sourceFieldUniversalIdentifiers.has(universalIdentifier),
+ );
+
+ if (missingTriggerFieldUniversalIdentifiers.length > 0) {
+ errors.push(
+ `Timeline activity type "${timelineActivityType.name}" references trigger fields that are not defined on object "${sourceObject.nameSingular}": ${missingTriggerFieldUniversalIdentifiers.join(', ')}.`,
+ );
+ }
+ }
+ }
+
+ return errors;
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-view-filter-operands.ts b/packages/twenty-cli/src/app/manifest/utils/validate-view-filter-operands.ts
new file mode 100644
index 00000000000..430d50c6a85
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-view-filter-operands.ts
@@ -0,0 +1,80 @@
+import {
+ type FieldManifest,
+ type ObjectFieldManifest,
+ type ObjectManifest,
+ type ViewManifest,
+} from 'twenty-shared/application';
+import {
+ FieldMetadataType,
+ type FilterableAndTSVectorFieldType,
+} from 'twenty-shared/types';
+import {
+ FILTER_OPERANDS_MAP,
+ getFilterOperandsForFilterableFieldType,
+ isDefined,
+} from 'twenty-shared/utils';
+
+export const validateViewFilterOperands = ({
+ views,
+ objects,
+ fields,
+}: {
+ views: ViewManifest[];
+ objects: ObjectManifest[];
+ fields: FieldManifest[];
+}): string[] => {
+ const errors: string[] = [];
+
+ const fieldByUniversalIdentifier = new Map<
+ string,
+ FieldManifest | ObjectFieldManifest
+ >();
+ for (const field of fields) {
+ fieldByUniversalIdentifier.set(field.universalIdentifier, field);
+ }
+ for (const object of objects) {
+ for (const objectField of object.fields) {
+ fieldByUniversalIdentifier.set(
+ objectField.universalIdentifier,
+ objectField,
+ );
+ }
+ }
+
+ for (const view of views) {
+ for (const filter of view.filters ?? []) {
+ const referencedField = fieldByUniversalIdentifier.get(
+ filter.fieldMetadataUniversalIdentifier,
+ );
+ if (!isDefined(referencedField)) {
+ continue;
+ }
+
+ const effectiveFieldType: FieldMetadataType =
+ (referencedField.type === FieldMetadataType.RELATION ||
+ referencedField.type === FieldMetadataType.MORPH_RELATION) &&
+ isDefined(filter.relationTargetFieldMetadataUniversalIdentifier)
+ ? (fieldByUniversalIdentifier.get(
+ filter.relationTargetFieldMetadataUniversalIdentifier,
+ )?.type ?? referencedField.type)
+ : referencedField.type;
+
+ if (!(effectiveFieldType in FILTER_OPERANDS_MAP)) {
+ continue;
+ }
+
+ const allowedOperands = getFilterOperandsForFilterableFieldType({
+ filterType: effectiveFieldType as FilterableAndTSVectorFieldType,
+ subFieldName: filter.subFieldName,
+ });
+
+ if (!allowedOperands.includes(filter.operand)) {
+ errors.push(
+ `Operand "${filter.operand}" is not supported on field "${referencedField.name}" (type "${effectiveFieldType}"). Supported operands: ${allowedOperands.join(', ')}.`,
+ );
+ }
+ }
+ }
+
+ return errors;
+};
diff --git a/packages/twenty-cli/src/app/manifest/utils/validate-yarn-lock.ts b/packages/twenty-cli/src/app/manifest/utils/validate-yarn-lock.ts
new file mode 100644
index 00000000000..c0c76630c57
--- /dev/null
+++ b/packages/twenty-cli/src/app/manifest/utils/validate-yarn-lock.ts
@@ -0,0 +1,20 @@
+import { pathExists } from '@/app/fs-utils';
+import { stat } from 'node:fs/promises';
+import path from 'path';
+
+export const validateYarnLockFile = async (
+ yarnLockPath: string,
+): Promise<string[]> => {
+ if (!(await pathExists(yarnLockPath))) {
+ return [];
+ }
+
+ return (await stat(yarnLockPath)).size === 0
+ ? [
+ 'yarn.lock is empty. Run "yarn install" to regenerate it before building.',
+ ]
+ : [];
+};
+
+export const validateYarnLock = (appPath: string): Promise<string[]> =>
+ validateYarnLockFile(path.join(appPath, 'yarn.lock'));
diff --git a/packages/twenty-cli/src/app/parse-app-export.ts b/packages/twenty-cli/src/app/parse-app-export.ts
new file mode 100644
index 00000000000..2db9392f6a8
--- /dev/null
+++ b/packages/twenty-cli/src/app/parse-app-export.ts
@@ -0,0 +1,71 @@
+import { isArray, isNull, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';
+import { isExportedManifest } from '@/app/pull/is-exported-manifest';
+import {
+ type AppExport,
+ type AppExportCoverageEntry,
+} from '@/app/types/app-export.type';
+import { CliError } from '@/output/cli-error';
+
+const isCoverageEntry = (value: unknown): value is AppExportCoverageEntry =>
+ isPlainObject(value) &&
+ isString(value.metadataName) &&
+ isString(value.universalIdentifier) &&
+ isString(value.status) &&
+ (isString(value.reason) || isNull(value.reason));
+
+export const parseAppExport = ({
+ value,
+ universalIdentifier,
+}: {
+ value: unknown;
+ universalIdentifier: string;
+}): AppExport => {
+ const applicationExport = value;
+
+ if (
+ !isPlainObject(applicationExport) ||
+ !isPlainObject(applicationExport.application) ||
+ !isString(applicationExport.application.universalIdentifier) ||
+ !isSameUniversalIdentifier({
+ value: applicationExport.application.universalIdentifier,
+ universalIdentifier,
+ }) ||
+ !isString(applicationExport.application.displayName) ||
+ !isString(applicationExport.application.sourceType) ||
+ !isExportedManifest(applicationExport.manifest) ||
+ !isSameUniversalIdentifier({
+ value: applicationExport.manifest.application.universalIdentifier,
+ universalIdentifier,
+ }) ||
+ !isArray(applicationExport.coverage) ||
+ !applicationExport.coverage.every(isCoverageEntry) ||
+ !isArray(applicationExport.files)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `The server returned an export of ${universalIdentifier} that this CLI cannot read.`,
+ });
+ }
+
+ if (applicationExport.files.length > 0) {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message:
+ 'The application export contains source or dependency files that this CLI cannot reconcile. No local files were changed.',
+ hint: 'Use a CLI version that supports this export format.',
+ });
+ }
+
+ return {
+ application: {
+ universalIdentifier: applicationExport.application.universalIdentifier,
+ displayName: applicationExport.application.displayName,
+ sourceType: applicationExport.application.sourceType,
+ },
+ manifest: applicationExport.manifest,
+ coverage: applicationExport.coverage,
+ files: [],
+ };
+};
diff --git a/packages/twenty-cli/src/app/parse-tooling-result.ts b/packages/twenty-cli/src/app/parse-tooling-result.ts
new file mode 100644
index 00000000000..6b3172e1f62
--- /dev/null
+++ b/packages/twenty-cli/src/app/parse-tooling-result.ts
@@ -0,0 +1,132 @@
+import { isArray, isNull, isNumber, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import {
+ type ToolingArtifact,
+ type ToolingBuild,
+ type ToolingDiagnostic,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+
+const isOptionalString = (value: unknown) =>
+ !isDefined(value) || isString(value);
+
+const isOptionalNumber = (value: unknown) =>
+ !isDefined(value) || isNumber(value);
+
+export const isToolingDiagnostic = (
+ value: unknown,
+): value is ToolingDiagnostic =>
+ isPlainObject(value) &&
+ (value.severity === 'error' || value.severity === 'warning') &&
+ isString(value.code) &&
+ isString(value.message) &&
+ isOptionalString(value.file) &&
+ isOptionalNumber(value.line) &&
+ isOptionalNumber(value.column);
+
+const isToolingArtifact = (value: unknown): value is ToolingArtifact =>
+ isPlainObject(value) &&
+ isString(value.path) &&
+ isString(value.role) &&
+ isString(value.sourcePath) &&
+ isNumber(value.size) &&
+ isString(value.sha256);
+
+const createInvalidResultError = () =>
+ new CliError({
+ code: 'WORKER_FAILED',
+ message: 'The app worker returned a result this CLI cannot read.',
+ hint: 'Check that the app and the CLI use compatible versions.',
+ });
+
+export const parseBuildData = (
+ value: unknown,
+): { data: ToolingBuild } | undefined => {
+ if (
+ !isPlainObject(value) ||
+ !isString(value.buildId) ||
+ !isOptionalString(value.directory) ||
+ !isString(value.contentHash) ||
+ !isPlainObject(value.application) ||
+ !isString(value.application.universalIdentifier) ||
+ !isString(value.application.name) ||
+ !isString(value.application.displayName) ||
+ !isString(value.manifestFormat) ||
+ !isPlainObject(value.manifest) ||
+ !isArray(value.files) ||
+ !value.files.every(isToolingArtifact)
+ ) {
+ return undefined;
+ }
+
+ return {
+ data: {
+ buildId: value.buildId,
+ ...(isString(value.directory) ? { directory: value.directory } : {}),
+ contentHash: value.contentHash,
+ application: {
+ universalIdentifier: value.application.universalIdentifier,
+ name: value.application.name,
+ displayName: value.application.displayName,
+ },
+ manifestFormat: value.manifestFormat,
+ manifest: value.manifest,
+ files: value.files,
+ },
+ };
+};
+
+export const parseNullData = (value: unknown): { data: null } | undefined =>
+ isNull(value) ? { data: null } : undefined;
+
+export const parseToolingResult = <TData>({
+ value,
+ parseData,
+}: {
+ value: unknown;
+ parseData: (data: unknown) => { data: TData } | undefined;
+}): ToolingResult<TData> => {
+ if (
+ !isPlainObject(value) ||
+ !isArray(value.diagnostics) ||
+ !value.diagnostics.every(isToolingDiagnostic)
+ ) {
+ throw createInvalidResultError();
+ }
+
+ const diagnostics = value.diagnostics;
+
+ if (value.success === true) {
+ const parsed = parseData(value.data);
+
+ if (!isDefined(parsed)) {
+ throw createInvalidResultError();
+ }
+
+ return { success: true, data: parsed.data, diagnostics };
+ }
+
+ if (
+ value.success === false &&
+ isPlainObject(value.error) &&
+ isString(value.error.code) &&
+ isString(value.error.message)
+ ) {
+ return {
+ success: false,
+ error: {
+ code: value.error.code,
+ message: value.error.message,
+ ...(isString(value.error.hint) ? { hint: value.error.hint } : {}),
+ ...(isPlainObject(value.error.details)
+ ? { details: value.error.details }
+ : {}),
+ },
+ diagnostics,
+ };
+ }
+
+ throw createInvalidResultError();
+};
diff --git a/packages/twenty-cli/src/app/project/__tests__/check-node-requirement.spec.ts b/packages/twenty-cli/src/app/project/__tests__/check-node-requirement.spec.ts
new file mode 100644
index 00000000000..ecb82260ab3
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/__tests__/check-node-requirement.spec.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { checkNodeRequirement } from '@/app/project/check-node-requirement';
+
+describe('checkNodeRequirement', () => {
+ it.each([
+ ['24.5.0', '^24.5.0', 'satisfied'],
+ ['24.4.9', '^24.5.0', 'unsatisfied'],
+ ['24.5.0', '24', 'satisfied'],
+ ['24.5.0', '<=24', 'satisfied'],
+ ['24.5.0', '99.x', 'unsatisfied'],
+ ['24.5.0', '>= 99.0.0', 'unsatisfied'],
+ ['24.5.0', '20 - 24', 'satisfied'],
+ ['24.5.0', '^20 || ^24', 'satisfied'],
+ ['24.5.0', 'latest', 'invalid'],
+ ])('checks Node %s against %j', (version, range, expected) => {
+ expect(checkNodeRequirement({ version, range })).toBe(expected);
+ });
+});
diff --git a/packages/twenty-cli/src/app/project/__tests__/resolve-source-sdk.spec.ts b/packages/twenty-cli/src/app/project/__tests__/resolve-source-sdk.spec.ts
new file mode 100644
index 00000000000..2e8639bedf7
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/__tests__/resolve-source-sdk.spec.ts
@@ -0,0 +1,129 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { createSourceTestApp } from '@/app/source/__tests__/utils/create-source-test-app';
+
+describe('source SDK compatibility', () => {
+ let appPath: string;
+ let sdkPath: string;
+
+ const updatePackage = async (fields: Record<string, unknown>) => {
+ const packagePath = join(sdkPath, 'package.json');
+ await writeFile(
+ packagePath,
+ JSON.stringify({
+ ...JSON.parse(await readFile(packagePath, 'utf8')),
+ ...fields,
+ }),
+ );
+ };
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-source-sdk-'));
+ sdkPath = await realpath(await createSourceTestApp(appPath));
+ await writeFile(
+ join(sdkPath, 'define.cjs'),
+ 'throw new Error("do not execute the SDK in the parent");',
+ );
+ });
+ afterEach(async () => rm(appPath, { recursive: true, force: true }));
+
+ it('checks only public authoring exports, without a build descriptor or project compiler', async () => {
+ expect(await resolveSourceSdk({ appPath })).toEqual({
+ version: '2.44.0',
+ packagePath: sdkPath,
+ });
+ const resolve = createRequire(join(appPath, 'package.json')).resolve;
+
+ expect(() => resolve('twenty-sdk/build')).toThrow();
+ expect(() => resolve('typescript')).toThrow();
+ });
+
+ it.each(['1.23.0', '2.44.0-canary.1', '3.0.0'])(
+ 'accepts %s when the public entry points exist',
+ async (version) => {
+ await updatePackage({ version });
+ expect((await resolveSourceSdk({ appPath })).version).toBe(version);
+ },
+ );
+
+ it.each(['1.22.0', 'unknown'])(
+ 'rejects unsupported SDK version %s',
+ async (version) => {
+ await updatePackage({ version });
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ });
+ },
+ );
+
+ it('requires the authoring entry points even for a recent version', async () => {
+ await updatePackage({ exports: { './define': './define.cjs' } });
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ details: { missingEntryPoints: ['twenty-sdk/front-component'] },
+ });
+ });
+
+ it.each([
+ { node: '>=999.0.0', code: 'NODE_VERSION_UNSUPPORTED' },
+ { node: 'not-semver', code: 'SDK_SOURCE_UNSUPPORTED' },
+ ])(
+ 'checks the installed SDK Node requirement $node',
+ async ({ node, code }) => {
+ await updatePackage({ engines: { node } });
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code,
+ });
+ },
+ );
+
+ it('resolves a hoisted SDK and a workspace symlink without importing it', async () => {
+ const nestedPath = join(appPath, 'apps/demo');
+ await mkdir(nestedPath, { recursive: true });
+ await writeFile(join(nestedPath, 'package.json'), '{}');
+ expect((await resolveSourceSdk({ appPath: nestedPath })).packagePath).toBe(
+ sdkPath,
+ );
+
+ const linkedPath = join(appPath, 'linked-app');
+ await mkdir(join(linkedPath, 'node_modules'), { recursive: true });
+ await writeFile(join(linkedPath, 'package.json'), '{}');
+ await symlink(sdkPath, join(linkedPath, 'node_modules/twenty-sdk'));
+ expect((await resolveSourceSdk({ appPath: linkedPath })).packagePath).toBe(
+ sdkPath,
+ );
+ });
+
+ it('distinguishes missing, broken and unsupported PnP installations', async () => {
+ await writeFile(join(sdkPath, 'package.json'), '{');
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code: 'TOOLING_UNSUPPORTED',
+ });
+ await rm(sdkPath, { recursive: true });
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code: 'SDK_NOT_INSTALLED',
+ });
+ await writeFile(
+ join(appPath, '.pnp.cjs'),
+ 'throw new Error("never imported");',
+ );
+ await expect(resolveSourceSdk({ appPath })).rejects.toMatchObject({
+ code: 'TOOLING_UNSUPPORTED',
+ message: expect.stringContaining("Plug'n'Play"),
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/project/check-node-requirement.ts b/packages/twenty-cli/src/app/project/check-node-requirement.ts
new file mode 100644
index 00000000000..401b00c7ac0
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/check-node-requirement.ts
@@ -0,0 +1,19 @@
+import { isNull } from '@sniptt/guards';
+import satisfies from 'semver/functions/satisfies';
+import validRange from 'semver/ranges/valid';
+
+type NodeRequirementCheck = 'satisfied' | 'unsatisfied' | 'invalid';
+
+export const checkNodeRequirement = ({
+ version,
+ range,
+}: {
+ version: string;
+ range: string;
+}): NodeRequirementCheck => {
+ if (isNull(validRange(range))) {
+ return 'invalid';
+ }
+
+ return satisfies(version, range) ? 'satisfied' : 'unsatisfied';
+};
diff --git a/packages/twenty-cli/src/app/project/has-yarn-plug-and-play.ts b/packages/twenty-cli/src/app/project/has-yarn-plug-and-play.ts
new file mode 100644
index 00000000000..61663f2687b
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/has-yarn-plug-and-play.ts
@@ -0,0 +1,25 @@
+import { access } from 'node:fs/promises';
+import { join } from 'node:path';
+
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+
+export const hasYarnPlugAndPlay = async (appPath: string) => {
+ for (const directory of listAncestorDirectories(appPath)) {
+ const hasLoader = (
+ await Promise.all(
+ ['.pnp.cjs', '.pnp.js'].map((fileName) =>
+ access(join(directory, fileName)).then(
+ () => true,
+ () => false,
+ ),
+ ),
+ )
+ ).some(Boolean);
+
+ if (hasLoader) {
+ return true;
+ }
+ }
+
+ return false;
+};
diff --git a/packages/twenty-cli/src/app/project/list-ancestor-directories.ts b/packages/twenty-cli/src/app/project/list-ancestor-directories.ts
new file mode 100644
index 00000000000..50952ad303b
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/list-ancestor-directories.ts
@@ -0,0 +1,9 @@
+import { dirname } from 'node:path';
+
+export const listAncestorDirectories = (directory: string): string[] => {
+ const parentDirectory = dirname(directory);
+
+ return parentDirectory === directory
+ ? [directory]
+ : [directory, ...listAncestorDirectories(parentDirectory)];
+};
diff --git a/packages/twenty-cli/src/app/project/resolve-app-project.ts b/packages/twenty-cli/src/app/project/resolve-app-project.ts
new file mode 100644
index 00000000000..f3d35aa6aff
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/resolve-app-project.ts
@@ -0,0 +1,138 @@
+import { readdir, stat } from 'node:fs/promises';
+import { basename, join, relative, resolve } from 'node:path';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+import { readJsonObject } from '@/app/read-json-object';
+import { type AppProject } from '@/app/project/types/app-project.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const DEPENDENCY_FIELDS = [
+ 'dependencies',
+ 'devDependencies',
+ 'peerDependencies',
+];
+
+const readAppProject = async (
+ directory: string,
+): Promise<AppProject | undefined> => {
+ const packageJson = await readJsonObject(join(directory, 'package.json'));
+
+ if (!isDefined(packageJson)) {
+ return undefined;
+ }
+
+ const dependsOnSdk = DEPENDENCY_FIELDS.some((field) => {
+ const dependencies = packageJson[field];
+
+ return (
+ isPlainObject(dependencies) && Object.hasOwn(dependencies, 'twenty-sdk')
+ );
+ });
+
+ if (!dependsOnSdk) {
+ return undefined;
+ }
+
+ return {
+ path: directory,
+ name: isNonEmptyString(packageJson.name)
+ ? packageJson.name
+ : basename(directory),
+ };
+};
+
+const findChildAppProjects = async (directory: string) => {
+ const entries = await readdir(directory, { withFileTypes: true }).catch(
+ () => [],
+ );
+ const projects = await Promise.all(
+ entries
+ .filter(
+ (entry) =>
+ entry.isDirectory() &&
+ !entry.name.startsWith('.') &&
+ entry.name !== 'node_modules',
+ )
+ .map((entry) => readAppProject(join(directory, entry.name))),
+ );
+
+ return projects
+ .filter(isDefined)
+ .sort((first, second) => first.path.localeCompare(second.path));
+};
+
+const findEnclosingAppProject = async (directory: string) => {
+ for (const candidate of listAncestorDirectories(directory)) {
+ const project = await readAppProject(candidate);
+
+ if (isDefined(project)) {
+ return project;
+ }
+ }
+
+ return undefined;
+};
+
+export const resolveAppProject = async ({
+ explicitPath,
+ workingDirectory,
+}: {
+ explicitPath?: string;
+ workingDirectory: string;
+}): Promise<AppProject> => {
+ if (isDefined(explicitPath)) {
+ const appPath = resolve(workingDirectory, explicitPath);
+ const appPathStats = await stat(appPath).catch(() => undefined);
+ const project =
+ isDefined(appPathStats) && appPathStats.isDirectory()
+ ? await readAppProject(appPath)
+ : undefined;
+
+ if (!isDefined(project)) {
+ throw new CliError({
+ code: 'APP_NOT_FOUND',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${appPath} is not a Twenty app: it needs a package.json that depends on twenty-sdk.`,
+ details: { path: appPath },
+ });
+ }
+
+ return project;
+ }
+
+ const enclosingProject = await findEnclosingAppProject(workingDirectory);
+
+ if (isDefined(enclosingProject)) {
+ return enclosingProject;
+ }
+
+ const candidates = await findChildAppProjects(workingDirectory);
+ const candidatePaths = candidates.map(
+ (candidate) => `./${relative(workingDirectory, candidate.path)}`,
+ );
+
+ if (candidates.length > 1) {
+ throw new CliError({
+ code: 'APP_PATH_REQUIRED',
+ exitCode: EXIT_CODE.USAGE,
+ message: `This folder contains ${candidates.length} apps. Choose one with --path.`,
+ hint: `Apps here: ${candidatePaths.join(', ')}`,
+ details: { candidates: candidates.map((candidate) => candidate.path) },
+ });
+ }
+
+ throw new CliError({
+ code: 'APP_NOT_FOUND',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'No Twenty app found in this folder or its parents.',
+ hint:
+ candidates.length === 1
+ ? `Pass --path ${candidatePaths[0]}`
+ : 'Run the command inside an app, or pass --path <app directory>.',
+ details: { workingDirectory },
+ });
+};
diff --git a/packages/twenty-cli/src/app/project/resolve-inside-sdk.ts b/packages/twenty-cli/src/app/project/resolve-inside-sdk.ts
new file mode 100644
index 00000000000..619a5786d98
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/resolve-inside-sdk.ts
@@ -0,0 +1,33 @@
+import { realpathSync } from 'node:fs';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { isInsideDirectory } from '@/utils/is-inside-directory';
+
+const tryResolve = (
+ resolveFromApp: NodeJS.RequireResolve,
+ specifier: string,
+) => {
+ try {
+ return realpathSync(resolveFromApp(specifier));
+ } catch {
+ return undefined;
+ }
+};
+
+export const resolveInsideSdk = ({
+ resolveFromApp,
+ specifier,
+ sdkPath,
+}: {
+ resolveFromApp: NodeJS.RequireResolve;
+ specifier: string;
+ sdkPath: string;
+}) => {
+ const resolvedPath = tryResolve(resolveFromApp, specifier);
+
+ return isDefined(resolvedPath) &&
+ isInsideDirectory({ filePath: resolvedPath, directory: sdkPath })
+ ? resolvedPath
+ : undefined;
+};
diff --git a/packages/twenty-cli/src/app/project/resolve-installed-sdk.ts b/packages/twenty-cli/src/app/project/resolve-installed-sdk.ts
new file mode 100644
index 00000000000..7e6761a484a
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/resolve-installed-sdk.ts
@@ -0,0 +1,61 @@
+import { realpath } from 'node:fs/promises';
+import { join } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { hasYarnPlugAndPlay } from '@/app/project/has-yarn-plug-and-play';
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+import { readJsonObject } from '@/app/read-json-object';
+import { pathExists } from '@/app/fs-utils';
+import { CliError } from '@/output/cli-error';
+
+const findInstalledSdk = async (appPath: string) => {
+ for (const directory of listAncestorDirectories(appPath)) {
+ const packagePath = join(directory, 'node_modules', 'twenty-sdk');
+ const isInstalled = await pathExists(packagePath);
+
+ if (!isInstalled) {
+ continue;
+ }
+
+ const packageJson = await readJsonObject(join(packagePath, 'package.json'));
+
+ if (!isDefined(packageJson) || packageJson.name !== 'twenty-sdk') {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message: `The twenty-sdk installation at ${packagePath} is incomplete: it has no readable twenty-sdk package.json.`,
+ hint: "Reinstall the app's dependencies (for example with yarn install), then try again.",
+ details: { appPath, sdkPath: packagePath },
+ });
+ }
+
+ return { path: await realpath(packagePath), packageJson };
+ }
+
+ return undefined;
+};
+
+const throwMissingSdk = async (appPath: string): Promise<never> => {
+ if (await hasYarnPlugAndPlay(appPath)) {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message:
+ "This app uses Yarn Plug'n'Play, which the twenty CLI cannot load the SDK from.",
+ hint: 'Set nodeLinker: node-modules in .yarnrc.yml, then run yarn install.',
+ details: { appPath },
+ });
+ }
+
+ throw new CliError({
+ code: 'SDK_NOT_INSTALLED',
+ message: 'twenty-sdk is not installed for this app.',
+ hint: "Install the app's dependencies (for example with yarn install), then try again.",
+ details: { appPath },
+ });
+};
+
+export const resolveInstalledSdk = async (appPath: string) => {
+ const sdk = await findInstalledSdk(appPath);
+
+ return isDefined(sdk) ? sdk : throwMissingSdk(appPath);
+};
diff --git a/packages/twenty-cli/src/app/project/resolve-source-sdk.ts b/packages/twenty-cli/src/app/project/resolve-source-sdk.ts
new file mode 100644
index 00000000000..162d2edd845
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/resolve-source-sdk.ts
@@ -0,0 +1,75 @@
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import satisfies from 'semver/functions/satisfies';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { checkNodeRequirement } from '@/app/project/check-node-requirement';
+import { resolveInstalledSdk } from '@/app/project/resolve-installed-sdk';
+import { resolveInsideSdk } from '@/app/project/resolve-inside-sdk';
+import { CliError } from '@/output/cli-error';
+
+const SOURCE_SDK_RANGE = '>=1.23.0';
+const SOURCE_ENTRY_POINTS = ['twenty-sdk/define', 'twenty-sdk/front-component'];
+
+export const resolveSourceSdk = async ({ appPath }: { appPath: string }) => {
+ const sdk = await resolveInstalledSdk(appPath);
+ const version = isString(sdk.packageJson.version)
+ ? sdk.packageJson.version
+ : 'unknown';
+ const details = { appPath, sdkPath: sdk.path, sdkVersion: version };
+ const resolveFromApp = createRequire(join(appPath, 'package.json')).resolve;
+ const missingEntryPoints = SOURCE_ENTRY_POINTS.filter(
+ (specifier) =>
+ !isDefined(
+ resolveInsideSdk({ resolveFromApp, specifier, sdkPath: sdk.path }),
+ ),
+ );
+
+ if (
+ !satisfies(version, SOURCE_SDK_RANGE, { includePrerelease: true }) ||
+ missingEntryPoints.length > 0
+ ) {
+ throw new CliError({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ message: `twenty-sdk ${version} cannot load app source with this CLI. Source loading needs twenty-sdk ${SOURCE_SDK_RANGE} with its define and front-component entry points.`,
+ hint: 'Install a compatible twenty-sdk version in this app.',
+ details: {
+ ...details,
+ supportedRange: SOURCE_SDK_RANGE,
+ missingEntryPoints,
+ },
+ });
+ }
+
+ const requiredNode = isPlainObject(sdk.packageJson.engines)
+ ? sdk.packageJson.engines.node
+ : undefined;
+
+ if (isDefined(requiredNode)) {
+ const requirement = isString(requiredNode)
+ ? checkNodeRequirement({
+ version: process.versions.node,
+ range: requiredNode,
+ })
+ : 'invalid';
+
+ if (requirement !== 'satisfied') {
+ throw new CliError({
+ code:
+ requirement === 'invalid'
+ ? 'SDK_SOURCE_UNSUPPORTED'
+ : 'NODE_VERSION_UNSUPPORTED',
+ message: `twenty-sdk ${version} declares Node ${String(requiredNode)}; this is Node ${process.versions.node}.`,
+ hint:
+ requirement === 'invalid'
+ ? 'Install a twenty-sdk version with a valid Node requirement.'
+ : 'Switch to a supported Node version, then try again.',
+ details: { ...details, requiredNode },
+ });
+ }
+ }
+
+ return { version, packagePath: sdk.path };
+};
diff --git a/packages/twenty-cli/src/app/project/types/app-project.type.ts b/packages/twenty-cli/src/app/project/types/app-project.type.ts
new file mode 100644
index 00000000000..0f105ec4a66
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/types/app-project.type.ts
@@ -0,0 +1,4 @@
+export type AppProject = {
+ path: string;
+ name: string;
+};
diff --git a/packages/twenty-cli/src/app/project/types/project-sdk.type.ts b/packages/twenty-cli/src/app/project/types/project-sdk.type.ts
new file mode 100644
index 00000000000..c8de3b23cad
--- /dev/null
+++ b/packages/twenty-cli/src/app/project/types/project-sdk.type.ts
@@ -0,0 +1,4 @@
+export type ProjectSdk = {
+ version: string;
+ packagePath: string;
+};
diff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.md
new file mode 100644
index 00000000000..b1169bbb60b
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/README.md
@@ -0,0 +1,28 @@
+# CLI application pull
+
+Pull reconciles the server's application export with local definitions and a
+target-bound baseline. It preserves unsupported and local-only entities, reports
+overwritten local edits, and commits source changes and the new baseline as one
+transaction. Source generation and translation behavior are covered by parity
+and reconciliation tests.
+
+See the [app tooling overview](../README.md) for package boundaries.
+
+## Contract
+
+- Source scanning stays inside the disposable CLI worker so configs containing functions are never serialized through IPC. Only the server export and report cross that boundary. Selected credentials are removed from the worker environment. App source is trusted developer code, not sandboxed code.
+- The wire/export and baseline boundary check identity and envelope fields, not every metadata collection. `toPullManifest` is the single explicit assertion into the typed writers, preserving their trust in the server schema. Missing/null object and field collections are consumed with `?? []`, like the other collections. Malformed entity contents can still make reconciliation fail before writing. We do not duplicate the server's schema.
+- The baseline file is an envelope whose `manifest` member is an `ExportedManifest`. Reconciliation walks arrays generically without maintaining a second collection list. Unrecognized collections and non-array metadata survive; protected or unreconciled definitions retain their prior baseline entries.
+- `preparePullEntities` resolves the source layout once for current and baseline entities. Planning, overwrite reporting and nested-definition protection consume these prepared entities. A definition can leave a parent only when another retained or written file contains it, or its remote deletion is confirmed.
+- Fields already declared with `defineField` stay in their existing files, even when the server exports them inside an object. Object generation excludes those fields; baseline comparisons use the same source layout. Pull also removes duplicate inline copies left in object files, while retaining the standalone definitions.
+- Before destination writes, `assertPullSdkExports` checks the actual imports emitted by the writer against the app's SDK. It checks export presence, not every config shape; run typecheck to validate the generated definitions against the installed SDK.
+- Temporary files and the baseline live under `.twenty/cli`. Apply and pull share `createPullBaseWrite` as the serializer. The baseline is bound to the API URL, workspace UUID and application UUID. Pull stages it with mode 0600 and writes it after the source files.
+- The baseline can carry `sourceFingerprints`, a SHA-256 per app-relative source and locale file. Apply captures them before building. Pull reports an overwritten local change when a file it rewrites or deletes no longer matches its fingerprint. Without a fingerprint it compares the file with the writer's rendering of the baseline, which is reliable only for source produced by that writer. Pull carries fingerprints forward, updating the files it writes and dropping the ones it deletes.
+- Ordinary I/O failures restore originals. Cancellation is checked before committing the staged plan, not halfway through it. An acknowledged successful commit wins over cancellation. The parent can forcibly kill an unresponsive worker after its grace period, so an unacknowledged result has outcome `unknown`, never a claim that rollback succeeded. Failed rollback retains backups and reports their directory; failure to clean up after a completed commit has outcome `pulled`.
+- Human reporting uses CLI terminal escaping, machine reporting contains the full coverage and path lists, and gaps warn without stopping successful writes. Unknown coverage status strings remain visible. Pull does not prompt for approval or require a clean Git checkout; remote changes overwrite conflicting local edits and are included in the report.
+
+Translation string extraction uses the CLI's TypeScript parser. Traversal, static-string rules, whitespace normalization and deduplication are checked against the SDK reference by parity tests. It does not depend on ts-morph or load parser tooling for help and command discovery.
+
+Pull accepts metadata exports with `files: []` and refuses nonempty source/dependency-file exports. It does not restore package files, generate the typed client or write logic-function/front-component source. Export responses have a 16 MiB cap. Pull does not modify the workspace.
+
+Tests cover writers, planning and reconciliation. Command tests build the actual Vite worker, exercise an authoring-only SDK, local mock HTTP, credentials/output isolation, SDK export refusal and forced termination after the first destination write. The repository SDK tests cover canonical generated definitions, nested coverage, translation preservation, target mismatch, overwrite reporting and rollback.
diff --git a/packages/twenty-cli/src/app/pull/__tests__/apply-pull-writes.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/apply-pull-writes.spec.ts
new file mode 100644
index 00000000000..f7d778cbdd1
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/apply-pull-writes.spec.ts
@@ -0,0 +1,191 @@
+import { applyPullWrites } from '@/app/pull/apply-pull-writes';
+import { type PullWrite } from '@/app/pull/plan-pull-writes';
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const buildWrite = (relativePath: string, content: string): PullWrite => ({
+ kind: 'object',
+ universalIdentifier: relativePath,
+ relativePath,
+ content,
+ isRegeneration: false,
+ requiredSdkExports: [],
+});
+
+describe('applyPullWrites', () => {
+ let appPath: string;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'apply-pull-writes-'));
+ });
+
+ afterEach(async () => {
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ const readAppFile = (relativePath: string) =>
+ readFile(join(appPath, relativePath), 'utf-8');
+
+ it('should write the planned files and delete the planned ones', async () => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(join(appPath, 'src/gone.ts'), 'previous');
+
+ await applyPullWrites({
+ appPath,
+ writes: [buildWrite('src/pet.object.ts', 'written')],
+ deletions: [{ universalIdentifier: 'gone', relativePath: 'src/gone.ts' }],
+ });
+
+ expect(await readAppFile('src/pet.object.ts')).toBe('written');
+ await expect(readAppFile('src/gone.ts')).rejects.toThrow();
+ });
+
+ it('should leave no working directory behind', async () => {
+ await applyPullWrites({
+ appPath,
+ writes: [buildWrite('src/pet.object.ts', 'written')],
+ deletions: [],
+ });
+
+ const workDirectoryEntries = await readdir(join(appPath, '.twenty'));
+
+ expect(
+ workDirectoryEntries.filter((entry) =>
+ /^pull-(staging|backup)-/.test(entry),
+ ),
+ ).toEqual([]);
+ });
+
+ it('should restore every file it had already replaced when a later write fails', async () => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(join(appPath, 'src/first.ts'), 'original first');
+ await writeFile(join(appPath, 'src/second.ts'), 'original second');
+ await writeFile(
+ join(appPath, 'src/nested'),
+ 'a file where a folder is needed',
+ );
+
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [
+ buildWrite('src/first.ts', 'new first'),
+ buildWrite('src/second.ts', 'new second'),
+ buildWrite('src/nested/deep.object.ts', 'never lands'),
+ ],
+ deletions: [],
+ }),
+ ).rejects.toThrow();
+
+ expect(await readAppFile('src/first.ts')).toBe('original first');
+ expect(await readAppFile('src/second.ts')).toBe('original second');
+ });
+
+ it('should put back a file it had already deleted when a later step fails', async () => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(join(appPath, 'src/kept.ts'), 'original kept');
+ await writeFile(
+ join(appPath, 'src/nested'),
+ 'a file where a folder is needed',
+ );
+
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [
+ buildWrite('src/kept.ts', 'new kept'),
+ buildWrite('src/nested/deep.object.ts', 'never lands'),
+ ],
+ deletions: [],
+ }),
+ ).rejects.toThrow();
+
+ expect(await readAppFile('src/kept.ts')).toBe('original kept');
+ });
+
+ it('should remove a new file it created when a later write fails', async () => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(
+ join(appPath, 'src/nested'),
+ 'a file where a folder is needed',
+ );
+
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [
+ buildWrite('src/brand-new.object.ts', 'new content'),
+ buildWrite('src/nested/deep.object.ts', 'never lands'),
+ ],
+ deletions: [],
+ }),
+ ).rejects.toThrow();
+
+ await expect(readAppFile('src/brand-new.object.ts')).rejects.toThrow();
+ });
+
+ it('should refuse a plan whose two entities resolve to the same file', async () => {
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [
+ buildWrite('src/pet.object.ts', 'one'),
+ buildWrite('src/pet.object.ts', 'two'),
+ ],
+ deletions: [],
+ }),
+ ).rejects.toThrow('same file path');
+ });
+
+ it('should refuse a plan that leaves the application directory', async () => {
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [
+ buildWrite('my-dir/../../.../../../whatever.ts', 'export default 1;'),
+ ],
+ deletions: [],
+ }),
+ ).rejects.toThrow('leaves the application directory');
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [],
+ deletions: [
+ { universalIdentifier: 'x', relativePath: 'src/../../escape.ts' },
+ ],
+ }),
+ ).rejects.toThrow('leaves the application directory');
+ });
+
+ it('should accept a folder whose name is only dots', async () => {
+ await applyPullWrites({
+ appPath,
+ writes: [buildWrite('.../kept.ts', 'export default 1;')],
+ deletions: [],
+ });
+
+ expect(await readAppFile('.../kept.ts')).toBe('export default 1;');
+ });
+
+ it('should refuse to delete a folder standing where a planned file goes', async () => {
+ await mkdir(join(appPath, 'src/pet.object.ts'), { recursive: true });
+
+ await expect(
+ applyPullWrites({
+ appPath,
+ writes: [buildWrite('src/pet.object.ts', 'written')],
+ deletions: [],
+ }),
+ ).rejects.toThrow('never deletes a folder');
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/assert-pull-sdk-exports.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/assert-pull-sdk-exports.spec.ts
new file mode 100644
index 00000000000..b490a5defb2
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/assert-pull-sdk-exports.spec.ts
@@ -0,0 +1,80 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+import { PageLayoutTabLayoutMode, WidgetType } from 'twenty-shared/types';
+
+import { assertPullSdkExports } from '@/app/pull/assert-pull-sdk-exports';
+import {
+ PAGE_LAYOUT_WIDGET_ENUM_BINDINGS,
+ writeDefineFile,
+} from '@/app/pull/write-define-file';
+
+const appPaths: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ appPaths
+ .splice(0)
+ .map((appPath) => rm(appPath, { recursive: true, force: true })),
+ );
+});
+
+describe('SDK exports required by generated source', () => {
+ it.each([false, true])(
+ 'checks imports emitted by the writer, wrapped: %s',
+ async (wrapped) => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-pull-sdk-'));
+ appPaths.push(appPath);
+ const sdkPath = join(appPath, 'node_modules/twenty-sdk');
+ await mkdir(sdkPath, { recursive: true });
+ await writeFile(join(appPath, 'package.json'), '{}');
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ exports: { './define': './define.cjs' },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'define.cjs'),
+ 'exports.definePageLayoutWidget = () => {}; exports.WidgetType = {};',
+ );
+
+ const { content, requiredSdkExports } = writeDefineFile(
+ wrapped
+ ? {
+ definer: 'definePageLayoutWidget',
+ config: {
+ type: WidgetType.GRAPH,
+ position: { layoutMode: PageLayoutTabLayoutMode.GRID },
+ },
+ enumBindings: PAGE_LAYOUT_WIDGET_ENUM_BINDINGS,
+ }
+ : { definer: 'defineApplication', config: {} },
+ );
+ expect(content.startsWith('import {\n')).toBe(wrapped);
+ try {
+ assertPullSdkExports({
+ appPath,
+ writes: [
+ {
+ requiredSdkExports,
+ },
+ ],
+ });
+ expect.fail('Expected a missing authoring export');
+ } catch (error) {
+ expect(error).toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ details: {
+ missingNames: [
+ wrapped ? 'PageLayoutTabLayoutMode' : 'defineApplication',
+ ],
+ },
+ });
+ }
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/build-manifest-entity-label-by-universal-identifier.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/build-manifest-entity-label-by-universal-identifier.spec.ts
new file mode 100644
index 00000000000..549bab3b067
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/build-manifest-entity-label-by-universal-identifier.spec.ts
@@ -0,0 +1,102 @@
+import { buildManifestEntityLabelByUniversalIdentifier } from '@/app/pull/build-manifest-entity-label-by-universal-identifier';
+import { describe, expect, it } from 'vitest';
+
+describe('buildManifestEntityLabelByUniversalIdentifier', () => {
+ it('should qualify a nested entity with the labels of its parents', () => {
+ expect(
+ buildManifestEntityLabelByUniversalIdentifier({
+ objects: [
+ {
+ universalIdentifier: 'ticket-identifier',
+ nameSingular: 'ticket',
+ namePlural: 'tickets',
+ fields: [
+ { universalIdentifier: 'labels-identifier', name: 'labels' },
+ ],
+ },
+ ],
+ pageLayouts: [
+ {
+ universalIdentifier: 'layout-identifier',
+ name: 'Dashboard',
+ tabs: [
+ {
+ universalIdentifier: 'tab-identifier',
+ title: 'Overview',
+ widgets: [
+ {
+ universalIdentifier: 'widget-identifier',
+ title: 'Runbook',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ roles: [{ universalIdentifier: 'role-identifier', label: 'Recruiter' }],
+ }),
+ ).toEqual({
+ 'ticket-identifier': 'ticket',
+ 'labels-identifier': 'ticket.labels',
+ 'layout-identifier': 'Dashboard',
+ 'tab-identifier': 'Dashboard.Overview',
+ 'widget-identifier': 'Dashboard.Overview.Runbook',
+ 'role-identifier': 'Recruiter',
+ });
+ });
+
+ it('should leave out an entity that carries no label of its own', () => {
+ expect(
+ buildManifestEntityLabelByUniversalIdentifier({
+ application: {
+ universalIdentifier: 'application-identifier',
+ displayName: 'Custom',
+ },
+ views: [
+ {
+ universalIdentifier: 'view-identifier',
+ name: 'Open tickets',
+ fields: [
+ {
+ universalIdentifier: 'view-field-identifier',
+ fieldMetadataUniversalIdentifier: 'labels-identifier',
+ },
+ ],
+ },
+ ],
+ }),
+ ).toEqual({ 'view-identifier': 'Open tickets' });
+ });
+
+ it('should never register the labelled entries of a JSON value', () => {
+ expect(
+ buildManifestEntityLabelByUniversalIdentifier({
+ fields: [
+ {
+ universalIdentifier: 'priority-identifier',
+ name: 'priority',
+ options: [{ id: 'option-id', label: 'High', value: 'HIGH' }],
+ defaultValue: { name: 'ignored' },
+ },
+ ],
+ }),
+ ).toEqual({ 'priority-identifier': 'priority' });
+ });
+ it('handles deeply nested JSON payloads without overflowing the call stack', () => {
+ let payload: unknown = 'value';
+ for (let depth = 0; depth < 15000; depth += 1)
+ payload = { nested: payload };
+
+ expect(
+ buildManifestEntityLabelByUniversalIdentifier({
+ fields: [
+ {
+ universalIdentifier: 'field',
+ name: 'payload',
+ defaultValue: payload,
+ },
+ ],
+ }),
+ ).toEqual({ field: 'payload' });
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts
new file mode 100644
index 00000000000..ed4cedfcacd
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts
@@ -0,0 +1,1153 @@
+import { buildPullEntities } from '@/app/pull/build-pull-entities';
+import {
+ NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ PAGE_LAYOUT_ENUM_BINDINGS,
+ PAGE_LAYOUT_TAB_ENUM_BINDINGS,
+ ROLE_ENUM_BINDINGS,
+ VIEW_ENUM_BINDINGS,
+ VIEW_FIELD_ENUM_BINDINGS,
+} from '@/app/pull/write-define-file';
+import {
+ getFieldPermissionUniversalIdentifier,
+ getObjectPermissionUniversalIdentifier,
+ getSystemRecordPageLayoutUniversalIdentifier,
+ getSystemViewUniversalIdentifier,
+ type Manifest,
+ type NavigationMenuItemManifest,
+ type PageLayoutManifest,
+ type PageLayoutTabManifest,
+ type StandaloneViewFieldManifest,
+ SYSTEM_VIEW_KEYS,
+ type ViewManifest,
+} from 'twenty-shared/application';
+import {
+ STANDARD_OBJECT_FIELDS,
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
+ STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS,
+} from 'twenty-shared/metadata';
+import {
+ AggregateOperations,
+ NavigationMenuItemType,
+ PageLayoutTabLayoutMode,
+ PageLayoutType,
+ WidgetType,
+ ViewSortDirection,
+ ViewType,
+} from 'twenty-shared/types';
+import { describe, expect, it } from 'vitest';
+
+const APP_UID = '11111111-1111-4111-8111-111111111111';
+const PET_UID = '22222222-2222-4222-8222-222222222222';
+const PET_NAME_FIELD_UID = '33333333-3333-4333-8333-333333333333';
+const COMPANY_FIELD_UID = '44444444-4444-4444-8444-444444444444';
+const INDEX_UID = '55555555-5555-4555-8555-555555555555';
+const JUNCTION_UID = '66666666-6666-4666-8666-666666666666';
+const JUNCTION_ID_FIELD_UID = '77777777-7777-4777-8777-777777777777';
+const VIEW_UID = '88888888-8888-4888-8888-888888888888';
+const VIEW_FIELD_UID = '99999999-9999-4999-8999-999999999999';
+const VIEW_SORT_UID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const INLINE_VIEW_FIELD_UID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const PAGE_LAYOUT_UID = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const PAGE_LAYOUT_TAB_UID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+const WIDGET_UID = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
+const STANDALONE_TAB_UID = 'ffffffff-ffff-4fff-8fff-ffffffffffff';
+const NAVIGATION_MENU_ITEM_UID = '10101010-1010-4010-8010-101010101010';
+const NAVIGATION_FOLDER_UID = '20202020-2020-4020-8020-202020202020';
+const SUPPORT_ROLE_UID = '30303030-3030-4303-8303-303030303030';
+const AUDITOR_ROLE_UID = '40404040-4040-4404-8404-404040404040';
+const EXPORT_PETS_FLAG_UID = '50505050-5050-4505-8505-505050505050';
+const LEGACY_OBJECT_PERMISSION_UID = '60606060-6060-4606-8606-606060606060';
+
+const APPLICATION_WITH_SUPPORT_DEFAULT_ROLE = {
+ universalIdentifier: APP_UID,
+ displayName: 'Pets',
+ description: 'Pet tracking',
+ defaultRoleUniversalIdentifier: SUPPORT_ROLE_UID,
+};
+
+const buildManifest = (overrides: Partial<Manifest> = {}): Manifest =>
+ ({
+ application: {
+ universalIdentifier: APP_UID,
+ displayName: 'Pets',
+ description: 'Pet tracking',
+ defaultRoleUniversalIdentifier: 'role-uid',
+ packageJsonChecksum: 'package-checksum',
+ yarnLockChecksum: 'lock-checksum',
+ },
+ objects: [
+ {
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ namePlural: 'pets',
+ labelSingular: 'Pet',
+ labelPlural: 'Pets',
+ labelIdentifierFieldMetadataUniversalIdentifier: PET_NAME_FIELD_UID,
+ fields: [
+ {
+ universalIdentifier: PET_NAME_FIELD_UID,
+ name: 'name',
+ label: 'Name',
+ type: 'TEXT',
+ writability: 'OPEN',
+ },
+ ],
+ },
+ ],
+ fields: [
+ {
+ universalIdentifier: COMPANY_FIELD_UID,
+ name: 'caredForPets',
+ label: 'Cared for pets',
+ type: 'TEXT',
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company,
+ },
+ ],
+ indexes: [],
+ ...overrides,
+ }) as unknown as Manifest;
+
+const buildViewManifest = (
+ overrides: Partial<ViewManifest> = {},
+): ViewManifest => ({
+ universalIdentifier: VIEW_UID,
+ name: 'All pets',
+ objectUniversalIdentifier: PET_UID,
+ type: ViewType.TABLE,
+ kanbanAggregateOperation: AggregateOperations.COUNT,
+ fields: [
+ {
+ universalIdentifier: INLINE_VIEW_FIELD_UID,
+ fieldMetadataUniversalIdentifier: PET_NAME_FIELD_UID,
+ position: 0,
+ aggregateOperation: AggregateOperations.COUNT,
+ },
+ ],
+ sorts: [
+ {
+ universalIdentifier: VIEW_SORT_UID,
+ fieldMetadataUniversalIdentifier: PET_NAME_FIELD_UID,
+ direction: ViewSortDirection.ASC,
+ },
+ ],
+ ...overrides,
+});
+
+const buildViewFieldManifest = (
+ overrides: Partial<StandaloneViewFieldManifest> = {},
+): StandaloneViewFieldManifest => ({
+ universalIdentifier: VIEW_FIELD_UID,
+ viewUniversalIdentifier: VIEW_UID,
+ fieldMetadataUniversalIdentifier: PET_NAME_FIELD_UID,
+ position: 1,
+ aggregateOperation: AggregateOperations.COUNT,
+ ...overrides,
+});
+
+const buildPageLayoutManifest = (
+ overrides: Partial<PageLayoutManifest> = {},
+): PageLayoutManifest => ({
+ universalIdentifier: PAGE_LAYOUT_UID,
+ name: 'Pet page',
+ type: PageLayoutType.RECORD_PAGE,
+ objectUniversalIdentifier: PET_UID,
+ tabs: [
+ {
+ universalIdentifier: PAGE_LAYOUT_TAB_UID,
+ title: 'Overview',
+ position: 0,
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ widgets: [
+ {
+ universalIdentifier: WIDGET_UID,
+ title: 'Notes',
+ type: WidgetType.NOTES,
+ objectUniversalIdentifier: PET_UID,
+ position: {
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ index: 0,
+ },
+ configuration: { configurationType: 'NOTES' },
+ },
+ ],
+ },
+ ],
+ ...overrides,
+});
+
+const buildPageLayoutTabManifest = (
+ overrides: Partial<PageLayoutTabManifest> = {},
+): PageLayoutTabManifest => ({
+ universalIdentifier: STANDALONE_TAB_UID,
+ pageLayoutUniversalIdentifier:
+ STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS.companyRecordPage
+ .universalIdentifier,
+ title: 'Extra',
+ position: 60,
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ ...overrides,
+});
+
+const buildNavigationMenuItemManifest = (
+ overrides: Partial<NavigationMenuItemManifest> = {},
+): NavigationMenuItemManifest => ({
+ universalIdentifier: NAVIGATION_MENU_ITEM_UID,
+ type: NavigationMenuItemType.OBJECT,
+ position: 8,
+ targetObjectUniversalIdentifier: PET_UID,
+ ...overrides,
+});
+
+describe('buildPullEntities', () => {
+ it('should strip the checksums the build recomputes from the application config', () => {
+ const { entities } = buildPullEntities(buildManifest());
+ const application = entities.find(
+ (entity) => entity.kind === 'application',
+ );
+
+ expect(application?.config).toEqual({
+ universalIdentifier: APP_UID,
+ displayName: 'Pets',
+ description: 'Pet tracking',
+ defaultRoleUniversalIdentifier: 'role-uid',
+ });
+ expect(
+ `${application?.defaultFolder}/${application?.fileBaseName}${application?.fileSuffix}`,
+ ).toBe('src/application.config.ts');
+ });
+
+ it('should write an object verbatim, keeping its name field and label identifier', () => {
+ const manifest = buildManifest();
+ const { entities } = buildPullEntities(manifest);
+ const object = entities.find((entity) => entity.kind === 'object');
+
+ expect(object?.config).toEqual(manifest.objects[0]);
+ expect(
+ `${object?.defaultFolder}/${object?.fileBaseName}${object?.fileSuffix}`,
+ ).toBe('src/objects/pet.object.ts');
+ });
+
+ it('should name a field on a standard object after that object', () => {
+ const { entities } = buildPullEntities(buildManifest());
+ const field = entities.find((entity) => entity.kind === 'field');
+
+ expect(
+ `${field?.defaultFolder}/${field?.fileBaseName}${field?.fileSuffix}`,
+ ).toBe('src/fields/company-cared-for-pets.field.ts');
+ });
+
+ it('should name an index after its object and fields', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ indexes: [
+ {
+ universalIdentifier: INDEX_UID,
+ objectUniversalIdentifier: PET_UID,
+ fields: [{ fieldUniversalIdentifier: PET_NAME_FIELD_UID }],
+ },
+ ],
+ } as unknown as Partial<Manifest>),
+ );
+ const index = entities.find((entity) => entity.kind === 'index');
+
+ expect(
+ `${index?.defaultFolder}/${index?.fileBaseName}${index?.fileSuffix}`,
+ ).toBe('src/indexes/pet-name.index.ts');
+ });
+
+ it('should write an object whose label identifier names an engine-derived field, keeping the pointer', () => {
+ const junctionObject = {
+ universalIdentifier: JUNCTION_UID,
+ nameSingular: 'petCareAgreement',
+ namePlural: 'petCareAgreements',
+ labelSingular: 'Pet care agreement',
+ labelPlural: 'Pet care agreements',
+ labelIdentifierFieldMetadataUniversalIdentifier: JUNCTION_ID_FIELD_UID,
+ fields: [
+ {
+ universalIdentifier: 'relation-field-uid',
+ name: 'pet',
+ label: 'Pet',
+ type: 'RELATION',
+ },
+ ],
+ };
+
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ objects: [junctionObject],
+ } as unknown as Partial<Manifest>),
+ );
+ const object = entities.find((entity) => entity.kind === 'object');
+
+ expect(skipped).toEqual([]);
+ expect(object?.config).toEqual(junctionObject);
+ });
+
+ it('should skip an index whose object is not part of the export', () => {
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ objects: [],
+ indexes: [
+ {
+ universalIdentifier: INDEX_UID,
+ objectUniversalIdentifier: 'an-object-of-another-application',
+ fields: [{ fieldUniversalIdentifier: 'unknown-field' }],
+ },
+ ],
+ } as unknown as Partial<Manifest>),
+ );
+
+ expect(entities.some((entity) => entity.kind === 'index')).toBe(false);
+ expect(
+ skipped.find((entry) => entry.universalIdentifier === INDEX_UID)?.reason,
+ ).toBe('its object is not part of the written source');
+ });
+
+ it('should write a view verbatim into src/views with the view enum bindings and its object as parent', () => {
+ const viewManifest = buildViewManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ views: [viewManifest] }),
+ );
+ const view = entities.find((entity) => entity.kind === 'view');
+
+ expect(skipped).toEqual([]);
+ expect(view?.universalIdentifier).toBe(VIEW_UID);
+ expect(view?.definer).toBe('defineView');
+ expect(view?.config).toEqual(viewManifest);
+ expect(view?.enumBindings).toEqual(VIEW_ENUM_BINDINGS);
+ expect(view?.parentName).toBe('pet');
+ expect(
+ `${view?.defaultFolder}/${view?.fileBaseName}${view?.fileSuffix}`,
+ ).toBe('src/views/all-pets.view.ts');
+ });
+
+ it('should give a view on a standard object that object as parent', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [
+ buildViewManifest({
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person,
+ }),
+ ],
+ }),
+ );
+ const view = entities.find((entity) => entity.kind === 'view');
+
+ expect(view?.parentName).toBe('person');
+ });
+
+ it('should name a view whose name has no kebab-case form after its identifier prefix', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({ views: [buildViewManifest({ name: '!!!' })] }),
+ );
+ const view = entities.find((entity) => entity.kind === 'view');
+
+ expect(view?.fileBaseName).toBe('88888888');
+ });
+
+ it('should cap the file name of a view with an overlong name', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [
+ buildViewManifest({ name: `${'Ab'.repeat(39)} ${'c'.repeat(300)}` }),
+ ],
+ }),
+ );
+ const view = entities.find((entity) => entity.kind === 'view');
+
+ expect(view?.fileBaseName).toBe(`${'ab-'.repeat(26)}ab`);
+ expect(view?.fileBaseName).toHaveLength(80);
+ });
+
+ it('should write a standalone view field into src/view-fields named after the manifest object and field it points to', () => {
+ const viewFieldManifest = buildViewFieldManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ views: [buildViewManifest()],
+ viewFields: [viewFieldManifest],
+ }),
+ );
+ const viewField = entities.find((entity) => entity.kind === 'viewField');
+
+ expect(skipped).toEqual([]);
+ expect(viewField?.universalIdentifier).toBe(VIEW_FIELD_UID);
+ expect(viewField?.definer).toBe('defineViewField');
+ expect(viewField?.config).toEqual(viewFieldManifest);
+ expect(viewField?.enumBindings).toEqual(VIEW_FIELD_ENUM_BINDINGS);
+ expect(viewField?.parentName).toBeNull();
+ expect(
+ `${viewField?.defaultFolder}/${viewField?.fileBaseName}${viewField?.fileSuffix}`,
+ ).toBe('src/view-fields/pet-name.view-field.ts');
+ });
+
+ it('should name a standalone view field pointing at a manifest field on a standard object after that object', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [buildViewManifest()],
+ viewFields: [
+ buildViewFieldManifest({
+ fieldMetadataUniversalIdentifier: COMPANY_FIELD_UID,
+ }),
+ ],
+ }),
+ );
+ const viewField = entities.find((entity) => entity.kind === 'viewField');
+
+ expect(viewField?.fileBaseName).toBe('company-cared-for-pets');
+ });
+
+ it('should name a standalone view field pointing at a standard field after the standard object and field', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [buildViewManifest()],
+ viewFields: [
+ buildViewFieldManifest({
+ fieldMetadataUniversalIdentifier:
+ STANDARD_OBJECT_FIELDS.person.jobTitle.universalIdentifier,
+ }),
+ ],
+ }),
+ );
+ const viewField = entities.find((entity) => entity.kind === 'viewField');
+
+ expect(viewField?.fileBaseName).toBe('person-job-title');
+ });
+
+ it('should name a standalone view field pointing at an unknown field after its identifier prefix', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [buildViewManifest()],
+ viewFields: [
+ buildViewFieldManifest({
+ fieldMetadataUniversalIdentifier: 'a-field-of-another-application',
+ }),
+ ],
+ }),
+ );
+ const viewField = entities.find((entity) => entity.kind === 'viewField');
+
+ expect(viewField?.fileBaseName).toBe('99999999');
+ });
+
+ it('should write a page layout verbatim into src/page-layouts with the page layout enum bindings and its object as parent', () => {
+ const pageLayoutManifest = buildPageLayoutManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ pageLayouts: [pageLayoutManifest] }),
+ );
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+
+ expect(skipped).toEqual([]);
+ expect(pageLayout?.universalIdentifier).toBe(PAGE_LAYOUT_UID);
+ expect(pageLayout?.definer).toBe('definePageLayout');
+ expect(pageLayout?.config).toEqual(pageLayoutManifest);
+ expect(pageLayout?.enumBindings).toEqual(PAGE_LAYOUT_ENUM_BINDINGS);
+ expect(pageLayout?.parentName).toBe('pet');
+ expect(
+ `${pageLayout?.defaultFolder}/${pageLayout?.fileBaseName}${pageLayout?.fileSuffix}`,
+ ).toBe('src/page-layouts/pet-page.page-layout.ts');
+ });
+
+ it('should drop the GraphQL typename keys a widget configuration saved from the UI carries', () => {
+ const pageLayoutManifest = buildPageLayoutManifest();
+ const widgetWithTypename = {
+ ...pageLayoutManifest.tabs![0].widgets![0],
+ configuration: {
+ __typename: 'RecordTableConfiguration',
+ configurationType: 'RECORD_TABLE',
+ recordLimit: null,
+ viewUniversalIdentifier: VIEW_UID,
+ },
+ };
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayouts: [
+ {
+ ...pageLayoutManifest,
+ tabs: [
+ { ...pageLayoutManifest.tabs![0], widgets: [widgetWithTypename] },
+ ],
+ },
+ ] as unknown as PageLayoutManifest[],
+ pageLayoutTabs: [
+ buildPageLayoutTabManifest({
+ widgets: [widgetWithTypename],
+ } as unknown as Partial<PageLayoutTabManifest>),
+ ],
+ }),
+ );
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+ const pageLayoutTab = entities.find(
+ (entity) => entity.kind === 'pageLayoutTab',
+ );
+ const expectedConfiguration = {
+ configurationType: 'RECORD_TABLE',
+ recordLimit: null,
+ viewUniversalIdentifier: VIEW_UID,
+ };
+
+ expect(
+ (pageLayout?.config as PageLayoutManifest).tabs?.[0].widgets?.[0]
+ .configuration,
+ ).toEqual(expectedConfiguration);
+ expect(
+ (pageLayoutTab?.config as PageLayoutTabManifest).widgets?.[0]
+ .configuration,
+ ).toEqual(expectedConfiguration);
+ });
+
+ it('should give a page layout on a standard object that object as parent', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayouts: [
+ buildPageLayoutManifest({
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person,
+ }),
+ ],
+ }),
+ );
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+
+ expect(pageLayout?.parentName).toBe('person');
+ });
+
+ it('should give a page layout without an object no parent', () => {
+ const {
+ objectUniversalIdentifier: _objectUniversalIdentifier,
+ ...standalonePageManifest
+ } = buildPageLayoutManifest({
+ name: 'Pet docs',
+ type: PageLayoutType.STANDALONE_PAGE,
+ });
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ pageLayouts: [standalonePageManifest] }),
+ );
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+
+ expect(skipped).toEqual([]);
+ expect(pageLayout?.parentName).toBeNull();
+ expect(pageLayout?.fileBaseName).toBe('pet-docs');
+ });
+
+ it('should name a page layout whose name has no kebab-case form after its identifier prefix', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayouts: [buildPageLayoutManifest({ name: '!!!' })],
+ }),
+ );
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+
+ expect(pageLayout?.fileBaseName).toBe('cccccccc');
+ });
+
+ it('should write a standalone page layout tab into src/page-layout-tabs with the tab enum bindings and its standard page layout as parent', () => {
+ const pageLayoutTabManifest = buildPageLayoutTabManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ pageLayoutTabs: [pageLayoutTabManifest] }),
+ );
+ const pageLayoutTab = entities.find(
+ (entity) => entity.kind === 'pageLayoutTab',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(pageLayoutTab?.universalIdentifier).toBe(STANDALONE_TAB_UID);
+ expect(pageLayoutTab?.definer).toBe('definePageLayoutTab');
+ expect(pageLayoutTab?.config).toEqual(pageLayoutTabManifest);
+ expect(pageLayoutTab?.enumBindings).toEqual(PAGE_LAYOUT_TAB_ENUM_BINDINGS);
+ expect(pageLayoutTab?.parentName).toBe('companyRecordPage');
+ expect(
+ `${pageLayoutTab?.defaultFolder}/${pageLayoutTab?.fileBaseName}${pageLayoutTab?.fileSuffix}`,
+ ).toBe('src/page-layout-tabs/extra.page-layout-tab.ts');
+ });
+
+ it('should give a standalone tab on the record page of a manifest object that page as parent', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayoutTabs: [
+ buildPageLayoutTabManifest({
+ pageLayoutUniversalIdentifier:
+ getSystemRecordPageLayoutUniversalIdentifier({
+ objectMetadataApplicationUniversalIdentifier: APP_UID,
+ objectUniversalIdentifier: PET_UID,
+ }),
+ }),
+ ],
+ }),
+ );
+ const pageLayoutTab = entities.find(
+ (entity) => entity.kind === 'pageLayoutTab',
+ );
+
+ expect(pageLayoutTab?.parentName).toBe('petRecordPage');
+ });
+
+ it('should give a standalone tab on a page layout of the manifest that layout as parent', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayouts: [buildPageLayoutManifest()],
+ pageLayoutTabs: [
+ buildPageLayoutTabManifest({
+ pageLayoutUniversalIdentifier: PAGE_LAYOUT_UID,
+ }),
+ ],
+ }),
+ );
+ const pageLayoutTab = entities.find(
+ (entity) => entity.kind === 'pageLayoutTab',
+ );
+
+ expect(pageLayoutTab?.parentName).toBe('Pet page');
+ });
+
+ it('should skip a standalone tab that does not name its page layout', () => {
+ const {
+ pageLayoutUniversalIdentifier: _pageLayoutUniversalIdentifier,
+ ...tabWithoutPageLayout
+ } = buildPageLayoutTabManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ pageLayoutTabs: [tabWithoutPageLayout] }),
+ );
+
+ expect(entities.some((entity) => entity.kind === 'pageLayoutTab')).toBe(
+ false,
+ );
+ expect(skipped).toEqual([
+ {
+ kind: 'pageLayoutTab',
+ universalIdentifier: STANDALONE_TAB_UID,
+ reason: 'it does not name the page layout it belongs to',
+ },
+ ]);
+ });
+
+ it('should write a navigation menu item verbatim into src/navigation-menu-items with the navigation menu item enum bindings, named after the object it targets', () => {
+ const navigationMenuItemManifest = buildNavigationMenuItemManifest();
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ navigationMenuItems: [navigationMenuItemManifest] }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(navigationMenuItem?.universalIdentifier).toBe(
+ NAVIGATION_MENU_ITEM_UID,
+ );
+ expect(navigationMenuItem?.definer).toBe('defineNavigationMenuItem');
+ expect(navigationMenuItem?.config).toEqual(navigationMenuItemManifest);
+ expect(navigationMenuItem?.enumBindings).toEqual(
+ NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ );
+ expect(navigationMenuItem?.parentName).toBeNull();
+ expect(
+ `${navigationMenuItem?.defaultFolder}/${navigationMenuItem?.fileBaseName}${navigationMenuItem?.fileSuffix}`,
+ ).toBe('src/navigation-menu-items/pet.navigation-menu-item.ts');
+ });
+
+ it('should prefer the name a navigation menu item carries over the object it targets', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ buildNavigationMenuItemManifest({ name: 'Pet shelter' }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('pet-shelter');
+ });
+
+ it('should name a navigation menu item with an empty name after the object it targets', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [buildNavigationMenuItemManifest({ name: '' })],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('pet');
+ });
+
+ it('should name a navigation menu item whose name is only whitespace after the object it targets', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [buildNavigationMenuItemManifest({ name: ' ' })],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('pet');
+ });
+
+ it('should name a navigation menu item targeting a standard object after that object', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ buildNavigationMenuItemManifest({
+ targetObjectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person,
+ }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('person');
+ });
+
+ it('should name a navigation menu item pointing at a view of the manifest after that view', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...viewItemManifest
+ } = buildNavigationMenuItemManifest({
+ type: NavigationMenuItemType.VIEW,
+ targetObjectUniversalIdentifier: PET_UID,
+ viewUniversalIdentifier: VIEW_UID,
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({
+ views: [buildViewManifest()],
+ navigationMenuItems: [viewItemManifest],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('all-pets');
+ });
+
+ it('should name a navigation menu item pointing at the index view of a manifest object after that view', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...indexViewItemManifest
+ } = buildNavigationMenuItemManifest({
+ type: NavigationMenuItemType.VIEW,
+ viewUniversalIdentifier: getSystemViewUniversalIdentifier({
+ objectMetadataApplicationUniversalIdentifier: APP_UID,
+ objectUniversalIdentifier: PET_UID,
+ viewKey: SYSTEM_VIEW_KEYS.INDEX,
+ }),
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({ navigationMenuItems: [indexViewItemManifest] }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('pet-index-view');
+ });
+
+ it('should name a navigation menu item pointing at a page layout after that layout', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...pageLayoutItemManifest
+ } = buildNavigationMenuItemManifest({
+ type: NavigationMenuItemType.PAGE_LAYOUT,
+ pageLayoutUniversalIdentifier: PAGE_LAYOUT_UID,
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({
+ pageLayouts: [buildPageLayoutManifest()],
+ navigationMenuItems: [pageLayoutItemManifest],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('pet-page');
+ });
+
+ it('should name a navigation menu item that points at nothing of the manifest after its identifier prefix', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...linkItemManifest
+ } = buildNavigationMenuItemManifest({
+ type: NavigationMenuItemType.LINK,
+ link: 'https://twenty.com',
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({ navigationMenuItems: [linkItemManifest] }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(navigationMenuItem?.fileBaseName).toBe('10101010');
+ });
+
+ it('should give a navigation menu item sitting in a folder that folder as parent', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...folderManifest
+ } = buildNavigationMenuItemManifest({
+ universalIdentifier: NAVIGATION_FOLDER_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: 'Care',
+ position: 0,
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ folderManifest,
+ buildNavigationMenuItemManifest({
+ folderUniversalIdentifier: NAVIGATION_FOLDER_UID,
+ }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.universalIdentifier === NAVIGATION_MENU_ITEM_UID,
+ );
+
+ expect(navigationMenuItem?.parentName).toBe('Care');
+ });
+
+ it('should give a navigation menu item sitting in a folder without a name no parent', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...folderManifest
+ } = buildNavigationMenuItemManifest({
+ universalIdentifier: NAVIGATION_FOLDER_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: '',
+ position: 0,
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ folderManifest,
+ buildNavigationMenuItemManifest({
+ folderUniversalIdentifier: NAVIGATION_FOLDER_UID,
+ }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.universalIdentifier === NAVIGATION_MENU_ITEM_UID,
+ );
+
+ expect(navigationMenuItem?.parentName).toBeNull();
+ });
+
+ it('should give a navigation menu item sitting in a folder named only with punctuation no parent', () => {
+ const {
+ targetObjectUniversalIdentifier: _targetObjectUniversalIdentifier,
+ ...folderManifest
+ } = buildNavigationMenuItemManifest({
+ universalIdentifier: NAVIGATION_FOLDER_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: '///',
+ position: 0,
+ });
+ const { entities } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ folderManifest,
+ buildNavigationMenuItemManifest({
+ folderUniversalIdentifier: NAVIGATION_FOLDER_UID,
+ }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.universalIdentifier === NAVIGATION_MENU_ITEM_UID,
+ );
+
+ expect(navigationMenuItem?.parentName).toBeNull();
+ });
+
+ it('should give a navigation menu item whose folder is not part of the export no parent', () => {
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ navigationMenuItems: [
+ buildNavigationMenuItemManifest({
+ folderUniversalIdentifier: 'a-folder-of-another-application',
+ }),
+ ],
+ }),
+ );
+ const navigationMenuItem = entities.find(
+ (entity) => entity.kind === 'navigationMenuItem',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(navigationMenuItem?.parentName).toBeNull();
+ });
+
+ it('should write a standalone page layout widget into src/page-layout-widgets, named after its title', () => {
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ pageLayoutWidgets: [
+ {
+ universalIdentifier: WIDGET_UID,
+ pageLayoutTabUniversalIdentifier: PAGE_LAYOUT_TAB_UID,
+ title: 'Care notes',
+ type: WidgetType.IFRAME,
+ objectUniversalIdentifier: PET_UID,
+ position: {
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ index: 1000,
+ },
+ configuration: {
+ configurationType: 'IFRAME',
+ url: 'https://example.com/docs',
+ __typename: 'IframeConfiguration',
+ },
+ },
+ ],
+ } as unknown as Partial<Manifest>),
+ );
+ const widget = entities.find(
+ (entity) => entity.kind === 'pageLayoutWidget',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(widget?.definer).toBe('definePageLayoutWidget');
+ expect(
+ `${widget?.defaultFolder}/${widget?.fileBaseName}${widget?.fileSuffix}`,
+ ).toBe('src/page-layout-widgets/care-notes.page-layout-widget.ts');
+ expect(widget?.parentName).toBe('pet');
+ expect(widget?.config).not.toHaveProperty('configuration.__typename');
+ expect(JSON.stringify(widget?.config)).not.toContain('__typename');
+ });
+
+ it('should build a manifest that has no views, view fields, page layouts and page layout tabs properties without producing their entities', () => {
+ const {
+ views: _views,
+ viewFields: _viewFields,
+ pageLayouts: _pageLayouts,
+ pageLayoutTabs: _pageLayoutTabs,
+ ...manifestWithoutViews
+ } = buildManifest({
+ views: [buildViewManifest()],
+ viewFields: [buildViewFieldManifest()],
+ pageLayouts: [buildPageLayoutManifest()],
+ pageLayoutTabs: [buildPageLayoutTabManifest()],
+ });
+
+ const { entities, skipped } = buildPullEntities(
+ manifestWithoutViews as unknown as Manifest,
+ );
+
+ expect(skipped).toEqual([]);
+ expect(entities.map((entity) => entity.kind)).toEqual([
+ 'application',
+ 'object',
+ 'field',
+ ]);
+ });
+
+ it('should never skip a view, a view field, a page layout or a page layout tab, even when their parent is unknown', () => {
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({
+ objects: [],
+ views: [
+ buildViewManifest({
+ objectUniversalIdentifier: 'an-object-of-another-application',
+ }),
+ ],
+ viewFields: [
+ buildViewFieldManifest({
+ fieldMetadataUniversalIdentifier: 'a-field-of-another-application',
+ }),
+ ],
+ pageLayouts: [
+ buildPageLayoutManifest({
+ objectUniversalIdentifier: 'an-object-of-another-application',
+ }),
+ ],
+ pageLayoutTabs: [
+ buildPageLayoutTabManifest({
+ pageLayoutUniversalIdentifier:
+ 'a-page-layout-of-another-application',
+ }),
+ ],
+ }),
+ );
+ const view = entities.find((entity) => entity.kind === 'view');
+ const pageLayout = entities.find((entity) => entity.kind === 'pageLayout');
+ const pageLayoutTab = entities.find(
+ (entity) => entity.kind === 'pageLayoutTab',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(entities.map((entity) => entity.kind)).toEqual(
+ expect.arrayContaining([
+ 'view',
+ 'viewField',
+ 'pageLayout',
+ 'pageLayoutTab',
+ ]),
+ );
+ expect(view?.parentName).toBeNull();
+ expect(pageLayout?.parentName).toBeNull();
+ expect(pageLayoutTab?.parentName).toBeNull();
+ });
+
+ it('should write a permission flag verbatim into src/permission-flags, named after its key', () => {
+ const permissionFlagManifest = {
+ universalIdentifier: EXPORT_PETS_FLAG_UID,
+ key: 'EXPORT_PETS',
+ label: 'Export pets',
+ permissionType: 'settings' as const,
+ };
+ const { entities, skipped } = buildPullEntities(
+ buildManifest({ permissionFlags: [permissionFlagManifest] }),
+ );
+ const permissionFlag = entities.find(
+ (entity) => entity.kind === 'permissionFlag',
+ );
+
+ expect(skipped).toEqual([]);
+ expect(permissionFlag?.definer).toBe('definePermissionFlag');
+ expect(permissionFlag?.config).toEqual(permissionFlagManifest);
+ expect(
+ `${permissionFlag?.defaultFolder}/${permissionFlag?.fileBaseName}${permissionFlag?.fileSuffix}`,
+ ).toBe('src/permission-flags/export-pets.permission-flag.ts');
+ });
+
+ it('should write the default role with defineApplicationRole and the other roles with defineRole into src/roles under the role enum bindings', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ application: APPLICATION_WITH_SUPPORT_DEFAULT_ROLE,
+ roles: [
+ { universalIdentifier: SUPPORT_ROLE_UID, label: 'Support' },
+ { universalIdentifier: AUDITOR_ROLE_UID, label: 'Auditor' },
+ ],
+ } as unknown as Partial<Manifest>),
+ );
+
+ expect(
+ entities
+ .filter((entity) => entity.kind === 'role')
+ .map((entity) => ({
+ definer: entity.definer,
+ path: `${entity.defaultFolder}/${entity.fileBaseName}${entity.fileSuffix}`,
+ enumBindings: entity.enumBindings,
+ })),
+ ).toEqual([
+ {
+ definer: 'defineApplicationRole',
+ path: 'src/roles/support.role.ts',
+ enumBindings: ROLE_ENUM_BINDINGS,
+ },
+ {
+ definer: 'defineRole',
+ path: 'src/roles/auditor.role.ts',
+ enumBindings: ROLE_ENUM_BINDINGS,
+ },
+ ]);
+ });
+
+ it('should drop the default role from the application config when that role is written', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ application: APPLICATION_WITH_SUPPORT_DEFAULT_ROLE,
+ roles: [{ universalIdentifier: SUPPORT_ROLE_UID, label: 'Support' }],
+ } as unknown as Partial<Manifest>),
+ );
+
+ expect(
+ entities.find((entity) => entity.kind === 'application')?.config,
+ ).toEqual({
+ universalIdentifier: APP_UID,
+ displayName: 'Pets',
+ description: 'Pet tracking',
+ });
+ });
+
+ it('should keep a default role that is not one of the written roles on the application config', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ application: APPLICATION_WITH_SUPPORT_DEFAULT_ROLE,
+ roles: [{ universalIdentifier: AUDITOR_ROLE_UID, label: 'Auditor' }],
+ } as unknown as Partial<Manifest>),
+ );
+
+ expect(
+ entities.find((entity) => entity.kind === 'application')?.config,
+ ).toEqual(APPLICATION_WITH_SUPPORT_DEFAULT_ROLE);
+ expect(entities.find((entity) => entity.kind === 'role')?.definer).toBe(
+ 'defineRole',
+ );
+ });
+
+ it('should leave out the object and field permission identifiers the build derives and keep the others', () => {
+ const { entities } = buildPullEntities(
+ buildManifest({
+ roles: [
+ {
+ universalIdentifier: SUPPORT_ROLE_UID,
+ label: 'Support',
+ objectPermissions: [
+ {
+ universalIdentifier: getObjectPermissionUniversalIdentifier({
+ applicationUniversalIdentifier: APP_UID,
+ roleUniversalIdentifier: SUPPORT_ROLE_UID,
+ objectUniversalIdentifier: PET_UID,
+ }),
+ objectUniversalIdentifier: PET_UID,
+ canReadObjectRecords: true,
+ },
+ {
+ universalIdentifier: LEGACY_OBJECT_PERMISSION_UID,
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company,
+ canReadObjectRecords: false,
+ },
+ ],
+ fieldPermissions: [
+ {
+ universalIdentifier: getFieldPermissionUniversalIdentifier({
+ applicationUniversalIdentifier: APP_UID,
+ roleUniversalIdentifier: SUPPORT_ROLE_UID,
+ fieldUniversalIdentifier: PET_NAME_FIELD_UID,
+ }),
+ objectUniversalIdentifier: PET_UID,
+ fieldUniversalIdentifier: PET_NAME_FIELD_UID,
+ canUpdateFieldValue: false,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [EXPORT_PETS_FLAG_UID],
+ },
+ ],
+ }),
+ );
+
+ expect(entities.find((entity) => entity.kind === 'role')?.config).toEqual({
+ universalIdentifier: SUPPORT_ROLE_UID,
+ label: 'Support',
+ objectPermissions: [
+ { objectUniversalIdentifier: PET_UID, canReadObjectRecords: true },
+ {
+ universalIdentifier: LEGACY_OBJECT_PERMISSION_UID,
+ objectUniversalIdentifier:
+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company,
+ canReadObjectRecords: false,
+ },
+ ],
+ fieldPermissions: [
+ {
+ objectUniversalIdentifier: PET_UID,
+ fieldUniversalIdentifier: PET_NAME_FIELD_UID,
+ canUpdateFieldValue: false,
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [EXPORT_PETS_FLAG_UID],
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/format-pull-report.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/format-pull-report.spec.ts
new file mode 100644
index 00000000000..b6f9913aa80
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/format-pull-report.spec.ts
@@ -0,0 +1,246 @@
+import { type AppExportCoverageEntry } from '@/app/types/app-export.type';
+import { formatPullReport } from '@/app/pull/format-pull-report';
+import { describe, expect, it } from 'vitest';
+
+const buildCoverage = (
+ entries: Partial<AppExportCoverageEntry>[],
+): AppExportCoverageEntry[] =>
+ entries.map((entry, index) => ({
+ metadataName: 'view',
+ universalIdentifier: `identifier-${index}`,
+ status: 'UNSUPPORTED',
+ reason: null,
+ ...entry,
+ }));
+
+const buildReport = (
+ overrides: Partial<Parameters<typeof formatPullReport>[0]> = {},
+) =>
+ formatPullReport({
+ writes: [],
+ deletions: [],
+ unchangedCount: 0,
+ skipped: [],
+ coverage: [],
+ localOnlyRelativePaths: [],
+ ...overrides,
+ });
+
+describe('formatPullReport', () => {
+ it('should group the files it touched by what happened to them', () => {
+ const report = buildReport({
+ writes: [
+ {
+ kind: 'object',
+ universalIdentifier: 'a',
+ relativePath: 'src/objects/pet.object.ts',
+ isRegeneration: false,
+ },
+ {
+ kind: 'application',
+ universalIdentifier: 'b',
+ relativePath: 'src/application.config.ts',
+ isRegeneration: true,
+ },
+ ],
+ deletions: [
+ {
+ universalIdentifier: 'c',
+ relativePath: 'src/objects/gone.object.ts',
+ },
+ ],
+ unchangedCount: 3,
+ });
+
+ expect(report).toContain('written src/objects/pet.object.ts');
+ expect(report).toContain('regenerated src/application.config.ts');
+ expect(report).toContain('deleted src/objects/gone.object.ts');
+ expect(report).toContain('unchanged 3 file(s)');
+ });
+
+ it('should count coverage rows per metadata name under a titled section', () => {
+ const report = buildReport({
+ coverage: buildCoverage([
+ { metadataName: 'view' },
+ { metadataName: 'view' },
+ { metadataName: 'role' },
+ { metadataName: 'roleTarget', status: 'EXCLUDED' },
+ { metadataName: 'fieldMetadata', status: 'ENGINE_DERIVED' },
+ { metadataName: 'fieldMetadata', status: 'FOREIGN_OWNED' },
+ ]),
+ });
+
+ expect(report).toContain(
+ 'Not written, unsupported by this version (3 row(s)):',
+ );
+ expect(report).toMatch(/role\s+1/);
+ expect(report).toMatch(/view\s+2/);
+ expect(report).toContain(
+ 'Owned by another application, not written (1 row(s)):',
+ );
+ expect(report).toContain('Excluded as workspace runtime state (1 row(s)):');
+ expect(report).toContain(
+ 'Derived by the engine, rebuilt on apply (1 row(s)):',
+ );
+ });
+
+ it('should omit a section with no rows', () => {
+ const report = buildReport({
+ coverage: buildCoverage([{ metadataName: 'view' }]),
+ });
+
+ expect(report).not.toContain('Excluded as workspace runtime state');
+ expect(report).not.toContain('Derived by the engine');
+ });
+
+ it('should list identifiers only in verbose mode and cap the list', () => {
+ const coverage = buildCoverage(
+ Array.from({ length: 25 }, () => ({ metadataName: 'view' })),
+ );
+
+ expect(buildReport({ coverage })).not.toContain('identifier-0');
+
+ const verboseReport = buildReport({ coverage, verbose: true });
+
+ expect(verboseReport).toContain('identifier-0');
+ expect(verboseReport).toContain('…and 5 more');
+ });
+
+ it('should print the reason next to each count and split a kind by reason', () => {
+ const report = buildReport({
+ coverage: buildCoverage([
+ {
+ metadataName: 'roleTarget',
+ status: 'EXCLUDED',
+ reason: 'member or API key role assignment',
+ },
+ {
+ metadataName: 'roleTarget',
+ status: 'EXCLUDED',
+ reason: 'member or API key role assignment',
+ },
+ {
+ metadataName: 'navigationMenuItem',
+ status: 'EXCLUDED',
+ reason: 'personal navigation item',
+ },
+ {
+ metadataName: 'navigationMenuItem',
+ status: 'EXCLUDED',
+ reason: 'navigation item pinned to a record',
+ },
+ ]),
+ });
+
+ expect(report).toMatch(
+ /roleTarget\s+2\s+member or API key role assignment/,
+ );
+ expect(report).toMatch(
+ /navigationMenuItem\s+1\s+navigation item pinned to a record/,
+ );
+ expect(report).toMatch(/navigationMenuItem\s+1\s+personal navigation item/);
+ });
+
+ it('should name the exported rows written without their workspace-local state', () => {
+ const report = buildReport({
+ coverage: buildCoverage([
+ { metadataName: 'objectMetadata', status: 'EXPORTED' },
+ {
+ metadataName: 'objectMetadata',
+ universalIdentifier: 'survey-result-identifier',
+ status: 'EXPORTED',
+ reason: 'deactivated in this workspace, exported active',
+ },
+ {
+ metadataName: 'fieldMetadata',
+ universalIdentifier: 'unlabelled-identifier',
+ status: 'EXPORTED',
+ reason: 'workspace overrides not exported',
+ },
+ ]),
+ entityLabelByUniversalIdentifier: {
+ 'survey-result-identifier': 'surveyResult',
+ },
+ });
+
+ expect(report).toContain(
+ 'Written without their workspace-local state (2 row(s)):',
+ );
+ expect(report).toContain(
+ 'objectMetadata surveyResult: deactivated in this workspace, exported active',
+ );
+ expect(report).toContain(
+ 'fieldMetadata unlabelled-identifier: workspace overrides not exported',
+ );
+ expect(report).not.toContain('identifier-0');
+ });
+
+ it('should cap the rows written without their workspace-local state unless verbose', () => {
+ const coverage = buildCoverage(
+ Array.from({ length: 25 }, () => ({
+ metadataName: 'fieldMetadata',
+ status: 'EXPORTED' as const,
+ reason: 'workspace overrides not exported',
+ })),
+ );
+
+ const report = buildReport({ coverage });
+
+ expect(report).toContain('…and 5 more, listed with --verbose');
+ expect(report).not.toContain('identifier-9');
+ expect(buildReport({ coverage, verbose: true })).toContain('identifier-9');
+ });
+
+ it('should name the entities the writer refused to write', () => {
+ const report = buildReport({
+ skipped: [
+ {
+ kind: 'object',
+ universalIdentifier: 'junction-uid',
+ reason:
+ 'petCareAgreement: its label identifier field is engine-derived and not part of the export',
+ },
+ ],
+ });
+
+ expect(report).toContain('Not written by the writer:');
+ expect(report).toContain('object petCareAgreement:');
+ });
+
+ it('should warn about a define file it could not read', () => {
+ const report = buildReport({
+ unreadableRelativePaths: ['src/objects/broken.object.ts'],
+ });
+
+ expect(report).toContain('Could not be read');
+ expect(report).toContain('src/objects/broken.object.ts');
+ });
+
+ it('should list local entities the workspace does not have', () => {
+ const report = buildReport({
+ localOnlyRelativePaths: ['src/objects/unpushed.object.ts'],
+ });
+
+ expect(report).toContain(
+ 'Local entities the workspace does not have (left untouched):',
+ );
+ expect(report).toContain('src/objects/unpushed.object.ts');
+ });
+
+ it('should list the locales whose entries stayed in compiled form', () => {
+ const report = buildReport({
+ compiledTranslationEntryCountByLocale: { 'fr-FR': 3, en: 1 },
+ });
+
+ expect(report).toContain('locales/compiled/');
+ expect(report).toMatch(/^ {2}en {11}1 entry$/m);
+ expect(report).toMatch(/^ {2}fr-FR {8}3 entries$/m);
+ });
+
+ it('should stay silent about compiled translations when every entry was decoded', () => {
+ expect(buildReport()).not.toContain('compiled form');
+ expect(
+ buildReport({ compiledTranslationEntryCountByLocale: { 'fr-FR': 0 } }),
+ ).not.toContain('compiled form');
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/plan-pull-writes.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/plan-pull-writes.spec.ts
new file mode 100644
index 00000000000..46151f1381a
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/plan-pull-writes.spec.ts
@@ -0,0 +1,1404 @@
+import { type TargetFunction } from '@/app/source/extract-define-entity';
+import { planPullWrites } from '@/app/pull/plan-pull-writes';
+import { preparePullEntities } from '@/app/pull/prepare-pull-entities';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+import {
+ type Manifest,
+ type NavigationMenuItemManifest,
+ type PageLayoutManifest,
+ type PageLayoutTabManifest,
+ type StandaloneViewFieldManifest,
+ type ViewFilterManifest,
+ type ViewManifest,
+} from 'twenty-shared/application';
+import { STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/metadata';
+import {
+ NavigationMenuItemType,
+ PageLayoutTabLayoutMode,
+ PageLayoutType,
+ WidgetType,
+ ViewFilterOperand,
+} from 'twenty-shared/types';
+import { describe, expect, it } from 'vitest';
+
+const planManifestPullWrites = (
+ options: Parameters<typeof preparePullEntities>[0] & {
+ workspaceUniversalIdentifiers: ReadonlySet<string>;
+ },
+) => {
+ const { entities, baseEntities, skipped } = preparePullEntities(options);
+
+ return {
+ ...planPullWrites({ ...options, entities, baseEntities }),
+ skipped,
+ };
+};
+
+const APP_UID = '11111111-1111-4111-8111-111111111111';
+const PET_UID = '22222222-2222-4222-8222-222222222222';
+const NAME_FIELD_UID = '33333333-3333-4333-8333-333333333333';
+const ROCKET_UID = '44444444-4444-4444-8444-444444444444';
+const ROCKET_NAME_FIELD_UID = '55555555-5555-4555-8555-555555555555';
+const JUNCTION_UID = '66666666-6666-4666-8666-666666666666';
+const JUNCTION_ID_FIELD_UID = '77777777-7777-4777-8777-777777777777';
+const ALL_PETS_VIEW_UID = '88888888-8888-4888-8888-888888888888';
+const HEALTHY_PETS_VIEW_UID = '99999999-9999-4999-8999-999999999999';
+const OVERVIEW_VIEW_UID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const SECOND_OVERVIEW_VIEW_UID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const THIRD_OVERVIEW_VIEW_UID = 'ffffffff-ffff-4fff-8fff-ffffffffffff';
+const HEALTHY_PETS_FILTER_UID = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const PET_NAME_VIEW_FIELD_UID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+const ROCKET_NAME_VIEW_FIELD_UID = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
+const PET_PAGE_LAYOUT_UID = '12121212-1212-4121-8121-121212121212';
+const ROCKET_PAGE_LAYOUT_UID = '13131313-1313-4131-8131-131313131313';
+const SECOND_PET_PAGE_LAYOUT_UID = '14141414-1414-4141-8141-141414141414';
+const COMPANY_EXTRA_TAB_UID = '15151515-1515-4151-8151-151515151515';
+const PERSON_EXTRA_TAB_UID = '16161616-1616-4161-8161-161616161616';
+const DOCS_WIDGET_UID = '17171717-1717-4171-8171-171717171717';
+const PET_CARE_FOLDER_NAVIGATION_ITEM_UID =
+ '18181818-1818-4181-8181-181818181818';
+const DAILY_OPS_FOLDER_NAVIGATION_ITEM_UID =
+ '19191919-1919-4191-8191-191919191919';
+const DOCS_NAVIGATION_ITEM_UID = '1a1a1a1a-1a1a-41a1-81a1-1a1a1a1a1a1a';
+const SECOND_DOCS_NAVIGATION_ITEM_UID = '1b1b1b1b-1b1b-41b1-81b1-1b1b1b1b1b1b';
+const PET_NAVIGATION_ITEM_UID = '1c1c1c1c-1c1c-41c1-81c1-1c1c1c1c1c1c';
+const SUPPORT_ROLE_UID = '1d1d1d1d-1d1d-41d1-81d1-1d1d1d1d1d1d';
+
+const buildObject = ({
+ universalIdentifier,
+ nameSingular,
+ labelIdentifierFieldMetadataUniversalIdentifier,
+ label = 'Name',
+}: {
+ universalIdentifier: string;
+ nameSingular: string;
+ labelIdentifierFieldMetadataUniversalIdentifier: string;
+ label?: string;
+}) => ({
+ universalIdentifier,
+ nameSingular,
+ namePlural: `${nameSingular}s`,
+ labelSingular: nameSingular,
+ labelPlural: `${nameSingular}s`,
+ labelIdentifierFieldMetadataUniversalIdentifier,
+ fields: [
+ {
+ universalIdentifier: labelIdentifierFieldMetadataUniversalIdentifier,
+ name: 'name',
+ label,
+ type: 'TEXT',
+ },
+ ],
+});
+
+const buildManifest = (objects: unknown[]): Manifest =>
+ ({
+ application: {
+ universalIdentifier: APP_UID,
+ displayName: 'Pets',
+ description: '',
+ defaultRoleUniversalIdentifier: 'role-uid',
+ },
+ objects,
+ fields: [],
+ indexes: [],
+ }) as unknown as Manifest;
+
+const MANIFEST = buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+]);
+
+const buildView = (
+ overrides: Partial<ViewManifest> & { universalIdentifier: string },
+): ViewManifest => ({
+ name: 'Overview',
+ objectUniversalIdentifier: PET_UID,
+ ...overrides,
+});
+
+const buildViewField = (
+ overrides: Partial<StandaloneViewFieldManifest> & {
+ universalIdentifier: string;
+ },
+): StandaloneViewFieldManifest => ({
+ viewUniversalIdentifier: OVERVIEW_VIEW_UID,
+ fieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ position: 0,
+ ...overrides,
+});
+
+const buildPageLayout = (
+ overrides: Partial<PageLayoutManifest> & { universalIdentifier: string },
+): PageLayoutManifest => ({
+ name: 'Overview',
+ type: PageLayoutType.RECORD_PAGE,
+ objectUniversalIdentifier: PET_UID,
+ ...overrides,
+});
+
+const buildPageLayoutTab = (
+ overrides: Partial<PageLayoutTabManifest> & { universalIdentifier: string },
+): PageLayoutTabManifest => ({
+ pageLayoutUniversalIdentifier:
+ STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS.companyRecordPage
+ .universalIdentifier,
+ title: 'Extra',
+ position: 60,
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ ...overrides,
+});
+
+const buildNavigationMenuItem = (
+ overrides: Partial<NavigationMenuItemManifest> & {
+ universalIdentifier: string;
+ },
+): NavigationMenuItemManifest => ({
+ type: NavigationMenuItemType.LINK,
+ position: 0,
+ ...overrides,
+});
+
+const buildManifestWithDocsPageLayout = (url: string): Manifest => ({
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier: ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ pageLayouts: [
+ buildPageLayout({
+ universalIdentifier: ROCKET_PAGE_LAYOUT_UID,
+ name: 'Board',
+ objectUniversalIdentifier: ROCKET_UID,
+ }),
+ buildPageLayout({
+ universalIdentifier: PET_PAGE_LAYOUT_UID,
+ tabs: [
+ {
+ universalIdentifier: COMPANY_EXTRA_TAB_UID,
+ title: 'Docs',
+ position: 0,
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ widgets: [
+ {
+ universalIdentifier: DOCS_WIDGET_UID,
+ title: 'Docs',
+ type: WidgetType.IFRAME,
+ position: {
+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,
+ index: 0,
+ },
+ configuration: { configurationType: 'IFRAME', url },
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+});
+
+const buildNameFilter = (value: string): ViewFilterManifest => ({
+ universalIdentifier: HEALTHY_PETS_FILTER_UID,
+ fieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ operand: ViewFilterOperand.IS,
+ value,
+});
+
+const buildManifestWithFilteredView = (filterValue: string): Manifest => ({
+ ...MANIFEST,
+ views: [
+ buildView({ universalIdentifier: ALL_PETS_VIEW_UID, name: 'All pets' }),
+ buildView({
+ universalIdentifier: HEALTHY_PETS_VIEW_UID,
+ name: 'Healthy pets',
+ filters: [buildNameFilter(filterValue)],
+ }),
+ ],
+});
+
+const buildManifestWithNavigationMenu = (link: string): Manifest => ({
+ ...MANIFEST,
+ navigationMenuItems: [
+ buildNavigationMenuItem({
+ universalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: 'Pet care',
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: DOCS_NAVIGATION_ITEM_UID,
+ name: 'Docs',
+ link,
+ position: 1,
+ folderUniversalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ }),
+ ],
+});
+
+describe('planPullWrites', () => {
+ it('should write every entity when the project has no source and no base', () => {
+ const plan = planManifestPullWrites({
+ manifest: MANIFEST,
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/application.config.ts',
+ 'src/objects/pet.object.ts',
+ ]);
+ expect(plan.writes.every((write) => !write.isRegeneration)).toBe(true);
+ expect(plan.deletions).toEqual([]);
+ });
+
+ it('should regenerate the application config in the file that already declares one', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application-config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: 'a-placeholder-identifier',
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: MANIFEST,
+ baseManifest: null,
+ scannedFiles,
+ });
+ const applicationWrite = plan.writes.find(
+ (write) => write.kind === 'application',
+ );
+
+ expect(applicationWrite?.relativePath).toBe('src/application-config.ts');
+ expect(applicationWrite?.isRegeneration).toBe(true);
+ });
+
+ it('should leave a file untouched when its entity has not changed since the base', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: MANIFEST,
+ baseManifest: MANIFEST,
+ scannedFiles,
+ });
+
+ expect(plan.writes).toEqual([]);
+ expect(plan.unchanged).toHaveLength(2);
+ });
+
+ it('should rewrite only the entity that changed on the server', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ label: 'Renamed on the server',
+ }),
+ ]),
+ baseManifest: MANIFEST,
+ scannedFiles,
+ });
+
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/objects/pet.object.ts',
+ ]);
+ expect(plan.writes[0].isRegeneration).toBe(true);
+ expect(plan.writes[0].content).toContain('Renamed on the server');
+ });
+
+ it('should delete the file of an entity the base knew and the workspace no longer has', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/objects/rocket.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: ROCKET_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: MANIFEST,
+ baseManifest: buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ scannedFiles,
+ });
+
+ expect(plan.deletions).toEqual([
+ {
+ universalIdentifier: ROCKET_UID,
+ relativePath: 'src/objects/rocket.object.ts',
+ },
+ ]);
+ });
+
+ it('should report a local entity that neither the workspace nor the base knows', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/objects/unpushed.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: 'an-unpushed-identifier',
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: MANIFEST,
+ baseManifest: null,
+ scannedFiles,
+ });
+
+ expect(plan.localOnlyRelativePaths).toEqual([
+ 'src/objects/unpushed.object.ts',
+ ]);
+ expect(plan.deletions).toEqual([]);
+ });
+
+ it('should not report a local file as local-only when the export reported its entity', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/logic-functions/notify-owner.logic-function.ts',
+ entityKey: 'logicFunctions',
+ targetFunctionName: 'defineLogicFunction',
+ universalIdentifier: 'a-logic-function-the-writer-cannot-write',
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set([
+ 'a-logic-function-the-writer-cannot-write',
+ ]),
+ manifest: MANIFEST,
+ baseManifest: null,
+ scannedFiles,
+ });
+
+ expect(plan.localOnlyRelativePaths).toEqual([]);
+ });
+
+ it('should place a new entity beside existing files of its kind', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'app/data-model/rocket.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: ROCKET_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: MANIFEST,
+ baseManifest: null,
+ scannedFiles,
+ });
+
+ expect(
+ plan.writes.find((write) => write.kind === 'object')?.relativePath,
+ ).toBe('app/data-model/pet.object.ts');
+ });
+
+ it('should qualify colliding file names with the name of each parent object', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ objects: [
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ],
+ fields: [
+ {
+ universalIdentifier: 'field-one',
+ name: 'notes',
+ label: 'Notes',
+ type: 'TEXT',
+ objectUniversalIdentifier: PET_UID,
+ },
+ {
+ universalIdentifier: 'field-two',
+ name: 'notes',
+ label: 'Notes',
+ type: 'TEXT',
+ objectUniversalIdentifier: ROCKET_UID,
+ },
+ ],
+ } as unknown as Manifest,
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'field')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ 'src/fields/pet-notes.field.ts',
+ 'src/fields/rocket-notes.field.ts',
+ ]);
+ });
+
+ it('should never write over a file that belongs to another entity', () => {
+ const plan = planManifestPullWrites({
+ manifest: MANIFEST,
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: 'a-different-identifier',
+ isReadable: true,
+ },
+ ],
+ });
+
+ const objectWrite = plan.writes.find((write) => write.kind === 'object');
+
+ expect(objectWrite?.relativePath).not.toBe('src/objects/pet.object.ts');
+ expect(objectWrite?.relativePath).toBe(
+ `src/objects/${PET_UID.slice(0, 8)}-pet.object.ts`,
+ );
+ });
+
+ it('should not claim a path that differs only by case', () => {
+ const plan = planManifestPullWrites({
+ manifest: MANIFEST,
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'src/objects/Pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: 'a-different-identifier',
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes
+ .find((write) => write.kind === 'object')
+ ?.relativePath.toLowerCase(),
+ ).not.toBe('src/objects/pet.object.ts');
+ });
+
+ it('should keep a file whose define file could not be read', () => {
+ const plan = planManifestPullWrites({
+ manifest: MANIFEST,
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: null,
+ targetFunctionName: null,
+ universalIdentifier: null,
+ isReadable: false,
+ },
+ ],
+ });
+
+ expect(plan.writes.map((write) => write.relativePath)).not.toContain(
+ 'src/objects/pet.object.ts',
+ );
+ });
+
+ it('should place a new view beside existing view files', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ views: [
+ buildView({ universalIdentifier: OVERVIEW_VIEW_UID }),
+ buildView({
+ universalIdentifier: ALL_PETS_VIEW_UID,
+ name: 'All pets',
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'app/screens/overview.view.ts',
+ entityKey: 'views',
+ targetFunctionName: 'defineView',
+ universalIdentifier: OVERVIEW_VIEW_UID,
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === ALL_PETS_VIEW_UID,
+ )?.relativePath,
+ ).toBe('app/screens/all-pets.view.ts');
+ });
+
+ it('should place a new standalone view field beside existing view field files', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ views: [buildView({ universalIdentifier: OVERVIEW_VIEW_UID })],
+ viewFields: [
+ buildViewField({
+ universalIdentifier: ROCKET_NAME_VIEW_FIELD_UID,
+ fieldMetadataUniversalIdentifier: ROCKET_NAME_FIELD_UID,
+ }),
+ buildViewField({ universalIdentifier: PET_NAME_VIEW_FIELD_UID }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'app/screens/overview.view.ts',
+ entityKey: 'views',
+ targetFunctionName: 'defineView',
+ universalIdentifier: OVERVIEW_VIEW_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'app/screens/columns/rocket-name.view-field.ts',
+ entityKey: 'viewFields',
+ targetFunctionName: 'defineViewField',
+ universalIdentifier: ROCKET_NAME_VIEW_FIELD_UID,
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === PET_NAME_VIEW_FIELD_UID,
+ )?.relativePath,
+ ).toBe('app/screens/columns/pet-name.view-field.ts');
+ });
+
+ it('should qualify colliding view file names with the kebab-cased name of each object', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: JUNCTION_UID,
+ nameSingular: 'petCareAgreement',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ JUNCTION_ID_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ views: [
+ buildView({
+ universalIdentifier: OVERVIEW_VIEW_UID,
+ objectUniversalIdentifier: JUNCTION_UID,
+ }),
+ buildView({
+ universalIdentifier: SECOND_OVERVIEW_VIEW_UID,
+ objectUniversalIdentifier: ROCKET_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'view')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ 'src/views/pet-care-agreement-overview.view.ts',
+ 'src/views/rocket-overview.view.ts',
+ ]);
+ });
+
+ it('should fall back to identifier-prefixed names when two views of one object share a name', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ views: [
+ buildView({ universalIdentifier: OVERVIEW_VIEW_UID }),
+ buildView({ universalIdentifier: SECOND_OVERVIEW_VIEW_UID }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'view')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ `src/views/${OVERVIEW_VIEW_UID.slice(0, 8)}-pet-overview.view.ts`,
+ `src/views/${SECOND_OVERVIEW_VIEW_UID.slice(0, 8)}-pet-overview.view.ts`,
+ ]);
+ });
+
+ it('should prefix only the views whose qualified names still collide', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ views: [
+ buildView({ universalIdentifier: OVERVIEW_VIEW_UID }),
+ buildView({ universalIdentifier: SECOND_OVERVIEW_VIEW_UID }),
+ buildView({
+ universalIdentifier: THIRD_OVERVIEW_VIEW_UID,
+ objectUniversalIdentifier: ROCKET_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'view')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ `src/views/${OVERVIEW_VIEW_UID.slice(0, 8)}-pet-overview.view.ts`,
+ `src/views/${SECOND_OVERVIEW_VIEW_UID.slice(0, 8)}-pet-overview.view.ts`,
+ 'src/views/rocket-overview.view.ts',
+ ]);
+ });
+
+ it('should keep a qualified file name within the length cap', () => {
+ const longName = 'x'.repeat(100);
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: PET_UID,
+ nameSingular: 'pet',
+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ views: [
+ buildView({ universalIdentifier: OVERVIEW_VIEW_UID, name: longName }),
+ buildView({
+ universalIdentifier: SECOND_OVERVIEW_VIEW_UID,
+ name: longName,
+ objectUniversalIdentifier: ROCKET_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'view')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ `src/views/pet-${'x'.repeat(76)}.view.ts`,
+ `src/views/rocket-${'x'.repeat(73)}.view.ts`,
+ ]);
+ });
+
+ it('should leave an unchanged view untouched and regenerate the view whose filter changed on the server', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/views/all-pets.view.ts',
+ entityKey: 'views',
+ targetFunctionName: 'defineView',
+ universalIdentifier: ALL_PETS_VIEW_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/views/healthy-pets.view.ts',
+ entityKey: 'views',
+ targetFunctionName: 'defineView',
+ universalIdentifier: HEALTHY_PETS_VIEW_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: buildManifestWithFilteredView('Max'),
+ baseManifest: buildManifestWithFilteredView('Rex'),
+ scannedFiles,
+ });
+
+ expect(
+ plan.unchanged.map((entity) => entity.universalIdentifier),
+ ).toContain(ALL_PETS_VIEW_UID);
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/views/healthy-pets.view.ts',
+ ]);
+ expect(plan.writes[0].isRegeneration).toBe(true);
+ expect(plan.writes[0].content).toContain("value: 'Max',");
+ expect(plan.writes[0].content).toContain('operand: ViewFilterOperand.IS,');
+ });
+
+ it('should place a new page layout beside existing page layout files', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ pageLayouts: [
+ buildPageLayout({ universalIdentifier: ROCKET_PAGE_LAYOUT_UID }),
+ buildPageLayout({
+ universalIdentifier: PET_PAGE_LAYOUT_UID,
+ name: 'Pet page',
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'app/screens/overview.page-layout.ts',
+ entityKey: 'pageLayouts',
+ targetFunctionName: 'definePageLayout',
+ universalIdentifier: ROCKET_PAGE_LAYOUT_UID,
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === PET_PAGE_LAYOUT_UID,
+ )?.relativePath,
+ ).toBe('app/screens/pet-page.page-layout.ts');
+ });
+
+ it('should place a new standalone page layout tab beside existing page layout tab files', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ pageLayoutTabs: [
+ buildPageLayoutTab({ universalIdentifier: COMPANY_EXTRA_TAB_UID }),
+ buildPageLayoutTab({
+ universalIdentifier: PERSON_EXTRA_TAB_UID,
+ pageLayoutUniversalIdentifier:
+ STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS.personRecordPage
+ .universalIdentifier,
+ title: 'Insights',
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'app/screens/tabs/extra.page-layout-tab.ts',
+ entityKey: 'pageLayoutTabs',
+ targetFunctionName: 'definePageLayoutTab',
+ universalIdentifier: COMPANY_EXTRA_TAB_UID,
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === PERSON_EXTRA_TAB_UID,
+ )?.relativePath,
+ ).toBe('app/screens/tabs/insights.page-layout-tab.ts');
+ });
+
+ it('should qualify colliding page layout file names with the kebab-cased name of each object', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...buildManifest([
+ buildObject({
+ universalIdentifier: JUNCTION_UID,
+ nameSingular: 'petCareAgreement',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ JUNCTION_ID_FIELD_UID,
+ }),
+ buildObject({
+ universalIdentifier: ROCKET_UID,
+ nameSingular: 'rocket',
+ labelIdentifierFieldMetadataUniversalIdentifier:
+ ROCKET_NAME_FIELD_UID,
+ }),
+ ]),
+ pageLayouts: [
+ buildPageLayout({
+ universalIdentifier: PET_PAGE_LAYOUT_UID,
+ objectUniversalIdentifier: JUNCTION_UID,
+ }),
+ buildPageLayout({
+ universalIdentifier: ROCKET_PAGE_LAYOUT_UID,
+ objectUniversalIdentifier: ROCKET_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'pageLayout')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ 'src/page-layouts/pet-care-agreement-overview.page-layout.ts',
+ 'src/page-layouts/rocket-overview.page-layout.ts',
+ ]);
+ });
+
+ it('should qualify colliding standalone tab file names with the kebab-cased name of each page layout', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ pageLayoutTabs: [
+ buildPageLayoutTab({ universalIdentifier: COMPANY_EXTRA_TAB_UID }),
+ buildPageLayoutTab({
+ universalIdentifier: PERSON_EXTRA_TAB_UID,
+ pageLayoutUniversalIdentifier:
+ STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS.personRecordPage
+ .universalIdentifier,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'pageLayoutTab')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ 'src/page-layout-tabs/company-record-page-extra.page-layout-tab.ts',
+ 'src/page-layout-tabs/person-record-page-extra.page-layout-tab.ts',
+ ]);
+ });
+
+ it('should fall back to identifier-prefixed names when two page layouts of one object share a name', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ pageLayouts: [
+ buildPageLayout({ universalIdentifier: PET_PAGE_LAYOUT_UID }),
+ buildPageLayout({ universalIdentifier: SECOND_PET_PAGE_LAYOUT_UID }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'pageLayout')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ `src/page-layouts/${PET_PAGE_LAYOUT_UID.slice(0, 8)}-pet-overview.page-layout.ts`,
+ `src/page-layouts/${SECOND_PET_PAGE_LAYOUT_UID.slice(0, 8)}-pet-overview.page-layout.ts`,
+ ]);
+ });
+
+ it('should leave an unchanged page layout untouched and regenerate the page layout whose widget changed on the server', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/rocket.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: ROCKET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/page-layouts/board.page-layout.ts',
+ entityKey: 'pageLayouts',
+ targetFunctionName: 'definePageLayout',
+ universalIdentifier: ROCKET_PAGE_LAYOUT_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/page-layouts/overview.page-layout.ts',
+ entityKey: 'pageLayouts',
+ targetFunctionName: 'definePageLayout',
+ universalIdentifier: PET_PAGE_LAYOUT_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: buildManifestWithDocsPageLayout('https://example.com/new'),
+ baseManifest: buildManifestWithDocsPageLayout('https://example.com/old'),
+ scannedFiles,
+ });
+
+ expect(
+ plan.unchanged.map((entity) => entity.universalIdentifier),
+ ).toContain(ROCKET_PAGE_LAYOUT_UID);
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/page-layouts/overview.page-layout.ts',
+ ]);
+ expect(plan.writes[0].isRegeneration).toBe(true);
+ expect(plan.writes[0].content).toContain("url: 'https://example.com/new',");
+ expect(plan.writes[0].content).toContain(
+ 'layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,',
+ );
+ expect(plan.writes[0].content).toContain('type: WidgetType.IFRAME,');
+ });
+
+ it('should place a new navigation menu item beside existing navigation menu item files', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ navigationMenuItems: [
+ buildNavigationMenuItem({
+ universalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: 'Pet care',
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: PET_NAVIGATION_ITEM_UID,
+ type: NavigationMenuItemType.OBJECT,
+ position: 8,
+ targetObjectUniversalIdentifier: PET_UID,
+ folderUniversalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [
+ {
+ relativePath: 'app/navigation/pet-care.navigation-menu-item.ts',
+ entityKey: 'navigationMenuItems',
+ targetFunctionName: 'defineNavigationMenuItem',
+ universalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ isReadable: true,
+ },
+ ],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === PET_NAVIGATION_ITEM_UID,
+ )?.relativePath,
+ ).toBe('app/navigation/pet.navigation-menu-item.ts');
+ });
+
+ it('should qualify colliding navigation menu item file names with the kebab-cased name of each folder', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ navigationMenuItems: [
+ buildNavigationMenuItem({
+ universalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: 'Pet care',
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: DAILY_OPS_FOLDER_NAVIGATION_ITEM_UID,
+ type: NavigationMenuItemType.FOLDER,
+ name: 'Daily ops',
+ position: 1,
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: DOCS_NAVIGATION_ITEM_UID,
+ name: 'Docs',
+ link: 'https://example.com/pet-care',
+ folderUniversalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: SECOND_DOCS_NAVIGATION_ITEM_UID,
+ name: 'Docs',
+ link: 'https://example.com/daily-ops',
+ folderUniversalIdentifier: DAILY_OPS_FOLDER_NAVIGATION_ITEM_UID,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes.find(
+ (write) => write.universalIdentifier === DOCS_NAVIGATION_ITEM_UID,
+ )?.relativePath,
+ ).toBe('src/navigation-menu-items/pet-care-docs.navigation-menu-item.ts');
+ expect(
+ plan.writes.find(
+ (write) =>
+ write.universalIdentifier === SECOND_DOCS_NAVIGATION_ITEM_UID,
+ )?.relativePath,
+ ).toBe('src/navigation-menu-items/daily-ops-docs.navigation-menu-item.ts');
+ expect(
+ plan.writes.find(
+ (write) =>
+ write.universalIdentifier === PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ )?.relativePath,
+ ).toBe('src/navigation-menu-items/pet-care.navigation-menu-item.ts');
+ expect(
+ plan.writes.find(
+ (write) =>
+ write.universalIdentifier === DAILY_OPS_FOLDER_NAVIGATION_ITEM_UID,
+ )?.relativePath,
+ ).toBe('src/navigation-menu-items/daily-ops.navigation-menu-item.ts');
+ });
+
+ it('should fall back to identifier-prefixed names when two navigation menu items outside any folder share a name', () => {
+ const plan = planManifestPullWrites({
+ manifest: {
+ ...MANIFEST,
+ navigationMenuItems: [
+ buildNavigationMenuItem({
+ universalIdentifier: DOCS_NAVIGATION_ITEM_UID,
+ name: 'Docs',
+ link: 'https://example.com/pet-care',
+ }),
+ buildNavigationMenuItem({
+ universalIdentifier: SECOND_DOCS_NAVIGATION_ITEM_UID,
+ name: 'Docs',
+ link: 'https://example.com/daily-ops',
+ position: 1,
+ }),
+ ],
+ },
+ baseManifest: null,
+ workspaceUniversalIdentifiers: new Set(),
+ scannedFiles: [],
+ });
+
+ expect(
+ plan.writes
+ .filter((write) => write.kind === 'navigationMenuItem')
+ .map((write) => write.relativePath)
+ .sort(),
+ ).toEqual([
+ `src/navigation-menu-items/${DOCS_NAVIGATION_ITEM_UID.slice(0, 8)}-docs.navigation-menu-item.ts`,
+ `src/navigation-menu-items/${SECOND_DOCS_NAVIGATION_ITEM_UID.slice(0, 8)}-docs.navigation-menu-item.ts`,
+ ]);
+ });
+
+ it('should leave an unchanged navigation menu item untouched and regenerate the item whose link changed on the server', () => {
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath:
+ 'src/navigation-menu-items/pet-care.navigation-menu-item.ts',
+ entityKey: 'navigationMenuItems',
+ targetFunctionName: 'defineNavigationMenuItem',
+ universalIdentifier: PET_CARE_FOLDER_NAVIGATION_ITEM_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/navigation-menu-items/docs.navigation-menu-item.ts',
+ entityKey: 'navigationMenuItems',
+ targetFunctionName: 'defineNavigationMenuItem',
+ universalIdentifier: DOCS_NAVIGATION_ITEM_UID,
+ isReadable: true,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: buildManifestWithNavigationMenu('https://example.com/new'),
+ baseManifest: buildManifestWithNavigationMenu('https://example.com/old'),
+ scannedFiles,
+ });
+
+ expect(
+ plan.unchanged.map((entity) => entity.universalIdentifier),
+ ).toContain(PET_CARE_FOLDER_NAVIGATION_ITEM_UID);
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/navigation-menu-items/docs.navigation-menu-item.ts',
+ ]);
+ expect(plan.writes[0].isRegeneration).toBe(true);
+ expect(plan.writes[0].content).toContain(
+ "link: 'https://example.com/new',",
+ );
+ expect(plan.writes[0].content).toContain(
+ 'type: NavigationMenuItemType.LINK,',
+ );
+ });
+
+ const planWithDefaultRoleFile = (
+ roleFileTargetFunctionName: TargetFunction,
+ ) => {
+ const manifestWithDefaultRole = {
+ ...MANIFEST,
+ application: {
+ ...MANIFEST.application,
+ defaultRoleUniversalIdentifier: SUPPORT_ROLE_UID,
+ },
+ roles: [{ universalIdentifier: SUPPORT_ROLE_UID, label: 'Support' }],
+ } as unknown as Manifest;
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/default-role.ts',
+ entityKey: 'roles',
+ targetFunctionName: roleFileTargetFunctionName,
+ universalIdentifier: SUPPORT_ROLE_UID,
+ isReadable: true,
+ },
+ ];
+
+ return planManifestPullWrites({
+ workspaceUniversalIdentifiers: new Set(),
+ manifest: manifestWithDefaultRole,
+ baseManifest: manifestWithDefaultRole,
+ scannedFiles,
+ });
+ };
+
+ it('should regenerate a file whose define function differs from the one pull writes, even when its entity did not change', () => {
+ const plan = planWithDefaultRoleFile('defineRole');
+
+ expect(plan.writes.map((write) => write.relativePath)).toEqual([
+ 'src/default-role.ts',
+ ]);
+ expect(plan.writes[0].isRegeneration).toBe(true);
+ expect(plan.writes[0].content).toContain(
+ 'export default defineApplicationRole({',
+ );
+ expect(plan.unchanged).toHaveLength(2);
+ });
+
+ it('should leave a default role file written with defineApplicationRole untouched when its role did not change', () => {
+ const plan = planWithDefaultRoleFile('defineApplicationRole');
+
+ expect(plan.writes).toEqual([]);
+ expect(plan.unchanged).toHaveLength(3);
+ });
+ it('repairs a duplicated inline view field without rewriting its standalone definition', () => {
+ const viewField = buildViewField({
+ universalIdentifier: PET_NAME_VIEW_FIELD_UID,
+ });
+ const view = buildView({
+ universalIdentifier: OVERVIEW_VIEW_UID,
+ fields: [],
+ });
+ const manifest = { ...MANIFEST, views: [view], viewFields: [viewField] };
+ const scannedFiles: ScannedSourceFile[] = [
+ {
+ relativePath: 'src/application.config.ts',
+ entityKey: 'application',
+ targetFunctionName: 'defineApplication',
+ universalIdentifier: APP_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/objects/pet.object.ts',
+ entityKey: 'objects',
+ targetFunctionName: 'defineObject',
+ universalIdentifier: PET_UID,
+ isReadable: true,
+ },
+ {
+ relativePath: 'src/views/overview.ts',
+ entityKey: 'views',
+ targetFunctionName: 'defineView',
+ universalIdentifier: OVERVIEW_VIEW_UID,
+ isReadable: true,
+ config: { ...view, fields: [viewField] },
+ },
+ {
+ relativePath: 'src/view-fields/name.ts',
+ entityKey: 'viewFields',
+ targetFunctionName: 'defineViewField',
+ universalIdentifier: PET_NAME_VIEW_FIELD_UID,
+ isReadable: true,
+ config: viewField,
+ },
+ ];
+
+ const plan = planManifestPullWrites({
+ manifest,
+ baseManifest: manifest,
+ scannedFiles,
+ workspaceUniversalIdentifiers: new Set(),
+ });
+
+ expect(plan.writes.map(({ relativePath }) => relativePath)).toEqual([
+ 'src/views/overview.ts',
+ ]);
+ expect(plan.writes[0].content).not.toContain(PET_NAME_VIEW_FIELD_UID);
+ expect(plan.unchanged).toContainEqual(
+ expect.objectContaining({ universalIdentifier: PET_NAME_VIEW_FIELD_UID }),
+ );
+ expect(plan.deletions).toEqual([]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/preserve-nested-pull-entities.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/preserve-nested-pull-entities.spec.ts
new file mode 100644
index 00000000000..f1443296a13
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/preserve-nested-pull-entities.spec.ts
@@ -0,0 +1,179 @@
+import { describe, expect, it } from 'vitest';
+
+import { type PullEntity } from '@/app/pull/build-pull-entities';
+import { type PullWrite } from '@/app/pull/plan-pull-writes';
+import { preserveNestedPullEntities } from '@/app/pull/preserve-nested-pull-entities';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+
+const LAYOUT_IDENTIFIER = '11111111-1111-4111-8111-111111111111';
+const TAB_IDENTIFIER = '22222222-2222-4222-8222-222222222222';
+const WIDGET_IDENTIFIER = '33333333-3333-4333-8333-333333333333';
+const LOCAL_WIDGET_IDENTIFIER = '44444444-4444-4444-8444-444444444444';
+const LAYOUT_PATH = 'src/page-layouts/company.ts';
+const TAB_PATH = 'src/page-layout-tabs/overview.ts';
+
+const widget = { universalIdentifier: WIDGET_IDENTIFIER };
+const tab = { universalIdentifier: TAB_IDENTIFIER, widgets: [widget] };
+const layout = { universalIdentifier: LAYOUT_IDENTIFIER, tabs: [tab] };
+const createEntity = (
+ kind: 'pageLayout' | 'pageLayoutTab',
+ config: { universalIdentifier: string } & Record<string, unknown>,
+): PullEntity => ({
+ kind,
+ universalIdentifier: config.universalIdentifier,
+ config,
+ definer: kind === 'pageLayout' ? 'definePageLayout' : 'definePageLayoutTab',
+ enumBindings: [],
+ defaultFolder: 'src',
+ fileSuffix: '.ts',
+ fileBaseName: 'fixture',
+ parentName: null,
+});
+const layoutEntity = createEntity('pageLayout', { ...layout, tabs: [] });
+const tabEntity = createEntity('pageLayoutTab', tab);
+const layoutFile: ScannedSourceFile = {
+ relativePath: LAYOUT_PATH,
+ entityKey: 'pageLayouts',
+ targetFunctionName: 'definePageLayout',
+ universalIdentifier: LAYOUT_IDENTIFIER,
+ isReadable: true,
+ config: layout,
+};
+const tabFile: ScannedSourceFile = {
+ relativePath: TAB_PATH,
+ entityKey: 'pageLayoutTabs',
+ targetFunctionName: 'definePageLayoutTab',
+ universalIdentifier: TAB_IDENTIFIER,
+ isReadable: true,
+ config: tab,
+};
+const createWrite = (
+ entity: PullEntity,
+ relativePath: string,
+ isRegeneration = true,
+): PullWrite => ({
+ kind: entity.kind,
+ universalIdentifier: entity.universalIdentifier,
+ relativePath,
+ isRegeneration,
+ content: '',
+ requiredSdkExports: [],
+});
+const layoutWrite = createWrite(layoutEntity, LAYOUT_PATH);
+const tabWrite = createWrite(tabEntity, TAB_PATH);
+
+const protect = (
+ options: Partial<Parameters<typeof preserveNestedPullEntities>[0]> = {},
+) =>
+ preserveNestedPullEntities({
+ entities: [layoutEntity, tabEntity],
+ baseEntities: [],
+ protectedIdentifiers: new Set([
+ LAYOUT_IDENTIFIER,
+ TAB_IDENTIFIER,
+ WIDGET_IDENTIFIER,
+ ]),
+ writes: [layoutWrite],
+ deletions: [],
+ scannedFiles: [layoutFile],
+ ...options,
+ });
+
+describe('preserveNestedPullEntities', () => {
+ it.each(['unchanged', 'new'])(
+ 'allows moving a nested definition into a %s file that retains it',
+ (destination) => {
+ const result = protect({
+ scannedFiles: [layoutFile, ...(destination === 'new' ? [] : [tabFile])],
+ writes:
+ destination === 'new'
+ ? [layoutWrite, createWrite(tabEntity, TAB_PATH, false)]
+ : [layoutWrite],
+ });
+
+ expect(result.skipped).toEqual([]);
+ expect(result.writes).toContainEqual(layoutWrite);
+ },
+ );
+
+ it('does not count an exported definition without a retained or written destination', () => {
+ const result = protect();
+
+ expect(result.writes).toEqual([]);
+ expect(result.skipped).toEqual([
+ expect.objectContaining({ universalIdentifier: LAYOUT_IDENTIFIER }),
+ ]);
+ });
+
+ it.each(['write', 'delete'])(
+ 'rechecks the source %s when the destination replacement is skipped',
+ (operation) => {
+ const result = protect({
+ baseEntities: [createEntity('pageLayout', layout), tabEntity],
+ scannedFiles: [
+ layoutFile,
+ {
+ ...tabFile,
+ config: {
+ ...tab,
+ widgets: [{ universalIdentifier: LOCAL_WIDGET_IDENTIFIER }],
+ },
+ },
+ ],
+ writes: operation === 'write' ? [layoutWrite, tabWrite] : [tabWrite],
+ deletions:
+ operation === 'delete'
+ ? [
+ {
+ universalIdentifier: LAYOUT_IDENTIFIER,
+ relativePath: LAYOUT_PATH,
+ },
+ ]
+ : [],
+ });
+
+ expect(result.writes).toEqual([]);
+ expect(result.deletions).toEqual([]);
+ expect(
+ result.skipped
+ .map(({ universalIdentifier }) => universalIdentifier)
+ .sort(),
+ ).toEqual([LAYOUT_IDENTIFIER, TAB_IDENTIFIER]);
+ },
+ );
+
+ it('allows moving a definition into the original contents of a skipped destination', () => {
+ const result = protect({
+ scannedFiles: [
+ layoutFile,
+ {
+ ...tabFile,
+ config: {
+ ...tab,
+ widgets: [widget, { universalIdentifier: LOCAL_WIDGET_IDENTIFIER }],
+ },
+ },
+ ],
+ writes: [layoutWrite, tabWrite],
+ });
+
+ expect(result.writes).toEqual([layoutWrite]);
+ expect(result.skipped).toEqual([
+ expect.objectContaining({ universalIdentifier: TAB_IDENTIFIER }),
+ ]);
+ });
+
+ it('does not count a file scheduled for deletion as retaining a definition', () => {
+ const result = protect({
+ baseEntities: [tabEntity],
+ scannedFiles: [layoutFile, tabFile],
+ deletions: [
+ { universalIdentifier: TAB_IDENTIFIER, relativePath: TAB_PATH },
+ ],
+ });
+
+ expect(result.writes).toEqual([]);
+ expect(result.deletions).toEqual([]);
+ expect(result.skipped).toHaveLength(2);
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/print-typescript-value.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/print-typescript-value.spec.ts
new file mode 100644
index 00000000000..dfe6ea0c241
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/print-typescript-value.spec.ts
@@ -0,0 +1,59 @@
+import { printTypescriptValue } from '@/app/pull/print-typescript-value';
+import { describe, expect, it } from 'vitest';
+
+const evaluatePrinted = (printed: string): unknown =>
+ new Function(`return (${printed});`)();
+
+describe('printTypescriptValue', () => {
+ it('should escape characters that would otherwise break the generated literal', () => {
+ const value = {
+ description: 'first\r\nsecond',
+ separators: '

',
+ quoted: "Tim's",
+ backslash: 'a\\b',
+ };
+
+ const printed = printTypescriptValue({ value });
+
+ expect(printed).toContain("description: 'first\\r\\nsecond',");
+ expect(printed).toContain("separators: '\\u2028\\u2029',");
+ expect(evaluatePrinted(printed)).toEqual(value);
+ });
+
+ it('should keep a __proto__ key as an own property instead of setting the prototype', () => {
+ const value = JSON.parse('{"__proto__": "not-a-prototype"}');
+
+ const printed = printTypescriptValue({ value });
+
+ expect(printed).toContain("['__proto__']: 'not-a-prototype',");
+
+ const evaluated = evaluatePrinted(printed) as Record<string, unknown>;
+
+ expect(Object.prototype.hasOwnProperty.call(evaluated, '__proto__')).toBe(
+ true,
+ );
+ expect(Object.getPrototypeOf(evaluated)).toBe(Object.prototype);
+ });
+
+ it('should quote a key that is not a valid identifier', () => {
+ expect(printTypescriptValue({ value: { 'fr-FR': 1 } })).toContain(
+ "'fr-FR': 1,",
+ );
+ });
+
+ it('should drop undefined properties and keep null ones', () => {
+ expect(
+ printTypescriptValue({ value: { kept: null, dropped: undefined } }),
+ ).toBe('{\n kept: null,\n}');
+ });
+ it('preserves lone surrogates and non-BMP text through UTF-8 source files', () => {
+ const value = {
+ label: String.fromCharCode(0xd800) + '😀' + String.fromCharCode(0xdfff),
+ };
+ const printed = printTypescriptValue({ value });
+
+ expect(
+ evaluatePrinted(Buffer.from(printed, 'utf8').toString('utf8')),
+ ).toEqual(value);
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts
new file mode 100644
index 00000000000..bd96c9640e6
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts
@@ -0,0 +1,1215 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { generateMessageId } from 'twenty-shared/i18n';
+
+import { collectSourceFingerprints } from '@/app/pull/collect-source-fingerprints';
+import { pullApplication } from '@/app/pull/pull-application';
+import { writePullBase } from '@/app/pull/write-pull-base';
+import { parseAppExport } from '@/app/parse-app-export';
+import { readSourceIdentity } from '@/app/worker/read-source-identity';
+const readAppIdentity = ({ appPath }: { appPath: string }) =>
+ readSourceIdentity({ appPath, signal: new AbortController().signal });
+import { type PullTarget as AppPullTarget } from '@/app/types/pull-target.type';
+import { type ToolingResult as BuildResult } from '@/app/types/tooling-result.type';
+import * as fileUtilities from '@/app/fs-utils';
+import { type AppExportCoverageEntry } from '@/app/types/app-export.type';
+import * as sourceScanner from '@/app/source/scan-project-source-files';
+
+const APPLICATION_IDENTIFIER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const OBJECT_IDENTIFIER = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const FIELD_IDENTIFIER = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const WORKSPACE_IDENTIFIER = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+const OTHER_IDENTIFIER = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
+const INDEX_IDENTIFIER = 'ffffffff-ffff-4fff-8fff-ffffffffffff';
+const STANDALONE_FIELD_IDENTIFIER = 'abababab-abab-4aba-8aba-abababababab';
+const STANDALONE_FIELD_PATH = 'src/fields/rating.ts';
+const TARGET: AppPullTarget = {
+ apiUrl: 'https://example.test',
+ workspaceId: WORKSPACE_IDENTIFIER,
+};
+const OBJECT_PATH = 'src/objects/pet.object.ts';
+const BASE_PATH = '.twenty/cli/pull-base.json';
+const APPLICATION_EXPORT_COVERAGE_STATUSES = [
+ 'EXPORTED',
+ 'UNSUPPORTED',
+ 'FOREIGN_OWNED',
+ 'EXCLUDED',
+ 'ENGINE_DERIVED',
+ 'FUTURE_STATUS',
+];
+
+const createExport = ({
+ includeObject = true,
+ label = 'Pet',
+ coverage = [],
+}: {
+ includeObject?: boolean;
+ label?: string;
+ coverage?: AppExportCoverageEntry[];
+} = {}) => ({
+ application: {
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ displayName: 'Pets',
+ sourceType: 'LOCAL',
+ },
+ manifest: {
+ application: {
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ displayName: 'Pets',
+ description: '',
+ defaultRoleUniversalIdentifier: OTHER_IDENTIFIER,
+ packageJsonChecksum: null,
+ yarnLockChecksum: null,
+ },
+ objects: includeObject
+ ? [
+ {
+ universalIdentifier: OBJECT_IDENTIFIER,
+ nameSingular: 'pet',
+ namePlural: 'pets',
+ labelSingular: label,
+ labelPlural: 'Pets',
+ labelIdentifierFieldMetadataUniversalIdentifier: FIELD_IDENTIFIER,
+ fields: [
+ {
+ universalIdentifier: FIELD_IDENTIFIER,
+ name: 'name',
+ label: 'Name',
+ type: 'TEXT',
+ },
+ ],
+ },
+ ]
+ : [],
+ fields: [],
+ indexes: [],
+ logicFunctions: [],
+ frontComponents: [],
+ permissionFlags: [],
+ roles: [],
+ skills: [],
+ agents: [],
+ publicAssets: [],
+ views: [],
+ viewFields: [],
+ navigationMenuItems: [],
+ pageLayouts: [],
+ pageLayoutTabs: [],
+ pageLayoutWidgets: [],
+ commandMenuItems: [],
+ timelineActivityTypes: [],
+ settingsMenuItems: [],
+ },
+ coverage,
+ files: [],
+});
+
+const sha256 = (content: string) =>
+ createHash('sha256').update(content).digest('hex');
+
+const requireSuccess = <TData>(result: BuildResult<TData>): TData => {
+ expect(result.success, JSON.stringify(result)).toBe(true);
+ if (!result.success) {
+ throw new Error(result.error.message);
+ }
+ return result.data;
+};
+
+describe('programmatic application pull', () => {
+ let appPath: string;
+ const read = (relativePath: string) =>
+ readFile(join(appPath, relativePath), 'utf8');
+ const pull = async (
+ applicationExport: unknown = createExport(),
+ target = TARGET,
+ signal?: AbortSignal,
+ ) => {
+ try {
+ return await pullApplication({
+ appPath,
+ applicationExport: parseAppExport({
+ value: applicationExport,
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ }),
+ target,
+ signal: signal ?? new AbortController().signal,
+ });
+ } catch (error) {
+ return {
+ success: false as const,
+ error: { code: 'PULL_FAILED', message: String(error) },
+ diagnostics: [],
+ };
+ }
+ };
+ const recordAppliedBase = async () =>
+ writePullBase({
+ appPath,
+ manifest: parseAppExport({
+ value: createExport(),
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ }).manifest,
+ target: TARGET,
+ sourceFingerprints: await collectSourceFingerprints(appPath),
+ signal: new AbortController().signal,
+ });
+ const addStandaloneField = async () => {
+ await mkdir(join(appPath, 'src/fields'), { recursive: true });
+ await writeFile(
+ join(appPath, STANDALONE_FIELD_PATH),
+ `import { defineField, FieldType } from 'twenty-sdk/define';
+export default defineField({
+ universalIdentifier: '${STANDALONE_FIELD_IDENTIFIER}',
+ objectUniversalIdentifier: '${OBJECT_IDENTIFIER}',
+ name: 'rating',
+ label: 'Rating',
+ type: FieldType.NUMBER,
+});
+`,
+ );
+ const exported = createExport();
+ exported.manifest.objects[0].fields.push({
+ universalIdentifier: STANDALONE_FIELD_IDENTIFIER,
+ name: 'rating',
+ label: 'Rating',
+ type: 'NUMBER',
+ });
+ return exported;
+ };
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-sdk-pull-'));
+ await mkdir(join(appPath, 'node_modules'));
+ await symlink(
+ resolve('../twenty-sdk'),
+ join(appPath, 'node_modules/twenty-sdk'),
+ 'dir',
+ );
+ await writeFile(join(appPath, 'package.json'), '{"name":"pull-fixture"}\n');
+ });
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('writes source and a normalized target-bound base, without returning source contents', async () => {
+ const data = requireSuccess(
+ await pull(createExport(), {
+ apiUrl: 'https://EXAMPLE.test/',
+ workspaceId: WORKSPACE_IDENTIFIER.toUpperCase(),
+ }),
+ );
+ expect(data.base.status).toBe('missing');
+ expect(data.writes).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ relativePath: OBJECT_PATH }),
+ ]),
+ );
+ expect(data.writes.every((write) => !('content' in write))).toBe(true);
+ expect(await read(OBJECT_PATH)).toContain("labelSingular: 'Pet'");
+ expect(JSON.parse(await read(BASE_PATH))).toMatchObject({
+ version: 2,
+ target: TARGET,
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+ it.each([
+ { hasBase: true, uppercaseIdentifier: false },
+ { hasBase: false, uppercaseIdentifier: false },
+ { hasBase: true, uppercaseIdentifier: true },
+ ])(
+ 'keeps standalone fields separate, base: $hasBase, uppercase identifier: $uppercaseIdentifier',
+ async ({ hasBase, uppercaseIdentifier }) => {
+ requireSuccess(await pull());
+ const exported = await addStandaloneField();
+ if (uppercaseIdentifier) {
+ await writeFile(
+ join(appPath, STANDALONE_FIELD_PATH),
+ (await read(STANDALONE_FIELD_PATH)).replace(
+ STANDALONE_FIELD_IDENTIFIER,
+ STANDALONE_FIELD_IDENTIFIER.toUpperCase(),
+ ),
+ );
+ }
+ const originalField = await read(STANDALONE_FIELD_PATH);
+
+ if (hasBase) {
+ await writePullBase({
+ appPath,
+ manifest: exported.manifest,
+ target: TARGET,
+ sourceFingerprints: await collectSourceFingerprints(appPath),
+ signal: new AbortController().signal,
+ });
+ } else {
+ await rm(join(appPath, BASE_PATH));
+ }
+ exported.manifest.objects[0].labelSingular = 'Changed remotely';
+
+ const result = requireSuccess(await pull(exported));
+ expect(result.skipped).toEqual([]);
+ expect(result.deletions).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain('Changed remotely');
+ expect(await read(OBJECT_PATH)).toContain(FIELD_IDENTIFIER);
+ expect(await read(OBJECT_PATH)).not.toContain(
+ STANDALONE_FIELD_IDENTIFIER,
+ );
+ if (hasBase) {
+ expect(await read(STANDALONE_FIELD_PATH)).toBe(originalField);
+ }
+ expect(JSON.parse(await read(BASE_PATH)).manifest).toEqual(
+ exported.manifest,
+ );
+ expect(requireSuccess(await pull(exported)).writes).toEqual([]);
+
+ await writeFile(
+ join(appPath, STANDALONE_FIELD_PATH),
+ (await read(STANDALONE_FIELD_PATH)).replace('Rating', 'Local rating'),
+ );
+ exported.manifest.objects[0].fields[1].label = 'Remote rating';
+
+ const fieldUpdate = requireSuccess(await pull(exported));
+ expect(fieldUpdate.writes).toEqual([
+ expect.objectContaining({ relativePath: STANDALONE_FIELD_PATH }),
+ ]);
+ expect(fieldUpdate.overwrittenLocalChanges).toEqual([
+ {
+ universalIdentifier: STANDALONE_FIELD_IDENTIFIER,
+ relativePath: STANDALONE_FIELD_PATH,
+ },
+ ]);
+ expect(await read(STANDALONE_FIELD_PATH)).toContain('Remote rating');
+ expect(requireSuccess(await pull(exported)).writes).toEqual([]);
+ },
+ );
+ it('repairs an already duplicated standalone field even when the export is unchanged', async () => {
+ requireSuccess(await pull());
+ const exported = await addStandaloneField();
+ await rm(join(appPath, STANDALONE_FIELD_PATH));
+ requireSuccess(await pull(exported));
+ await addStandaloneField();
+
+ const repaired = requireSuccess(await pull(exported));
+
+ expect(repaired.skipped).toEqual([]);
+ expect(repaired.writes).toEqual([
+ expect.objectContaining({ relativePath: OBJECT_PATH }),
+ ]);
+ expect(await read(OBJECT_PATH)).not.toContain(STANDALONE_FIELD_IDENTIFIER);
+ expect(await readdir(join(appPath, 'src/fields'))).toEqual(['rating.ts']);
+ expect(await read(STANDALONE_FIELD_PATH)).toContain(
+ STANDALONE_FIELD_IDENTIFIER,
+ );
+ expect(requireSuccess(await pull(exported)).writes).toEqual([]);
+ });
+ it('preserves covered standalone fields and removes confirmed remote deletions', async () => {
+ requireSuccess(await pull());
+ const exported = await addStandaloneField();
+ requireSuccess(await pull(exported));
+ const originalField = await read(STANDALONE_FIELD_PATH);
+ const withoutField = createExport({
+ label: 'Changed remotely',
+ coverage: [
+ {
+ metadataName: 'fieldMetadata',
+ universalIdentifier: STANDALONE_FIELD_IDENTIFIER,
+ status: 'UNSUPPORTED',
+ reason: 'unsupported field',
+ },
+ ],
+ });
+
+ expect(requireSuccess(await pull(withoutField)).deletions).toEqual([]);
+ expect(await read(STANDALONE_FIELD_PATH)).toBe(originalField);
+ const removed = requireSuccess(
+ await pull({ ...withoutField, coverage: [] }),
+ );
+ expect(removed.deletions).toEqual([
+ {
+ universalIdentifier: STANDALONE_FIELD_IDENTIFIER,
+ relativePath: STANDALONE_FIELD_PATH,
+ },
+ ]);
+ await expect(read(STANDALONE_FIELD_PATH)).rejects.toThrow();
+ });
+ it('reads identity while unrelated definitions cannot build', async () => {
+ requireSuccess(await pull());
+ await writeFile(
+ join(appPath, 'src/broken.object.ts'),
+ "import 'missing-dependency'; export default defineObject({",
+ );
+ expect(
+ requireSuccess(await readAppIdentity({ appPath })).application,
+ ).toEqual({
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ displayName: 'Pets',
+ });
+ });
+ it('returns no identity for an empty project', async () => {
+ expect(requireSuccess(await readAppIdentity({ appPath }))).toEqual({
+ application: null,
+ });
+ });
+ it('rejects ambiguous or unreadable application declarations before writing', async () => {
+ requireSuccess(await pull());
+ const base = await read(BASE_PATH);
+ await writeFile(
+ join(appPath, 'src/second.ts'),
+ await read('src/application.config.ts'),
+ );
+ expect(await pull()).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED' },
+ });
+ await rm(join(appPath, 'src/second.ts'));
+ await writeFile(
+ join(appPath, 'src/application.config.ts'),
+ "import 'missing-package'; export default defineApplication({ universalIdentifier: 'broken' });",
+ );
+ expect(await readAppIdentity({ appPath })).toMatchObject({
+ success: false,
+ error: { code: 'IDENTITY_READ_FAILED' },
+ });
+ expect(await pull()).toMatchObject({ success: false });
+ expect(await read(BASE_PATH)).toBe(base);
+ });
+ it('rejects a different application and accepts the same UUID in uppercase', async () => {
+ requireSuccess(await pull());
+ const source = await read('src/application.config.ts');
+ await writeFile(
+ join(appPath, 'src/application.config.ts'),
+ source.replace(APPLICATION_IDENTIFIER, OTHER_IDENTIFIER),
+ );
+ expect(await pull()).toMatchObject({
+ success: false,
+ error: {
+ code: 'PULL_FAILED',
+ message: expect.stringContaining('different directory'),
+ },
+ });
+ await writeFile(
+ join(appPath, 'src/application.config.ts'),
+ source.replace(
+ APPLICATION_IDENTIFIER,
+ APPLICATION_IDENTIFIER.toUpperCase(),
+ ),
+ );
+ requireSuccess(await pull());
+ });
+ it('keeps local edits until the remote changes, then reports their overwrite', async () => {
+ requireSuccess(await pull());
+ const local = (await read(OBJECT_PATH)).replace(
+ "labelSingular: 'Pet'",
+ "labelSingular: 'My local pet'",
+ );
+ await writeFile(join(appPath, OBJECT_PATH), local);
+ expect(requireSuccess(await pull()).writes).toEqual([]);
+ expect(await read(OBJECT_PATH)).toBe(local);
+ const changed = requireSuccess(
+ await pull(createExport({ label: 'Remote pet' })),
+ );
+ expect(changed.overwrittenLocalChanges).toEqual([
+ { universalIdentifier: OBJECT_IDENTIFIER, relativePath: OBJECT_PATH },
+ ]);
+ expect(await read(OBJECT_PATH)).toContain("labelSingular: 'Remote pet'");
+ });
+ it('does not report untouched generated files as conflicting edits', async () => {
+ requireSuccess(await pull());
+ expect(
+ requireSuccess(await pull(createExport({ label: 'Remote pet' })))
+ .overwrittenLocalChanges,
+ ).toEqual([]);
+ });
+ it('does not report a hand-written file that is unchanged since apply fingerprinted it', async () => {
+ requireSuccess(await pull());
+ await writeFile(
+ join(appPath, OBJECT_PATH),
+ (await read(OBJECT_PATH)).replace(
+ "labelSingular: 'Pet'",
+ 'labelSingular: "Pet"',
+ ),
+ );
+ await recordAppliedBase();
+ const changed = requireSuccess(
+ await pull(createExport({ label: 'Remote pet' })),
+ );
+ expect(changed.overwrittenLocalChanges).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain("labelSingular: 'Remote pet'");
+ });
+ it('reports an edit made after apply fingerprinted the file', async () => {
+ requireSuccess(await pull());
+ await recordAppliedBase();
+ await writeFile(
+ join(appPath, OBJECT_PATH),
+ (await read(OBJECT_PATH)).replace(
+ "labelSingular: 'Pet'",
+ "labelSingular: 'My local pet'",
+ ),
+ );
+ expect(
+ requireSuccess(await pull(createExport({ label: 'Remote pet' })))
+ .overwrittenLocalChanges,
+ ).toEqual([
+ { universalIdentifier: OBJECT_IDENTIFIER, relativePath: OBJECT_PATH },
+ ]);
+ });
+ it('carries fingerprints across pulls, updating rewritten files and dropping deleted ones', async () => {
+ requireSuccess(await pull());
+ await recordAppliedBase();
+ const applied = JSON.parse(await read(BASE_PATH)).sourceFingerprints;
+ requireSuccess(await pull(createExport({ label: 'Remote pet' })));
+ const pulled = JSON.parse(await read(BASE_PATH)).sourceFingerprints;
+ expect(pulled[OBJECT_PATH]).toBe(sha256(await read(OBJECT_PATH)));
+ expect(pulled[OBJECT_PATH]).not.toBe(applied[OBJECT_PATH]);
+ expect(pulled['src/application.config.ts']).toBe(
+ applied['src/application.config.ts'],
+ );
+ requireSuccess(await pull(createExport({ includeObject: false })));
+ expect(
+ JSON.parse(await read(BASE_PATH)).sourceFingerprints,
+ ).not.toHaveProperty([OBJECT_PATH]);
+ });
+ it.each(APPLICATION_EXPORT_COVERAGE_STATUSES)(
+ 'preserves a base entity still mentioned by %s coverage',
+ async (status) => {
+ requireSuccess(await pull());
+ const original = await read(OBJECT_PATH);
+ const data = requireSuccess(
+ await pull(
+ createExport({
+ includeObject: false,
+ coverage: [
+ {
+ metadataName: 'objectMetadata',
+ universalIdentifier: OBJECT_IDENTIFIER,
+ status,
+ reason: null,
+ },
+ ],
+ }),
+ ),
+ );
+ expect(data.deletions).toEqual([]);
+ expect(await read(OBJECT_PATH)).toBe(original);
+ },
+ );
+ it('preserves an index skipped because its object is no longer exported', async () => {
+ const exported = createExport();
+ const index = {
+ universalIdentifier: INDEX_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_IDENTIFIER,
+ isUnique: false,
+ fields: [{ fieldUniversalIdentifier: FIELD_IDENTIFIER }],
+ };
+ const withIndex = {
+ ...exported,
+ manifest: { ...exported.manifest, indexes: [index] },
+ };
+ const first = requireSuccess(await pull(withIndex));
+ const indexPath = first.writes.find(
+ (write) => write.kind === 'index',
+ )?.relativePath;
+ if (!indexPath) {
+ throw new Error('Missing index fixture');
+ }
+ const before = await read(indexPath);
+ const result = requireSuccess(
+ await pull({
+ ...withIndex,
+ manifest: { ...withIndex.manifest, objects: [] },
+ }),
+ );
+ expect(result.skipped).toEqual([
+ expect.objectContaining({ universalIdentifier: INDEX_IDENTIFIER }),
+ ]);
+ expect(
+ result.deletions.every(
+ (deletion) => deletion.universalIdentifier !== INDEX_IDENTIFIER,
+ ),
+ ).toBe(true);
+ expect(await read(indexPath)).toBe(before);
+ });
+
+ it.each(['covered', 'covered-windows', 'no-base', 'confirmed-deletion'])(
+ 'preserves nested definitions unless their remote deletion is confirmed: %s',
+ async (scenario) => {
+ const originalExport = createExport();
+ originalExport.manifest.objects[0].fields.push({
+ universalIdentifier: OTHER_IDENTIFIER,
+ name: 'note',
+ label: 'Note',
+ type: 'TEXT',
+ });
+ requireSuccess(await pull(originalExport));
+ const original = await read(OBJECT_PATH);
+ const changed = createExport({ label: 'Changed remotely' });
+
+ if (scenario.startsWith('covered')) {
+ changed.coverage.push({
+ metadataName: 'fieldMetadata',
+ universalIdentifier: OTHER_IDENTIFIER,
+ status: 'UNSUPPORTED',
+ reason: 'unsupported relation',
+ });
+ }
+ if (scenario === 'no-base') {
+ await rm(join(appPath, BASE_PATH));
+ }
+ if (scenario === 'covered-windows') {
+ const scan = sourceScanner.scanProjectSourceFiles;
+ vi.spyOn(sourceScanner, 'scanProjectSourceFiles').mockImplementation(
+ async (...options) =>
+ (await scan(...options)).map((file) => ({
+ ...file,
+ relativePath: file.relativePath.split('/').join('\\'),
+ })),
+ );
+ }
+
+ const result = requireSuccess(await pull(changed));
+
+ if (scenario === 'confirmed-deletion') {
+ expect(result.skipped).toEqual([]);
+ expect(await read(OBJECT_PATH)).not.toContain(OTHER_IDENTIFIER);
+ expect(await read(OBJECT_PATH)).toContain('Changed remotely');
+ } else {
+ expect(await read(OBJECT_PATH)).toBe(original);
+ expect(result.skipped).toContainEqual({
+ kind: 'object',
+ universalIdentifier: OBJECT_IDENTIFIER,
+ reason: expect.stringContaining(OTHER_IDENTIFIER),
+ });
+ }
+ },
+ );
+ it('retries a skipped replacement and applies a later confirmed nested deletion', async () => {
+ const originalExport = createExport();
+ originalExport.manifest.objects[0].fields.push({
+ universalIdentifier: OTHER_IDENTIFIER,
+ name: 'note',
+ label: 'Note',
+ type: 'TEXT',
+ });
+ requireSuccess(await pull(originalExport));
+ const original = await read(OBJECT_PATH);
+ const partialExport = createExport({
+ label: 'Changed remotely',
+ coverage: [
+ {
+ metadataName: 'fieldMetadata',
+ universalIdentifier: OTHER_IDENTIFIER,
+ status: 'UNSUPPORTED',
+ reason: 'unsupported field',
+ },
+ ],
+ });
+ partialExport.manifest.application.displayName = 'Changed application';
+
+ requireSuccess(await pull(partialExport));
+ expect(await read(OBJECT_PATH)).toBe(original);
+ const localApplication = (await read('src/application.config.ts')).replace(
+ 'Changed application',
+ 'Locally edited application',
+ );
+ await writeFile(
+ join(appPath, 'src/application.config.ts'),
+ localApplication,
+ );
+
+ const repeated = requireSuccess(await pull(partialExport));
+ expect(repeated.skipped).toContainEqual(
+ expect.objectContaining({ universalIdentifier: OBJECT_IDENTIFIER }),
+ );
+ expect(repeated.writes).toEqual([]);
+
+ const completed = requireSuccess(
+ await pull({ ...partialExport, coverage: [] }),
+ );
+ expect(completed.writes).toEqual([
+ expect.objectContaining({ relativePath: OBJECT_PATH }),
+ ]);
+ expect(completed.skipped).toEqual([]);
+ expect(completed.overwrittenLocalChanges).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain('Changed remotely');
+ expect(await read(OBJECT_PATH)).not.toContain(OTHER_IDENTIFIER);
+ expect(await read('src/application.config.ts')).toBe(localApplication);
+ expect(
+ requireSuccess(await pull({ ...partialExport, coverage: [] })).writes,
+ ).toEqual([]);
+ });
+
+ it('retries a skipped file without a prior base once its local-only child is removed', async () => {
+ requireSuccess(await pull());
+ const sourceWithoutChild = await read(OBJECT_PATH);
+ const originalExport = createExport();
+ originalExport.manifest.objects[0].fields.push({
+ universalIdentifier: OTHER_IDENTIFIER,
+ name: 'note',
+ label: 'Note',
+ type: 'TEXT',
+ });
+ requireSuccess(await pull(originalExport));
+ await rm(join(appPath, BASE_PATH));
+ const changed = createExport({ label: 'Changed remotely' });
+ expect(requireSuccess(await pull(changed)).skipped).toHaveLength(1);
+
+ await writeFile(join(appPath, OBJECT_PATH), sourceWithoutChild);
+
+ const result = requireSuccess(await pull(changed));
+ expect(result.writes).toContainEqual(
+ expect.objectContaining({ relativePath: OBJECT_PATH }),
+ );
+ expect(result.skipped).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain('Changed remotely');
+ });
+
+ it('retries a skipped application declaration without a prior base', async () => {
+ requireSuccess(await pull());
+ const applicationPath = 'src/application.config.ts';
+ const originalApplication = await read(applicationPath);
+ await writeFile(
+ join(appPath, applicationPath),
+ originalApplication.replace(
+ "displayName: 'Pets',",
+ `displayName: 'Pets', postInstallLogicFunction: { universalIdentifier: '${OTHER_IDENTIFIER}' },`,
+ ),
+ );
+ await rm(join(appPath, BASE_PATH));
+ const changed = createExport();
+ changed.manifest.application.displayName = 'Changed remotely';
+
+ expect(requireSuccess(await pull(changed)).skipped).toContainEqual(
+ expect.objectContaining({
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ }),
+ );
+ await writeFile(join(appPath, applicationPath), originalApplication);
+
+ const result = requireSuccess(await pull(changed));
+ expect(result.skipped).toEqual([]);
+ expect(result.writes).toContainEqual(
+ expect.objectContaining({ relativePath: applicationPath }),
+ );
+ expect(await read(applicationPath)).toContain('Changed remotely');
+ });
+
+ it('retains a covered whole-file base until its remote deletion is confirmed', async () => {
+ requireSuccess(await pull());
+ const partialExport = createExport({
+ includeObject: false,
+ coverage: [
+ {
+ metadataName: 'objectMetadata',
+ universalIdentifier: OBJECT_IDENTIFIER,
+ status: 'UNSUPPORTED',
+ reason: 'unsupported object',
+ },
+ ],
+ });
+ requireSuccess(await pull(partialExport));
+ const result = requireSuccess(
+ await pull({ ...partialExport, coverage: [] }),
+ );
+
+ expect(result.deletions).toEqual([
+ { universalIdentifier: OBJECT_IDENTIFIER, relativePath: OBJECT_PATH },
+ ]);
+ await expect(read(OBJECT_PATH)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('preserves application edits while a newly skipped default role is retried', async () => {
+ const exported = createExport();
+ const role = {
+ universalIdentifier: OTHER_IDENTIFIER,
+ label: 'Reader',
+ objectPermissions: [
+ {
+ universalIdentifier: INDEX_IDENTIFIER,
+ objectUniversalIdentifier: OBJECT_IDENTIFIER,
+ canReadObjectRecords: true,
+ },
+ ],
+ };
+ requireSuccess(
+ await pull({
+ ...exported,
+ manifest: { ...exported.manifest, roles: [role] },
+ }),
+ );
+ await rm(join(appPath, BASE_PATH));
+ const partialExport = {
+ ...exported,
+ manifest: {
+ ...exported.manifest,
+ roles: [{ ...role, label: 'Changed role', objectPermissions: [] }],
+ },
+ };
+ const first = requireSuccess(await pull(partialExport));
+ expect(first.skipped).toContainEqual(
+ expect.objectContaining({ universalIdentifier: OTHER_IDENTIFIER }),
+ );
+ const localApplication = (await read('src/application.config.ts')).replace(
+ 'Pets',
+ 'Locally edited application',
+ );
+ await writeFile(
+ join(appPath, 'src/application.config.ts'),
+ localApplication,
+ );
+
+ const second = requireSuccess(await pull(partialExport));
+ expect(second.skipped).toContainEqual(
+ expect.objectContaining({ universalIdentifier: OTHER_IDENTIFIER }),
+ );
+ expect(second.writes).toEqual([]);
+ expect(await read('src/application.config.ts')).toBe(localApplication);
+ });
+
+ it('deletes a remotely removed base entity and preserves a local-only definition', async () => {
+ requireSuccess(await pull());
+ const local = (await read(OBJECT_PATH))
+ .split(OBJECT_IDENTIFIER)
+ .join(OTHER_IDENTIFIER);
+ await writeFile(join(appPath, 'src/objects/local.object.ts'), local);
+ const data = requireSuccess(
+ await pull(createExport({ includeObject: false })),
+ );
+ expect(data.deletions).toEqual([
+ { universalIdentifier: OBJECT_IDENTIFIER, relativePath: OBJECT_PATH },
+ ]);
+ expect(data.localOnlyRelativePaths).toEqual([
+ 'src/objects/local.object.ts',
+ ]);
+ await expect(read(OBJECT_PATH)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(await read('src/objects/local.object.ts')).toBe(local);
+ });
+ it.each([
+ 'origin',
+ 'workspace',
+ 'application',
+ 'unbound',
+ 'unreadable',
+ 'missing',
+ ])('does not infer deletions from a %s base', async (kind) => {
+ requireSuccess(await pull());
+ const exported = createExport();
+ const base = {
+ version: kind === 'unbound' ? 1 : 2,
+ target: {
+ apiUrl: kind === 'origin' ? 'https://other.test' : TARGET.apiUrl,
+ workspaceId:
+ kind === 'workspace' ? OTHER_IDENTIFIER : TARGET.workspaceId,
+ },
+ applicationUniversalIdentifier:
+ kind === 'application' ? OTHER_IDENTIFIER : APPLICATION_IDENTIFIER,
+ manifest: {
+ ...exported.manifest,
+ application: {
+ ...exported.manifest.application,
+ universalIdentifier:
+ kind === 'application' ? OTHER_IDENTIFIER : APPLICATION_IDENTIFIER,
+ },
+ },
+ };
+ await writeFile(
+ join(appPath, BASE_PATH),
+ kind === 'unreadable' ? '{broken' : JSON.stringify(base),
+ );
+ if (kind === 'missing') {
+ await rm(join(appPath, BASE_PATH));
+ }
+ const data = requireSuccess(
+ await pull(createExport({ includeObject: false })),
+ );
+ expect(data.base.status).toBe(
+ ['origin', 'workspace', 'application'].includes(kind)
+ ? 'other-target'
+ : kind,
+ );
+ expect(data.deletions).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain('defineObject');
+ });
+ it('does not infer deletions from malformed reconciliation state', async () => {
+ requireSuccess(await pull());
+ const base = JSON.parse(await read(BASE_PATH));
+ base.unreconciledUniversalIdentifiers = ['not-an-identifier'];
+ await writeFile(join(appPath, BASE_PATH), JSON.stringify(base));
+
+ const result = requireSuccess(
+ await pull(createExport({ includeObject: false })),
+ );
+ expect(result.base.status).toBe('unreadable');
+ expect(result.deletions).toEqual([]);
+ expect(await read(OBJECT_PATH)).toContain('defineObject');
+ });
+ it.each([
+ null,
+ {},
+ { ...createExport(), coverage: undefined },
+ {
+ ...createExport(),
+ application: {
+ ...createExport().application,
+ universalIdentifier: OTHER_IDENTIFIER,
+ },
+ },
+ {
+ ...createExport(),
+ files: [{ folder: '.', path: 'package.json', content: '{}' }],
+ },
+ ])(
+ 'refuses an incomplete or unsupported export without writes (%#)',
+ async (exported) => {
+ expect(await pull(exported)).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED' },
+ });
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'node_modules',
+ 'package.json',
+ ]);
+ },
+ );
+ it('rolls back replaced and deleted source when the final base commit fails', async () => {
+ requireSuccess(await pull());
+ const originalObject = await read(OBJECT_PATH);
+ const originalApplication = await read('src/application.config.ts');
+ const originalBase = await read(BASE_PATH);
+ const originalCopy = fileUtilities.copy;
+ vi.spyOn(fileUtilities, 'copy').mockImplementation(
+ async (source, destination) => {
+ if (
+ source.includes('pull-staging-') &&
+ destination === join(appPath, BASE_PATH)
+ ) {
+ throw new Error('base write failed');
+ }
+ await originalCopy(source, destination);
+ },
+ );
+ const exported = createExport({ includeObject: false });
+ exported.manifest.application.displayName = 'Changed app';
+ expect(await pull(exported)).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED', message: 'base write failed' },
+ });
+ expect(await read(OBJECT_PATH)).toBe(originalObject);
+ expect(await read('src/application.config.ts')).toBe(originalApplication);
+ expect(await read(BASE_PATH)).toBe(originalBase);
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+ it('returns the complete result after a commit succeeds despite cancellation', async () => {
+ const controller = new AbortController();
+ const originalCopy = fileUtilities.copy;
+ let releaseCopy: () => void = () => undefined;
+ const blockedCopy = new Promise<void>((resolveCopy) => {
+ releaseCopy = resolveCopy;
+ });
+ let markStarted: () => void = () => undefined;
+ const started = new Promise<void>((resolveStarted) => {
+ markStarted = resolveStarted;
+ });
+ vi.spyOn(fileUtilities, 'copy').mockImplementation(
+ async (source, destination) => {
+ await originalCopy(source, destination);
+ if (destination === join(appPath, 'src/application.config.ts')) {
+ controller.abort(new Error('stop pull'));
+ markStarted();
+ await blockedCopy;
+ }
+ },
+ );
+ let settled = false;
+ const pending = pull(createExport(), TARGET, controller.signal).then(
+ (result) => {
+ settled = true;
+ return result;
+ },
+ );
+ await started;
+ expect(settled).toBe(false);
+ releaseCopy();
+ const result = requireSuccess(await pending);
+ expect(result.writes).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ relativePath: OBJECT_PATH }),
+ ]),
+ );
+ expect(await read(OBJECT_PATH)).toContain('defineObject');
+ expect(JSON.parse(await read(BASE_PATH))).toMatchObject({ version: 2 });
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+ it('preserves an independent write failure racing with cancellation', async () => {
+ requireSuccess(await pull());
+ const base = await read(BASE_PATH);
+ const controller = new AbortController();
+ const originalCopy = fileUtilities.copy;
+ vi.spyOn(fileUtilities, 'copy').mockImplementation(
+ async (source, destination) => {
+ if (source.includes('pull-staging-')) {
+ controller.abort(new Error('stop'));
+ throw new Error('disk failed');
+ }
+ await originalCopy(source, destination);
+ },
+ );
+ expect(
+ await pull(createExport({ label: 'Changed' }), TARGET, controller.signal),
+ ).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED', message: 'disk failed' },
+ });
+ expect(await read(BASE_PATH)).toBe(base);
+ });
+ it('does not start writes for a pre-aborted call', async () => {
+ expect(
+ await pull(createExport(), TARGET, AbortSignal.abort()),
+ ).toMatchObject({ success: false, error: { code: 'CANCELLED' } });
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'node_modules',
+ 'package.json',
+ ]);
+ });
+
+ it('preserves a compiled locale from an unbound checkout', async () => {
+ await mkdir(join(appPath, 'locales/compiled'), { recursive: true });
+ const local = '{"local-id":"Local translation"}\n';
+ await writeFile(join(appPath, 'locales/compiled/fr-FR.json'), local);
+ const exported = createExport();
+ const data = requireSuccess(
+ await pull({
+ ...exported,
+ manifest: {
+ ...exported.manifest,
+ translations: {
+ 'fr-FR': {
+ [generateMessageId('Pet', 'objectMetadata.labelSingular')]:
+ 'Animal',
+ },
+ },
+ },
+ }),
+ );
+ expect(data.deletions).toEqual([]);
+ expect(await read('locales/compiled/fr-FR.json')).toBe(local);
+ expect(await read('locales/fr-FR.json')).toContain('Animal');
+ });
+
+ it('reports overwritten locale edits and removes only base-owned locales', async () => {
+ const exported = createExport();
+ const translationIdentifier = generateMessageId(
+ 'Pet',
+ 'objectMetadata.labelSingular',
+ );
+ const translated = {
+ ...exported,
+ manifest: {
+ ...exported.manifest,
+ translations: {
+ 'fr-FR': { [translationIdentifier]: 'Animal' },
+ },
+ },
+ };
+ requireSuccess(await pull(translated));
+ await writeFile(
+ join(appPath, 'locales/fr-FR.json'),
+ (await read('locales/fr-FR.json')).replace('Animal', 'Local'),
+ );
+ const changed = requireSuccess(
+ await pull({
+ ...translated,
+ manifest: {
+ ...translated.manifest,
+ translations: {
+ 'fr-FR': { [translationIdentifier]: 'Serveur' },
+ },
+ },
+ }),
+ );
+ expect(changed.overwrittenLocalChanges).toContainEqual({
+ universalIdentifier: 'fr-FR',
+ relativePath: 'locales/fr-FR.json',
+ });
+ const removed = requireSuccess(
+ await pull({
+ ...exported,
+ manifest: { ...exported.manifest, translations: {} },
+ }),
+ );
+ expect(removed.deletions).toContainEqual({
+ universalIdentifier: 'fr-FR',
+ relativePath: 'locales/fr-FR.json',
+ });
+ });
+
+ it('allows read-only symlinked helpers while preserving them', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'twenty-pull-helpers-'));
+ try {
+ const helper = 'export const label = "shared";\n';
+ await writeFile(join(outside, 'helper.ts'), helper);
+ await mkdir(join(appPath, 'src'));
+ await symlink(outside, join(appPath, 'src/shared'), 'dir');
+ expect(requireSuccess(await readAppIdentity({ appPath }))).toEqual({
+ application: null,
+ });
+ requireSuccess(await pull());
+ expect(
+ requireSuccess(await readAppIdentity({ appPath })).application
+ ?.universalIdentifier,
+ ).toBe(APPLICATION_IDENTIFIER);
+ expect(await readFile(join(outside, 'helper.ts'), 'utf8')).toBe(helper);
+ } finally {
+ await rm(outside, { recursive: true, force: true });
+ }
+ });
+
+ it.each([
+ 'https://user:[email protected]',
+ 'file:///tmp/example',
+ 'https://example.test/?secret=token',
+ ])('refuses an unsafe target URL: %s', async (apiUrl) => {
+ expect(await pull(createExport(), { ...TARGET, apiUrl })).toMatchObject({
+ success: false,
+ error: { code: 'INVALID_API_URL' },
+ });
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'node_modules',
+ 'package.json',
+ ]);
+ });
+ it('refuses symlinked source and base destinations', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'twenty-pull-outside-'));
+ try {
+ await symlink(outside, join(appPath, '.twenty'), 'dir');
+ expect(await pull()).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED' },
+ });
+ expect(await readdir(outside)).toEqual([]);
+ await rm(join(appPath, '.twenty'));
+ await symlink(outside, join(appPath, 'src'), 'dir');
+ expect(await pull()).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED' },
+ });
+ expect(await readdir(outside)).toEqual([]);
+ } finally {
+ await rm(outside, { recursive: true, force: true });
+ }
+ });
+ it('accepts absent and null collections, preserves new server collections in the baseline', async () => {
+ const exported = createExport();
+ const data = requireSuccess(
+ await pull({
+ ...exported,
+ manifest: {
+ application: exported.manifest.application,
+ fields: null,
+ futureEntities: [
+ { universalIdentifier: OTHER_IDENTIFIER, value: 'future' },
+ ],
+ },
+ }),
+ );
+ expect(data.writes).toHaveLength(1);
+ expect(JSON.parse(await read(BASE_PATH)).manifest).toEqual({
+ application: exported.manifest.application,
+ fields: null,
+ futureEntities: [
+ { universalIdentifier: OTHER_IDENTIFIER, value: 'future' },
+ ],
+ });
+ });
+
+ it('reports incomplete rollback and retains originals even if staging cleanup fails', async () => {
+ requireSuccess(await pull());
+ const original = await read(OBJECT_PATH);
+ const originalCopy = fileUtilities.copy;
+ vi.spyOn(fileUtilities, 'copy').mockImplementation(
+ async (source, destination) => {
+ if (
+ source.includes('pull-staging-') ||
+ source.includes('pull-backup-')
+ ) {
+ throw new Error('copy failed');
+ }
+ await originalCopy(source, destination);
+ },
+ );
+ vi.spyOn(fileUtilities, 'remove').mockRejectedValue(
+ new Error('cleanup failed'),
+ );
+ const result = await pull(createExport({ label: 'Changed' }));
+ expect(result).toMatchObject({
+ success: false,
+ error: {
+ code: 'PULL_FAILED',
+ details: { outcome: 'unknown', backupDirectory: expect.any(String) },
+ },
+ });
+ if (result.success || !('details' in result.error)) {
+ throw new Error('Expected recovery details');
+ }
+ const details = result.error.details;
+ const backupDirectory = details?.backupDirectory;
+ if (typeof backupDirectory !== 'string') {
+ throw new Error('Expected backup path');
+ }
+ expect(await readFile(join(backupDirectory, OBJECT_PATH), 'utf8')).toBe(
+ original,
+ );
+ });
+
+ it('reports a completed pull when only temporary directory cleanup fails', async () => {
+ vi.spyOn(fileUtilities, 'remove').mockRejectedValue(
+ new Error('cleanup failed'),
+ );
+ expect(await pull()).toMatchObject({
+ success: false,
+ error: { code: 'PULL_FAILED', details: { outcome: 'pulled' } },
+ });
+ expect(JSON.parse(await read(BASE_PATH))).toMatchObject({ version: 2 });
+ expect(await read(OBJECT_PATH)).toContain('defineObject');
+ });
+ it('keeps a remotely deleted object file containing a new local field', async () => {
+ requireSuccess(await pull());
+ const local = (await read(OBJECT_PATH)).replace(
+ 'fields: [',
+ `fields: [{
+ universalIdentifier: '${INDEX_IDENTIFIER}', name: 'localNote', label: 'Local note', type: 'TEXT',
+ },`,
+ );
+ await writeFile(join(appPath, OBJECT_PATH), local);
+
+ const result = requireSuccess(
+ await pull(createExport({ includeObject: false })),
+ );
+
+ expect(result.deletions).toEqual([]);
+ expect(await read(OBJECT_PATH)).toBe(local);
+ expect(result.skipped).toContainEqual(
+ expect.objectContaining({
+ kind: 'object',
+ universalIdentifier: OBJECT_IDENTIFIER,
+ reason: expect.stringContaining(INDEX_IDENTIFIER),
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts
new file mode 100644
index 00000000000..0dd9a92e38c
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts
@@ -0,0 +1,387 @@
+import {
+ mkdir,
+ mkdtemp,
+ open,
+ readFile,
+ readdir,
+ rename,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import type * as fileSystemPromises from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { type Manifest } from 'twenty-shared/application';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';
+import { readTargetBoundPullBase } from '@/app/pull/read-target-bound-pull-base';
+import { writePullBase } from '@/app/pull/write-pull-base';
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof fileSystemPromises>();
+
+ return { ...actual, open: vi.fn(actual.open), rename: vi.fn(actual.rename) };
+});
+
+const TARGET = {
+ apiUrl: 'https://crm.example.test/api',
+ workspaceId: '48eb6ca1-dbd6-492e-8b53-5785a266c454',
+};
+const MANIFEST: Manifest = {
+ application: {
+ universalIdentifier: '6a0c9d8e-8f5f-4c43-9b8e-0e1f2a3b4c5d',
+ displayName: 'App',
+ description: '',
+ defaultRoleUniversalIdentifier: 'c8c1213a-e037-41e6-bd76-2f5c828f58cd',
+ packageJsonChecksum: null,
+ yarnLockChecksum: null,
+ },
+ objects: [],
+ fields: [],
+ logicFunctions: [],
+ frontComponents: [],
+ permissionFlags: [],
+ roles: [],
+ skills: [],
+ agents: [],
+ views: [],
+ viewFields: [],
+ navigationMenuItems: [],
+ pageLayouts: [],
+ pageLayoutTabs: [],
+ pageLayoutWidgets: [],
+ commandMenuItems: [],
+ timelineActivityTypes: [],
+ settingsMenuItems: [],
+ publicAssets: [],
+};
+
+const BASE = {
+ version: 2,
+ target: TARGET,
+ applicationUniversalIdentifier: MANIFEST.application.universalIdentifier,
+ manifest: MANIFEST,
+};
+
+describe('target-bound CLI pull base', () => {
+ let appPath: string;
+ let basePath: string;
+ let controller: AbortController;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-pull-base-'));
+ basePath = join(appPath, PULL_BASE_FILE_PATH);
+ controller = new AbortController();
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ const record = () =>
+ writePullBase({
+ appPath,
+ manifest: MANIFEST,
+ target: TARGET,
+ signal: controller.signal,
+ });
+ const read = (
+ target = TARGET,
+ applicationUniversalIdentifier = MANIFEST.application.universalIdentifier,
+ ) =>
+ readTargetBoundPullBase({
+ appPath,
+ target,
+ applicationUniversalIdentifier,
+ });
+ const seed = async (contents: string) => {
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await writeFile(basePath, contents);
+ };
+
+ it('round-trips a base across equivalent URL and UUID spellings', async () => {
+ await writePullBase({
+ appPath,
+ manifest: MANIFEST,
+ target: {
+ apiUrl: 'HTTPS://CRM.EXAMPLE.TEST:443/api///',
+ workspaceId: TARGET.workspaceId.toUpperCase(),
+ },
+ signal: controller.signal,
+ });
+
+ expect(
+ await read(
+ {
+ apiUrl: `${TARGET.apiUrl}/`,
+ workspaceId: TARGET.workspaceId.toUpperCase(),
+ },
+ MANIFEST.application.universalIdentifier.toUpperCase(),
+ ),
+ ).toMatchObject({ status: 'used', manifest: MANIFEST });
+ expect(JSON.parse(await readFile(basePath, 'utf8'))).toEqual(BASE);
+ expect((await stat(basePath)).mode & 0o777).toBe(0o600);
+ });
+
+ it('stores source fingerprints sorted by path and reads them back', async () => {
+ const roleFingerprint = 'a'.repeat(64);
+ const objectFingerprint = 'b'.repeat(64);
+
+ await writePullBase({
+ appPath,
+ manifest: MANIFEST,
+ target: TARGET,
+ sourceFingerprints: {
+ 'src/role.ts': roleFingerprint,
+ 'src/object.ts': objectFingerprint,
+ },
+ signal: controller.signal,
+ });
+
+ expect(await read()).toMatchObject({
+ status: 'used',
+ sourceFingerprints: {
+ 'src/object.ts': objectFingerprint,
+ 'src/role.ts': roleFingerprint,
+ },
+ });
+ expect(
+ Object.keys(
+ JSON.parse(await readFile(basePath, 'utf8')).sourceFingerprints,
+ ),
+ ).toEqual(['src/object.ts', 'src/role.ts']);
+ });
+
+ it.each([
+ [
+ { ...TARGET, apiUrl: 'https://other.example.test/api' },
+ MANIFEST.application.universalIdentifier,
+ ],
+ [
+ { ...TARGET, apiUrl: 'https://crm.example.test/other' },
+ MANIFEST.application.universalIdentifier,
+ ],
+ [
+ { ...TARGET, workspaceId: MANIFEST.application.universalIdentifier },
+ MANIFEST.application.universalIdentifier,
+ ],
+ [TARGET, TARGET.workspaceId],
+ ])(
+ 'ignores a baseline for another target or app: %j %s',
+ async (target, identifier) => {
+ await record();
+
+ expect(await read(target, identifier)).toEqual({
+ status: 'other-target',
+ manifest: null,
+ });
+ },
+ );
+
+ it('ignores the legacy SDK base', async () => {
+ await mkdir(join(appPath, '.twenty'));
+ await writeFile(
+ join(appPath, '.twenty/pull-base.json'),
+ JSON.stringify(BASE),
+ );
+
+ expect(await read()).toEqual({ status: 'missing', manifest: null });
+ });
+
+ it.each([
+ [
+ 'legacy unbound',
+ JSON.stringify({ version: 1, manifest: MANIFEST }),
+ 'unbound',
+ ],
+ ['truncated JSON', '{"version":2', 'unreadable'],
+ [
+ 'non-object manifest',
+ JSON.stringify({
+ ...BASE,
+ manifest: null,
+ }),
+ 'unreadable',
+ ],
+ [
+ 'non-object application',
+ JSON.stringify({ ...BASE, manifest: { application: null } }),
+ 'unreadable',
+ ],
+ [
+ 'non-string application UUID',
+ JSON.stringify({
+ ...BASE,
+ manifest: { application: { universalIdentifier: 42 } },
+ }),
+ 'unreadable',
+ ],
+ [
+ 'wrong manifest UUID',
+ JSON.stringify({
+ ...BASE,
+ applicationUniversalIdentifier: TARGET.workspaceId,
+ }),
+ 'unreadable',
+ ],
+ [
+ 'invalid target UUID',
+ JSON.stringify({
+ ...BASE,
+ target: { ...TARGET, workspaceId: 'invalid' },
+ }),
+ 'unreadable',
+ ],
+ [
+ 'credentialed URL',
+ JSON.stringify({
+ ...BASE,
+ target: { ...TARGET, apiUrl: 'https://[email protected]' },
+ }),
+ 'unreadable',
+ ],
+ [
+ 'invalid unresolved UUID',
+ JSON.stringify({
+ ...BASE,
+ unreconciledUniversalIdentifiers: ['invalid'],
+ }),
+ 'unreadable',
+ ],
+ [
+ 'invalid source fingerprint',
+ JSON.stringify({
+ ...BASE,
+ sourceFingerprints: { 'src/role.ts': 'not-a-sha256' },
+ }),
+ 'unreadable',
+ ],
+ [
+ 'non-object source fingerprints',
+ JSON.stringify({ ...BASE, sourceFingerprints: ['src/role.ts'] }),
+ 'unreadable',
+ ],
+ ])(
+ 'falls back without a baseline for %s',
+ async (_name, contents, status) => {
+ await seed(contents);
+
+ expect(await read()).toEqual({ status, manifest: null });
+ expect(await readFile(basePath, 'utf8')).toBe(contents);
+ },
+ );
+
+ it.each([
+ { application: MANIFEST.application },
+ { ...MANIFEST, settingsMenuItems: null, objects: null },
+ { ...MANIFEST, futureCollection: [{ name: 'preserved' }] },
+ ])(
+ 'reads stored collections without normalizing or validating their schema',
+ async (manifest) => {
+ const contents = JSON.stringify({ ...BASE, manifest });
+ await seed(contents);
+
+ expect(await read()).toMatchObject({ status: 'used', manifest });
+ expect(await readFile(basePath, 'utf8')).toBe(contents);
+ },
+ );
+
+ it('rejects a linked baseline instead of reading another file', async () => {
+ const otherPath = join(appPath, 'other.json');
+ await writeFile(otherPath, JSON.stringify(BASE));
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await symlink(otherPath, basePath);
+
+ await expect(read()).rejects.toThrow('symbolic links');
+ });
+
+ it('keeps the prior base until the complete replacement is renamed', async () => {
+ await seed('previous base');
+ const original =
+ await vi.importActual<typeof fileSystemPromises>('node:fs/promises');
+ vi.mocked(rename).mockImplementationOnce(async (source, destination) => {
+ expect(await readFile(basePath, 'utf8')).toBe('previous base');
+ expect(JSON.parse(await readFile(source, 'utf8'))).toEqual(BASE);
+ await original.rename(source, destination);
+ });
+
+ await record();
+
+ expect(await read()).toMatchObject({ status: 'used', manifest: MANIFEST });
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+
+ it('preserves the old base and removes staging files when rename fails', async () => {
+ await seed('previous base');
+ vi.mocked(rename).mockRejectedValueOnce(new Error('disk error'));
+
+ await expect(record()).rejects.toMatchObject({
+ code: 'PULL_BASE_RECORD_FAILED',
+ });
+
+ expect(await readFile(basePath, 'utf8')).toBe('previous base');
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+
+ it('preserves the old base when cancelled after staging but before commit', async () => {
+ await seed('previous base');
+ const original =
+ await vi.importActual<typeof fileSystemPromises>('node:fs/promises');
+ vi.mocked(open).mockImplementationOnce(async (...args) => {
+ const handle = await original.open(...args);
+ const sync = handle.sync.bind(handle);
+ vi.spyOn(handle, 'sync').mockImplementationOnce(async () => {
+ await sync();
+ controller.abort();
+ });
+ return handle;
+ });
+
+ await expect(record()).rejects.toMatchObject({ name: 'AbortError' });
+
+ expect(await readFile(basePath, 'utf8')).toBe('previous base');
+ expect(await readdir(join(appPath, '.twenty/cli'))).toEqual([
+ 'pull-base.json',
+ ]);
+ });
+
+ it('reports a completed write when cancellation arrives after commit', async () => {
+ const original =
+ await vi.importActual<typeof fileSystemPromises>('node:fs/promises');
+ vi.mocked(rename).mockImplementationOnce(async (...args) => {
+ await original.rename(...args);
+ controller.abort();
+ });
+
+ await expect(record()).resolves.toBeUndefined();
+ expect(await read()).toMatchObject({ status: 'used', manifest: MANIFEST });
+ });
+ it.each([
+ { objects: [null] },
+ { fields: [42] },
+ { translations: 'malformed' },
+ { translations: { fr: { invalid: 42 } } },
+ {
+ objects: [
+ { universalIdentifier: 'object', nameSingular: 'pet', fields: [null] },
+ ],
+ },
+ ])(
+ 'treats malformed entity collections as an unreadable base',
+ async (collections) => {
+ await seed(
+ JSON.stringify({ ...BASE, manifest: { ...MANIFEST, ...collections } }),
+ );
+ expect(await read()).toEqual({ status: 'unreadable', manifest: null });
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/split-pulled-translations.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/split-pulled-translations.spec.ts
new file mode 100644
index 00000000000..dd28b7f2e05
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/split-pulled-translations.spec.ts
@@ -0,0 +1,233 @@
+import { splitPulledTranslations } from '@/app/pull/split-pulled-translations';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { type Manifest } from 'twenty-shared/application';
+import { generateMessageId } from 'twenty-shared/i18n';
+import { afterEach, describe, expect, it } from 'vitest';
+
+const PET_LABEL_ID = generateMessageId('Pet', 'objectMetadata.labelSingular');
+const AGE_LABEL_ID = generateMessageId('Age', 'fieldMetadata.label');
+const VIEW_NAME_ID = generateMessageId('All pets', 'view.name');
+
+const buildManifest = (overrides: Record<string, unknown>): Manifest =>
+ ({
+ application: {},
+ objects: [
+ {
+ universalIdentifier: 'pet',
+ nameSingular: 'pet',
+ namePlural: 'pets',
+ labelSingular: 'Pet',
+ labelPlural: 'Pets',
+ description: 'A pet',
+ fields: [
+ {
+ universalIdentifier: 'age',
+ name: 'age',
+ label: 'Age',
+ description: '',
+ type: 'NUMBER',
+ },
+ ],
+ },
+ ],
+ fields: [],
+ indexes: [],
+ views: [
+ {
+ universalIdentifier: 'all-pets',
+ name: 'All pets',
+ objectUniversalIdentifier: 'pet',
+ },
+ ],
+ viewFields: [],
+ ...overrides,
+ }) as unknown as Manifest;
+
+const createdDirectories: string[] = [];
+
+const createDirectory = async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'split-pulled-translations-'));
+
+ createdDirectories.push(directory);
+
+ return directory;
+};
+
+describe('splitPulledTranslations', () => {
+ afterEach(async () => {
+ await Promise.all(
+ createdDirectories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true })),
+ );
+ });
+
+ it('should write entries whose source is a pulled label in the authoring format and keep the rest compiled', async () => {
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'fr-FR': {
+ [PET_LABEL_ID]: 'Animal',
+ [AGE_LABEL_ID]: 'Âge',
+ [VIEW_NAME_ID]: 'Tous les animaux',
+ zzzzzz: 'orphan',
+ },
+ },
+ }),
+ frontComponentSourcePaths: [],
+ });
+
+ expect(catalogs).toEqual([
+ {
+ locale: 'fr-FR',
+ authored: {
+ 'fieldMetadata.label': { Age: 'Âge' },
+ 'objectMetadata.labelSingular': { Pet: 'Animal' },
+ 'view.name': { 'All pets': 'Tous les animaux' },
+ },
+ compiled: { zzzzzz: 'orphan' },
+ },
+ ]);
+ });
+
+ it('should decode the strings of the front components it is given', async () => {
+ const componentPath = join(
+ await createDirectory(),
+ 'card.front-component.tsx',
+ );
+
+ await writeFile(
+ componentPath,
+ `
+ import { t, Trans } from 'twenty-sdk/front-component';
+
+ const Component = () => {
+ const label = t('No content yet');
+ const verb = t({ message: 'Open', context: 'door' });
+
+ return <Trans context="card">Untitled</Trans>;
+ };
+
+ export default defineFrontComponent({ component: Component });
+ `,
+ );
+
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'de-DE': {
+ [generateMessageId('No content yet')]: 'Noch kein Inhalt',
+ [generateMessageId('Open', 'door')]: 'Öffnen',
+ [generateMessageId('Untitled', 'card')]: 'Ohne Titel',
+ },
+ },
+ }),
+ frontComponentSourcePaths: [componentPath],
+ });
+
+ expect(catalogs).toEqual([
+ {
+ locale: 'de-DE',
+ authored: {
+ 'No content yet': 'Noch kein Inhalt',
+ card: { Untitled: 'Ohne Titel' },
+ door: { Open: 'Öffnen' },
+ },
+ compiled: {},
+ },
+ ]);
+ });
+
+ it('should keep an entry compiled when the label it was translated from has changed', async () => {
+ const staleId = generateMessageId('Kitten', 'objectMetadata.labelSingular');
+
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: { 'fr-FR': { [staleId]: 'Chaton' } },
+ }),
+ frontComponentSourcePaths: [],
+ });
+
+ expect(catalogs).toEqual([
+ { locale: 'fr-FR', authored: {}, compiled: { [staleId]: 'Chaton' } },
+ ]);
+ });
+
+ it('should ignore locales the platform does not support, including path-shaped keys', async () => {
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'fr-FR': { [PET_LABEL_ID]: 'Animal' },
+ klingon: { [PET_LABEL_ID]: 'targh' },
+ '../../escape': { [PET_LABEL_ID]: 'nope' },
+ },
+ }),
+ frontComponentSourcePaths: [],
+ });
+
+ expect(catalogs.map(({ locale }) => locale)).toEqual(['fr-FR']);
+ });
+
+ it('should ignore a locale whose catalog is not a map of strings', async () => {
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'fr-FR': 'Animal',
+ 'de-DE': ['Haustier'],
+ 'es-ES': { [PET_LABEL_ID]: 7 },
+ 'it-IT': { [PET_LABEL_ID]: 'Animale' },
+ },
+ }),
+ frontComponentSourcePaths: [],
+ });
+
+ expect(catalogs.map(({ locale }) => locale)).toEqual(['it-IT']);
+ });
+
+ it('should order locales and return nothing for an export without translations', async () => {
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'fr-FR': { [PET_LABEL_ID]: 'Animal' },
+ 'de-DE': { [PET_LABEL_ID]: 'Haustier' },
+ },
+ }),
+ frontComponentSourcePaths: [],
+ });
+
+ expect(catalogs.map(({ locale }) => locale)).toEqual(['de-DE', 'fr-FR']);
+ expect(
+ await splitPulledTranslations({
+ manifest: buildManifest({}),
+ frontComponentSourcePaths: [],
+ }),
+ ).toEqual([]);
+ });
+ it('keeps prototype-shaped message contexts as own catalog properties', async () => {
+ const componentPath = join(await createDirectory(), 'card.tsx');
+ await writeFile(
+ componentPath,
+ `import { t } from 'twenty-sdk/front-component';
+export const label = t({ message: 'Review fixture', context: '__proto__' });`,
+ );
+ const catalogs = await splitPulledTranslations({
+ manifest: buildManifest({
+ translations: {
+ 'fr-FR': {
+ [generateMessageId('Review fixture', '__proto__')]: 'Exemple',
+ },
+ },
+ }),
+ frontComponentSourcePaths: [componentPath],
+ });
+
+ expect(Object.hasOwn(catalogs[0].authored, '__proto__')).toBe(true);
+ expect(catalogs[0].authored.__proto__).toEqual({
+ 'Review fixture': 'Exemple',
+ });
+ expect(Object.hasOwn(Object.prototype, 'Review fixture')).toBe(false);
+ expect(JSON.stringify(catalogs[0].authored)).toContain('__proto__');
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/strip-graphql-typename.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/strip-graphql-typename.spec.ts
new file mode 100644
index 00000000000..b3a05895b54
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/strip-graphql-typename.spec.ts
@@ -0,0 +1,36 @@
+import { stripGraphqlTypename } from '@/app/pull/strip-graphql-typename';
+import { describe, expect, it } from 'vitest';
+
+describe('stripGraphqlTypename', () => {
+ it('should drop __typename keys at every depth and keep everything else, nulls included', () => {
+ expect(
+ stripGraphqlTypename({
+ __typename: 'PageLayoutWidget',
+ title: 'People',
+ configuration: {
+ __typename: 'RecordTableConfiguration',
+ configurationType: 'RECORD_TABLE',
+ recordLimit: null,
+ filter: {
+ recordFilters: [
+ { __typename: 'ChartFilter', value: null, operand: 'is' },
+ ],
+ },
+ },
+ }),
+ ).toEqual({
+ title: 'People',
+ configuration: {
+ configurationType: 'RECORD_TABLE',
+ recordLimit: null,
+ filter: { recordFilters: [{ value: null, operand: 'is' }] },
+ },
+ });
+ });
+
+ it('should return scalars and arrays unchanged', () => {
+ expect(stripGraphqlTypename('People')).toBe('People');
+ expect(stripGraphqlTypename(null)).toBeNull();
+ expect(stripGraphqlTypename([1, 'two', null])).toEqual([1, 'two', null]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts
new file mode 100644
index 00000000000..998c27e5d7b
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/__tests__/write-define-file.spec.ts
@@ -0,0 +1,556 @@
+import {
+ FIELD_ENUM_BINDINGS,
+ INDEX_ENUM_BINDINGS,
+ NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ OBJECT_ENUM_BINDINGS,
+ PAGE_LAYOUT_ENUM_BINDINGS,
+ PAGE_LAYOUT_TAB_ENUM_BINDINGS,
+ ROLE_ENUM_BINDINGS,
+ VIEW_ENUM_BINDINGS,
+ VIEW_FIELD_ENUM_BINDINGS,
+ writeDefineFile,
+} from '@/app/pull/write-define-file';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { describe, expect, it } from 'vitest';
+
+describe('writeDefineFile', () => {
+ it('should write an enum-valued property as a symbol and import it', () => {
+ const { content: file, requiredSdkExports } = writeDefineFile({
+ definer: 'defineField',
+ config: {
+ universalIdentifier: 'field-uid',
+ type: 'TEXT',
+ name: 'title',
+ writability: 'OPEN',
+ },
+ enumBindings: FIELD_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain(
+ "import { defineField, FieldType, MetadataWritability } from 'twenty-sdk/define';",
+ );
+ expect(requiredSdkExports).toEqual([
+ 'defineField',
+ 'FieldType',
+ 'MetadataWritability',
+ ]);
+ expect(file).toContain('type: FieldType.TEXT,');
+ expect(file).toContain('writability: MetadataWritability.OPEN,');
+ });
+
+ it('should look up an enum member whose name differs from its value', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineField',
+ config: {
+ universalIdentifier: 'field-uid',
+ type: 'NUMBER',
+ universalSettings: { dataType: 'bigint' },
+ },
+ enumBindings: FIELD_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain('dataType: NumberDataType.BIGINT,');
+ });
+
+ it('should leave a string that is not a member of the bound enum as a literal', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineField',
+ config: { universalIdentifier: 'field-uid', type: 'NOT_A_FIELD_TYPE' },
+ enumBindings: FIELD_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain("type: 'NOT_A_FIELD_TYPE',");
+ expect(file).toContain("import { defineField } from 'twenty-sdk/define';");
+ });
+
+ it('should only bind enum properties at the declared path', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineIndex',
+ config: {
+ universalIdentifier: 'index-uid',
+ indexType: 'BTREE',
+ fields: [{ fieldUniversalIdentifier: 'field-uid', indexType: 'BTREE' }],
+ },
+ enumBindings: INDEX_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain('indexType: IndexType.BTREE,');
+ expect(file).toContain("indexType: 'BTREE',");
+ });
+
+ it('should wrap the import statement when it grows past one line', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineObject',
+ config: {
+ writability: 'OPEN',
+ openRecordIn: 'USER_CHOICE',
+ fields: [
+ {
+ type: 'RELATION',
+ universalSettings: {
+ relationType: 'MANY_TO_ONE',
+ onDelete: 'SET_NULL',
+ },
+ },
+ ],
+ },
+ enumBindings: OBJECT_ENUM_BINDINGS,
+ });
+
+ expect(file.startsWith('import {\n defineObject,\n')).toBe(true);
+ expect(file).toContain("} from 'twenty-sdk/define';");
+ expect(file).toContain('relationType: RelationType.MANY_TO_ONE,');
+ expect(file).toContain('onDelete: OnDeleteAction.SET_NULL,');
+ });
+
+ it('should quote a key that is not a valid identifier and escape strings', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineApplication',
+ config: {
+ displayName: "Tim's app",
+ translations: { 'fr-FR': { greeting: 'Bonjour' } },
+ nothing: null,
+ empty: [],
+ },
+ });
+
+ expect(file).toContain("displayName: 'Tim\\'s app',");
+ expect(file).toContain("'fr-FR': {");
+ expect(file).toContain('nothing: null,');
+ expect(file).toContain('empty: [],');
+ });
+
+ it('should end with a single default export of the definer call', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineObject',
+ config: { nameSingular: 'pet' },
+ });
+
+ expect(file).toBe(
+ "import { defineObject } from 'twenty-sdk/define';\n" +
+ '\n' +
+ 'export default defineObject({\n' +
+ " nameSingular: 'pet',\n" +
+ '});\n',
+ );
+ });
+
+ it('should write every bound view property as its enum symbol and import each symbol on its own line', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineView',
+ config: {
+ universalIdentifier: 'view-uid',
+ name: 'Companies by owner',
+ objectUniversalIdentifier: 'object-uid',
+ type: 'TABLE_WIDGET',
+ visibility: 'WORKSPACE',
+ openRecordIn: 'SIDE_PANEL',
+ calendarLayout: 'MONTH',
+ kanbanAggregateOperation: 'COUNT',
+ fields: [
+ {
+ universalIdentifier: 'view-field-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ position: 0,
+ aggregateOperation: 'COUNT_UNIQUE_VALUES',
+ },
+ ],
+ filters: [
+ {
+ universalIdentifier: 'view-filter-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ operand: 'CONTAINS',
+ value: 'acme',
+ },
+ ],
+ filterGroups: [
+ {
+ universalIdentifier: 'view-filter-group-uid',
+ logicalOperator: 'NOT',
+ },
+ ],
+ sorts: [
+ {
+ universalIdentifier: 'view-sort-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ direction: 'DESC',
+ },
+ ],
+ },
+ enumBindings: VIEW_ENUM_BINDINGS,
+ });
+
+ expect(
+ file.startsWith(
+ 'import {\n' +
+ ' defineView,\n' +
+ ' AggregateOperations,\n' +
+ ' ViewCalendarLayout,\n' +
+ ' ViewFilterGroupLogicalOperator,\n' +
+ ' ViewFilterOperand,\n' +
+ ' ViewOpenRecordIn,\n' +
+ ' ViewSortDirection,\n' +
+ ' ViewType,\n' +
+ ' ViewVisibility,\n' +
+ "} from 'twenty-sdk/define';\n",
+ ),
+ ).toBe(true);
+ expect(file).toContain('type: ViewType.TABLE_WIDGET,');
+ expect(file).toContain('visibility: ViewVisibility.WORKSPACE,');
+ expect(file).toContain('openRecordIn: ViewOpenRecordIn.SIDE_PANEL,');
+ expect(file).toContain('calendarLayout: ViewCalendarLayout.MONTH,');
+ expect(file).toContain(
+ 'kanbanAggregateOperation: AggregateOperations.COUNT,',
+ );
+ expect(file).toContain(
+ 'aggregateOperation: AggregateOperations.COUNT_UNIQUE_VALUES,',
+ );
+ expect(file).toContain('operand: ViewFilterOperand.CONTAINS,');
+ expect(file).toContain(
+ 'logicalOperator: ViewFilterGroupLogicalOperator.NOT,',
+ );
+ expect(file).toContain('direction: ViewSortDirection.DESC,');
+ });
+
+ it('should leave a filter operand that is not a member of ViewFilterOperand as a literal', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineView',
+ config: {
+ universalIdentifier: 'view-uid',
+ filters: [
+ {
+ universalIdentifier: 'view-filter-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ operand: 'contains',
+ value: 'acme',
+ },
+ ],
+ },
+ enumBindings: VIEW_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain("operand: 'contains',");
+ expect(file).toContain("import { defineView } from 'twenty-sdk/define';");
+ });
+
+ it('should not bind an operand that sits on the view itself rather than inside its filters', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineView',
+ config: {
+ universalIdentifier: 'view-uid',
+ operand: 'CONTAINS',
+ },
+ enumBindings: VIEW_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain("operand: 'CONTAINS',");
+ expect(file).toContain("import { defineView } from 'twenty-sdk/define';");
+ });
+
+ it('should write a standalone view field aggregate operation as an AggregateOperations member', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineViewField',
+ config: {
+ universalIdentifier: 'view-field-uid',
+ viewUniversalIdentifier: 'view-uid',
+ fieldMetadataUniversalIdentifier: 'field-uid',
+ position: 0,
+ isVisible: true,
+ aggregateOperation: 'MIN',
+ },
+ enumBindings: VIEW_FIELD_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain('aggregateOperation: AggregateOperations.MIN,');
+ expect(file).toContain(
+ "import { defineViewField, AggregateOperations } from 'twenty-sdk/define';",
+ );
+ });
+
+ it('should write every bound page layout property as its enum symbol and import each symbol on its own line', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'definePageLayout',
+ config: {
+ universalIdentifier: 'page-layout-uid',
+ name: 'Pet dashboard',
+ type: 'DASHBOARD',
+ tabs: [
+ {
+ universalIdentifier: 'tab-uid',
+ title: 'Charts',
+ position: 0,
+ layoutMode: 'GRID',
+ widgets: [
+ {
+ universalIdentifier: 'chart-widget-uid',
+ title: 'Age by status',
+ type: 'GRAPH',
+ objectUniversalIdentifier: 'object-uid',
+ position: {
+ layoutMode: 'GRID',
+ row: 0,
+ column: 0,
+ rowSpan: 4,
+ columnSpan: 6,
+ },
+ configuration: {
+ configurationType: 'BAR_CHART',
+ aggregateFieldMetadataUniversalIdentifier: 'age-field-uid',
+ aggregateOperation: 'AVG',
+ primaryAxisGroupByFieldMetadataUniversalIdentifier:
+ 'status-field-uid',
+ primaryAxisDateGranularity: 'MONTH',
+ secondaryAxisGroupByFieldMetadataUniversalIdentifier: null,
+ groupMode: 'STACKED',
+ },
+ },
+ {
+ universalIdentifier: 'fields-widget-uid',
+ title: 'Fields',
+ type: 'FIELDS',
+ position: { layoutMode: 'VERTICAL_LIST', index: 1 },
+ configuration: {
+ configurationType: 'FIELDS',
+ viewUniversalIdentifier: null,
+ fieldDisplayMode: 'CARD',
+ },
+ },
+ ],
+ },
+ ],
+ },
+ enumBindings: PAGE_LAYOUT_ENUM_BINDINGS,
+ });
+
+ expect(
+ file.startsWith(
+ 'import {\n' +
+ ' definePageLayout,\n' +
+ ' AggregateOperations,\n' +
+ ' ObjectRecordGroupByDateGranularity,\n' +
+ ' PageLayoutTabLayoutMode,\n' +
+ ' PageLayoutType,\n' +
+ ' WidgetType,\n' +
+ "} from 'twenty-sdk/define';\n",
+ ),
+ ).toBe(true);
+ expect(file).toContain('type: PageLayoutType.DASHBOARD,');
+ expect(file).toContain('layoutMode: PageLayoutTabLayoutMode.GRID,');
+ expect(file).toContain('type: WidgetType.GRAPH,');
+ expect(file).toContain('type: WidgetType.FIELDS,');
+ expect(file).toContain(
+ 'layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,',
+ );
+ expect(file).toContain('aggregateOperation: AggregateOperations.AVG,');
+ expect(file).toContain(
+ 'primaryAxisDateGranularity: ObjectRecordGroupByDateGranularity.MONTH,',
+ );
+ expect(file).toContain("configurationType: 'BAR_CHART',");
+ expect(file).toContain("groupMode: 'STACKED',");
+ expect(file).toContain("fieldDisplayMode: 'CARD',");
+ expect(file).toContain(
+ 'secondaryAxisGroupByFieldMetadataUniversalIdentifier: null,',
+ );
+ expect(file).toContain('viewUniversalIdentifier: null,');
+ });
+
+ it('should not bind a layout mode that sits on the page layout itself rather than on its tabs', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'definePageLayout',
+ config: { universalIdentifier: 'page-layout-uid', layoutMode: 'GRID' },
+ enumBindings: PAGE_LAYOUT_ENUM_BINDINGS,
+ });
+
+ expect(file).toContain("layoutMode: 'GRID',");
+ expect(file).toContain(
+ "import { definePageLayout } from 'twenty-sdk/define';",
+ );
+ });
+
+ it('should write a standalone page layout tab with its widgets under the tab enum bindings', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'definePageLayoutTab',
+ config: {
+ universalIdentifier: 'tab-uid',
+ pageLayoutUniversalIdentifier: 'page-layout-uid',
+ title: 'Extra',
+ position: 60,
+ layoutMode: 'VERTICAL_LIST',
+ widgets: [
+ {
+ universalIdentifier: 'widget-uid',
+ title: 'Docs',
+ type: 'IFRAME',
+ position: { layoutMode: 'VERTICAL_LIST', index: 0 },
+ configuration: {
+ configurationType: 'IFRAME',
+ url: 'https://example.com/docs',
+ },
+ },
+ ],
+ },
+ enumBindings: PAGE_LAYOUT_TAB_ENUM_BINDINGS,
+ });
+
+ expect(file).toBe(
+ 'import {\n' +
+ ' definePageLayoutTab,\n' +
+ ' PageLayoutTabLayoutMode,\n' +
+ ' WidgetType,\n' +
+ "} from 'twenty-sdk/define';\n" +
+ '\n' +
+ 'export default definePageLayoutTab({\n' +
+ " universalIdentifier: 'tab-uid',\n" +
+ " pageLayoutUniversalIdentifier: 'page-layout-uid',\n" +
+ " title: 'Extra',\n" +
+ ' position: 60,\n' +
+ ' layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,\n' +
+ ' widgets: [\n' +
+ ' {\n' +
+ " universalIdentifier: 'widget-uid',\n" +
+ " title: 'Docs',\n" +
+ ' type: WidgetType.IFRAME,\n' +
+ ' position: {\n' +
+ ' layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,\n' +
+ ' index: 0,\n' +
+ ' },\n' +
+ ' configuration: {\n' +
+ " configurationType: 'IFRAME',\n" +
+ " url: 'https://example.com/docs',\n" +
+ ' },\n' +
+ ' },\n' +
+ ' ],\n' +
+ '});\n',
+ );
+ });
+
+ it('should write a nameless object navigation menu item with its type as a NavigationMenuItemType member', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineNavigationMenuItem',
+ config: {
+ universalIdentifier: 'ad199fde-d4f4-4634-a94c-95b52fa32567',
+ type: 'OBJECT',
+ position: 8,
+ targetObjectUniversalIdentifier: '5c5822f2-9efa-4cb7-8101-98f5c25765b9',
+ },
+ enumBindings: NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ });
+
+ expect(file).toBe(
+ 'import {\n' +
+ ' defineNavigationMenuItem,\n' +
+ ' NavigationMenuItemType,\n' +
+ "} from 'twenty-sdk/define';\n" +
+ '\n' +
+ 'export default defineNavigationMenuItem({\n' +
+ " universalIdentifier: 'ad199fde-d4f4-4634-a94c-95b52fa32567',\n" +
+ ' type: NavigationMenuItemType.OBJECT,\n' +
+ ' position: 8,\n' +
+ " targetObjectUniversalIdentifier: '5c5822f2-9efa-4cb7-8101-98f5c25765b9',\n" +
+ '});\n',
+ );
+ });
+
+ it('should write a folder navigation menu item with its name and icon', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineNavigationMenuItem',
+ config: {
+ universalIdentifier: 'navigation-menu-item-uid',
+ type: 'FOLDER',
+ position: 2,
+ name: 'Operations',
+ icon: 'IconFolder',
+ },
+ enumBindings: NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ });
+
+ expect(file).toBe(
+ 'import {\n' +
+ ' defineNavigationMenuItem,\n' +
+ ' NavigationMenuItemType,\n' +
+ "} from 'twenty-sdk/define';\n" +
+ '\n' +
+ 'export default defineNavigationMenuItem({\n' +
+ " universalIdentifier: 'navigation-menu-item-uid',\n" +
+ ' type: NavigationMenuItemType.FOLDER,\n' +
+ ' position: 2,\n' +
+ " name: 'Operations',\n" +
+ " icon: 'IconFolder',\n" +
+ '});\n',
+ );
+ });
+
+ it('should write the row-level predicates, predicate groups and system permission flags of a role as enum members', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'defineRole',
+ config: {
+ universalIdentifier: 'role-uid',
+ label: 'Auditor',
+ rowLevelPermissionPredicateGroups: [
+ {
+ universalIdentifier: 'predicate-group-uid',
+ objectUniversalIdentifier: 'object-uid',
+ logicalOperator: 'OR',
+ },
+ ],
+ rowLevelPermissionPredicates: [
+ {
+ universalIdentifier: 'predicate-uid',
+ objectUniversalIdentifier: 'object-uid',
+ fieldUniversalIdentifier: 'field-uid',
+ operand: 'CONTAINS',
+ value: 'Rex',
+ predicateGroupUniversalIdentifier: 'predicate-group-uid',
+ },
+ ],
+ permissionFlagUniversalIdentifiers: [
+ SystemPermissionFlag.WORKSPACE,
+ 'application-permission-flag-uid',
+ ],
+ },
+ enumBindings: ROLE_ENUM_BINDINGS,
+ });
+
+ expect(
+ file.startsWith(
+ 'import {\n' +
+ ' defineRole,\n' +
+ ' RowLevelPermissionPredicateGroupLogicalOperator,\n' +
+ ' RowLevelPermissionPredicateOperand,\n' +
+ ' SystemPermissionFlag,\n' +
+ "} from 'twenty-sdk/define';\n",
+ ),
+ ).toBe(true);
+ expect(file).toContain(
+ 'logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator.OR,',
+ );
+ expect(file).toContain(
+ 'operand: RowLevelPermissionPredicateOperand.CONTAINS,',
+ );
+ expect(file).toContain('SystemPermissionFlag.WORKSPACE');
+ expect(file).toContain("'application-permission-flag-uid'");
+ });
+
+ it('should write a permission flag with its permission type as a literal', () => {
+ const { content: file } = writeDefineFile({
+ definer: 'definePermissionFlag',
+ config: {
+ universalIdentifier: 'permission-flag-uid',
+ key: 'EXPORT_PETS',
+ label: 'Export pets',
+ permissionType: 'settings',
+ },
+ });
+
+ expect(file).toBe(
+ "import { definePermissionFlag } from 'twenty-sdk/define';\n" +
+ '\n' +
+ 'export default definePermissionFlag({\n' +
+ " universalIdentifier: 'permission-flag-uid',\n" +
+ " key: 'EXPORT_PETS',\n" +
+ " label: 'Export pets',\n" +
+ " permissionType: 'settings',\n" +
+ '});\n',
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/app/pull/app-path-error.ts b/packages/twenty-cli/src/app/pull/app-path-error.ts
new file mode 100644
index 00000000000..ed5b5b9302e
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/app-path-error.ts
@@ -0,0 +1 @@
+export class AppPathError extends Error {}
diff --git a/packages/twenty-cli/src/app/pull/apply-pull-writes.ts b/packages/twenty-cli/src/app/pull/apply-pull-writes.ts
new file mode 100644
index 00000000000..8eac1ad273a
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/apply-pull-writes.ts
@@ -0,0 +1,232 @@
+import { copy, ensureDir, pathExists, remove } from '@/app/fs-utils';
+import { type PullDeletion, type PullWrite } from '@/app/pull/plan-pull-writes';
+import { CliError } from '@/output/cli-error';
+import { lstat, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
+
+const PULL_WORK_DIRECTORY = '.twenty/cli';
+
+const assertPlanIsApplicable = async ({
+ appPath,
+ writes,
+ deletions,
+}: {
+ appPath: string;
+ writes: Pick<PullWrite, 'relativePath' | 'content'>[];
+ deletions: PullDeletion[];
+}): Promise<void> => {
+ const relativePaths = writes.map((write) => write.relativePath);
+
+ if (new Set(relativePaths).size !== relativePaths.length) {
+ throw new Error(
+ 'Refusing to write: two entities resolved to the same file path',
+ );
+ }
+
+ const applicationRoot = resolve(appPath);
+
+ for (const relativePath of [
+ ...relativePaths,
+ ...deletions.map((deletion) => deletion.relativePath),
+ ]) {
+ const containedPath = relative(
+ applicationRoot,
+ resolve(applicationRoot, relativePath),
+ );
+
+ if (
+ containedPath.length === 0 ||
+ containedPath === '..' ||
+ containedPath.startsWith(`..${sep}`) ||
+ isAbsolute(containedPath)
+ ) {
+ throw new Error(
+ `Refusing to write: ${relativePath} leaves the application directory`,
+ );
+ }
+
+ const destinationPath = join(appPath, relativePath);
+
+ if (!(await pathExists(destinationPath))) {
+ continue;
+ }
+
+ const destinationStats = await lstat(destinationPath);
+
+ if (destinationStats.isDirectory()) {
+ throw new Error(
+ `Refusing to write: ${relativePath} is a directory, and pull never deletes a folder`,
+ );
+ }
+ }
+};
+
+const backUpExistingFile = async ({
+ appPath,
+ backupDirectory,
+ relativePath,
+}: {
+ appPath: string;
+ backupDirectory: string;
+ relativePath: string;
+}): Promise<boolean> => {
+ const destinationPath = join(appPath, relativePath);
+
+ if (!(await pathExists(destinationPath))) {
+ return false;
+ }
+
+ const backupPath = join(backupDirectory, relativePath);
+
+ await ensureDir(dirname(backupPath));
+ await copy(destinationPath, backupPath);
+
+ return true;
+};
+
+const restoreBackedUpFiles = async ({
+ appPath,
+ backupDirectory,
+ backedUpRelativePaths,
+ writtenRelativePaths,
+}: {
+ appPath: string;
+ backupDirectory: string;
+ backedUpRelativePaths: string[];
+ writtenRelativePaths: string[];
+}): Promise<void> => {
+ for (const relativePath of writtenRelativePaths) {
+ await rm(join(appPath, relativePath), { force: true });
+ }
+
+ for (const relativePath of backedUpRelativePaths) {
+ const destinationPath = join(appPath, relativePath);
+
+ await ensureDir(dirname(destinationPath));
+ await rm(destinationPath, { force: true });
+ await copy(join(backupDirectory, relativePath), destinationPath);
+ }
+};
+
+export const applyPullWrites = async ({
+ appPath,
+ writes,
+ deletions,
+ finalWrite,
+ signal,
+}: {
+ appPath: string;
+ writes: PullWrite[];
+ deletions: PullDeletion[];
+ finalWrite?: Pick<PullWrite, 'relativePath' | 'content'>;
+ signal?: AbortSignal;
+}): Promise<void> => {
+ const allWrites = finalWrite ? [...writes, finalWrite] : writes;
+
+ signal?.throwIfAborted();
+ await assertPlanIsApplicable({ appPath, writes: allWrites, deletions });
+
+ const workDirectory = join(appPath, PULL_WORK_DIRECTORY);
+
+ await ensureDir(workDirectory);
+
+ const stagingDirectory = await mkdtemp(join(workDirectory, 'pull-staging-'));
+ const backupDirectory = await mkdtemp(join(workDirectory, 'pull-backup-'));
+ const backedUpRelativePaths: string[] = [];
+ const writtenRelativePaths: string[] = [];
+
+ try {
+ for (const write of allWrites) {
+ const stagedPath = join(stagingDirectory, write.relativePath);
+
+ await ensureDir(dirname(stagedPath));
+ await writeFile(
+ stagedPath,
+ write.content,
+ write === finalWrite ? { mode: 0o600 } : undefined,
+ );
+ }
+
+ for (const relativePath of [
+ ...allWrites.map((write) => write.relativePath),
+ ...deletions.map((deletion) => deletion.relativePath),
+ ]) {
+ const wasBackedUp = await backUpExistingFile({
+ appPath,
+ backupDirectory,
+ relativePath,
+ });
+
+ if (wasBackedUp) {
+ backedUpRelativePaths.push(relativePath);
+ }
+ }
+
+ signal?.throwIfAborted();
+
+ for (const write of writes) {
+ const destinationPath = join(appPath, write.relativePath);
+
+ await ensureDir(dirname(destinationPath));
+ writtenRelativePaths.push(write.relativePath);
+ await copy(join(stagingDirectory, write.relativePath), destinationPath);
+ }
+
+ for (const deletion of deletions) {
+ await rm(join(appPath, deletion.relativePath), { force: true });
+ }
+
+ if (finalWrite) {
+ const destinationPath = join(appPath, finalWrite.relativePath);
+
+ await ensureDir(dirname(destinationPath));
+ writtenRelativePaths.push(finalWrite.relativePath);
+ await copy(
+ join(stagingDirectory, finalWrite.relativePath),
+ destinationPath,
+ );
+ }
+ } catch (error) {
+ try {
+ await restoreBackedUpFiles({
+ appPath,
+ backupDirectory,
+ backedUpRelativePaths,
+ writtenRelativePaths: writtenRelativePaths.filter(
+ (relativePath) => !backedUpRelativePaths.includes(relativePath),
+ ),
+ });
+ } catch (restoreError) {
+ await remove(stagingDirectory).catch(() => undefined);
+
+ throw new CliError({
+ code: 'PULL_FAILED',
+ details: { outcome: 'unknown', backupDirectory },
+ message: `Pull failed and could not restore every file it had replaced. The originals are kept in ${backupDirectory}.\nOriginal failure: ${error instanceof Error ? error.message : String(error)}\nRestore failure: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`,
+ });
+ }
+
+ await remove(stagingDirectory);
+ await remove(backupDirectory);
+
+ if (signal?.aborted && Object.is(error, signal.reason)) {
+ throw error;
+ }
+ throw new CliError({
+ code: 'PULL_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ details: { outcome: 'unchanged' },
+ });
+ }
+
+ try {
+ await remove(stagingDirectory);
+ await remove(backupDirectory);
+ } catch (error) {
+ throw new CliError({
+ code: 'PULL_FAILED',
+ message: `Pull completed, but temporary files could not be removed: ${error instanceof Error ? error.message : String(error)}`,
+ details: { outcome: 'pulled', backupDirectory, stagingDirectory },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/assert-pull-paths.ts b/packages/twenty-cli/src/app/pull/assert-pull-paths.ts
new file mode 100644
index 00000000000..a3ca4c90b96
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/assert-pull-paths.ts
@@ -0,0 +1,48 @@
+import { lstat } from 'node:fs/promises';
+import { isAbsolute, relative, resolve, sep } from 'node:path';
+
+import { AppPathError } from '@/app/pull/app-path-error';
+
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const assertPullPaths = async ({
+ appPath,
+ relativePaths,
+}: {
+ appPath: string;
+ relativePaths: string[];
+}): Promise<void> => {
+ for (const relativePath of relativePaths) {
+ const containedPath = relative(appPath, resolve(appPath, relativePath));
+
+ if (
+ containedPath.length === 0 ||
+ containedPath === '..' ||
+ containedPath.startsWith(`..${sep}`) ||
+ isAbsolute(containedPath)
+ ) {
+ throw new AppPathError(
+ `Path leaves the application directory: ${relativePath}`,
+ );
+ }
+
+ let currentPath = appPath;
+
+ for (const part of containedPath.split(sep)) {
+ currentPath = resolve(currentPath, part);
+
+ try {
+ if ((await lstat(currentPath)).isSymbolicLink()) {
+ throw new AppPathError(
+ `Cannot follow symbolic links: ${relativePath}`,
+ );
+ }
+ } catch (error) {
+ if (hasErrorCode(error, 'ENOENT')) {
+ break;
+ }
+ throw error;
+ }
+ }
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts
new file mode 100644
index 00000000000..5de2d047956
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts
@@ -0,0 +1,39 @@
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type PullWrite } from '@/app/pull/plan-pull-writes';
+import { CliError } from '@/output/cli-error';
+
+export const assertPullSdkExports = ({
+ appPath,
+ writes,
+}: {
+ appPath: string;
+ writes: Pick<PullWrite, 'requiredSdkExports'>[];
+}) => {
+ const requiredNames = new Set(
+ writes.flatMap((write) => write.requiredSdkExports),
+ );
+
+ if (requiredNames.size === 0) {
+ return;
+ }
+
+ const defineExports: Record<string, unknown> = createRequire(
+ join(appPath, 'package.json'),
+ )('twenty-sdk/define');
+
+ const missingNames = [...requiredNames]
+ .filter((name) => !isDefined(defineExports[name]))
+ .sort();
+
+ if (missingNames.length > 0) {
+ throw new CliError({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ message: `The app's twenty-sdk cannot read the generated definitions. Missing exports: ${missingNames.join(', ')}.`,
+ hint: 'Upgrade the app to a compatible twenty-sdk version (2.40.0 or later).',
+ details: { missingNames },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/build-manifest-entity-label-by-universal-identifier.ts b/packages/twenty-cli/src/app/pull/build-manifest-entity-label-by-universal-identifier.ts
new file mode 100644
index 00000000000..376ffb39e59
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/build-manifest-entity-label-by-universal-identifier.ts
@@ -0,0 +1,56 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+const LABEL_KEYS = ['nameSingular', 'name', 'label', 'title'] as const;
+
+export const buildManifestEntityLabelByUniversalIdentifier = (
+ manifest: Record<string, unknown>,
+): Record<string, string> => {
+ const labelByUniversalIdentifier: Record<string, string> = {};
+
+ const pending: { value: unknown; parentLabel?: string }[] = [
+ { value: manifest },
+ ];
+
+ while (pending.length > 0) {
+ const entry = pending.pop();
+
+ if (!isDefined(entry)) {
+ break;
+ }
+
+ const { value, parentLabel } = entry;
+
+ if (Array.isArray(value)) {
+ for (const item of [...value].reverse()) {
+ pending.push({ value: item, parentLabel });
+ }
+
+ continue;
+ }
+
+ if (!isPlainObject(value)) {
+ continue;
+ }
+
+ const ownLabel = LABEL_KEYS.map((key) => value[key]).find(isNonEmptyString);
+ const label =
+ isDefined(ownLabel) && isDefined(parentLabel)
+ ? `${parentLabel}.${ownLabel}`
+ : (ownLabel ?? parentLabel);
+
+ if (
+ isDefined(ownLabel) &&
+ isDefined(label) &&
+ isNonEmptyString(value.universalIdentifier)
+ ) {
+ labelByUniversalIdentifier[value.universalIdentifier] = label;
+ }
+
+ for (const child of Object.values(value).reverse()) {
+ pending.push({ value: child, parentLabel: label });
+ }
+ }
+
+ return labelByUniversalIdentifier;
+};
diff --git a/packages/twenty-cli/src/app/pull/build-pull-base-entities.ts b/packages/twenty-cli/src/app/pull/build-pull-base-entities.ts
new file mode 100644
index 00000000000..0804897d691
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/build-pull-base-entities.ts
@@ -0,0 +1,30 @@
+import { isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type PullEntity } from '@/app/pull/build-pull-entities';
+
+export const buildPullBaseEntities = ({
+ entities,
+ unreconciledUniversalIdentifiers,
+}: {
+ entities: PullEntity[];
+ unreconciledUniversalIdentifiers?: ReadonlySet<string>;
+}): PullEntity[] =>
+ entities.map((entity) => {
+ if (
+ entity.kind !== 'application' ||
+ !isPlainObject(entity.config) ||
+ !isString(entity.config.defaultRoleUniversalIdentifier) ||
+ !unreconciledUniversalIdentifiers?.has(
+ entity.config.defaultRoleUniversalIdentifier.toLowerCase(),
+ )
+ ) {
+ return entity;
+ }
+
+ // A skipped default role still owns the application's default-role declaration.
+ const { defaultRoleUniversalIdentifier: _identifier, ...config } =
+ entity.config;
+
+ return { ...entity, config };
+ });
diff --git a/packages/twenty-cli/src/app/pull/build-pull-entities.ts b/packages/twenty-cli/src/app/pull/build-pull-entities.ts
new file mode 100644
index 00000000000..f8963e769b7
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/build-pull-entities.ts
@@ -0,0 +1,375 @@
+import {
+ FIELD_ENUM_BINDINGS,
+ INDEX_ENUM_BINDINGS,
+ NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ PAGE_LAYOUT_WIDGET_ENUM_BINDINGS,
+ OBJECT_ENUM_BINDINGS,
+ PAGE_LAYOUT_ENUM_BINDINGS,
+ PAGE_LAYOUT_TAB_ENUM_BINDINGS,
+ ROLE_ENUM_BINDINGS,
+ VIEW_ENUM_BINDINGS,
+ VIEW_FIELD_ENUM_BINDINGS,
+ type EnumBinding,
+} from '@/app/pull/write-define-file';
+import {
+ buildIndexFileBaseName,
+ buildViewFieldFileBaseName,
+ type FieldLocation,
+ toFileBaseName,
+} from '@/app/pull/pull-file-base-name';
+import { stripGraphqlTypename } from '@/app/pull/strip-graphql-typename';
+import { kebabCase } from '@/app/pull/kebab-case';
+import { type Manifest } from 'twenty-shared/application';
+import { fromApplicationManifestToApplicationConfig } from '@/app/pull/from-application-manifest-to-application-config';
+import { fromRoleManifestToRoleConfig } from '@/app/pull/from-role-manifest-to-role-config';
+import { buildPullFieldFileName } from '@/app/pull/build-pull-field-file-name';
+import { buildPullNavigationMenuItemFileName } from '@/app/pull/build-pull-navigation-menu-item-file-name';
+import { getObjectNameForPullFile } from '@/app/pull/get-object-name-for-pull-file';
+import { getPageLayoutNameForPullFile } from '@/app/pull/get-page-layout-name-for-pull-file';
+import { getNavigationFolderNameForPullFile } from '@/app/pull/get-navigation-folder-name-for-pull-file';
+import { isDefined } from 'twenty-shared/utils';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+
+export const PULL_ENTITY_KINDS = [
+ 'application',
+ 'object',
+ 'field',
+ 'index',
+ 'permissionFlag',
+ 'role',
+ 'view',
+ 'viewField',
+ 'pageLayout',
+ 'pageLayoutTab',
+ 'navigationMenuItem',
+ 'pageLayoutWidget',
+] as const;
+
+export type PullEntityKind = (typeof PULL_ENTITY_KINDS)[number];
+
+export type PullEntity = {
+ kind: PullEntityKind;
+ universalIdentifier: string;
+ definer: string;
+ config: unknown;
+ enumBindings: EnumBinding[];
+ defaultFolder: string;
+ fileSuffix: string;
+ fileBaseName: string;
+ parentName: string | null;
+};
+
+export type SkippedPullEntity = {
+ kind: PullEntityKind;
+ universalIdentifier: string;
+ reason: string;
+};
+
+export const buildPullEntities = (
+ manifest: Manifest,
+ sourceFileByUniversalIdentifier: ReadonlyMap<
+ string,
+ ScannedSourceFile
+ > = new Map(),
+): { entities: PullEntity[]; skipped: SkippedPullEntity[] } => {
+ const applicationUniversalIdentifier =
+ manifest.application.universalIdentifier;
+ const entities: PullEntity[] = [];
+ const skipped: SkippedPullEntity[] = [];
+
+ entities.push({
+ kind: 'application',
+ universalIdentifier: applicationUniversalIdentifier,
+ definer: 'defineApplication',
+ config: fromApplicationManifestToApplicationConfig(manifest),
+ enumBindings: [],
+ defaultFolder: 'src',
+ fileSuffix: '.config.ts',
+ fileBaseName: 'application',
+ parentName: null,
+ });
+
+ const writtenObjectUniversalIdentifiers = new Set<string>();
+ const fieldLocationByUniversalIdentifier = new Map<string, FieldLocation>();
+ const standaloneFields = [...(manifest.fields ?? [])];
+
+ for (const objectManifest of manifest.objects ?? []) {
+ const inlineFields = [];
+
+ for (const field of objectManifest.fields ?? []) {
+ fieldLocationByUniversalIdentifier.set(field.universalIdentifier, {
+ objectName: objectManifest.nameSingular,
+ fieldName: field.name,
+ });
+ if (
+ sourceFileByUniversalIdentifier.get(
+ field.universalIdentifier.toLowerCase(),
+ )?.entityKey === 'fields'
+ ) {
+ standaloneFields.push({
+ ...field,
+ objectUniversalIdentifier: objectManifest.universalIdentifier,
+ });
+ } else {
+ inlineFields.push(field);
+ }
+ }
+
+ writtenObjectUniversalIdentifiers.add(objectManifest.universalIdentifier);
+
+ entities.push({
+ kind: 'object',
+ universalIdentifier: objectManifest.universalIdentifier,
+ definer: 'defineObject',
+ config: { ...objectManifest, fields: inlineFields },
+ enumBindings: OBJECT_ENUM_BINDINGS,
+ defaultFolder: 'src/objects',
+ fileSuffix: '.object.ts',
+ fileBaseName: kebabCase(objectManifest.nameSingular),
+ parentName: null,
+ });
+ }
+
+ for (const fieldManifest of standaloneFields) {
+ const objectName = getObjectNameForPullFile({
+ objectUniversalIdentifier: fieldManifest.objectUniversalIdentifier,
+ manifest,
+ });
+
+ fieldLocationByUniversalIdentifier.set(fieldManifest.universalIdentifier, {
+ objectName,
+ fieldName: fieldManifest.name,
+ });
+
+ entities.push({
+ kind: 'field',
+ universalIdentifier: fieldManifest.universalIdentifier,
+ definer: 'defineField',
+ config: fieldManifest,
+ enumBindings: FIELD_ENUM_BINDINGS,
+ defaultFolder: 'src/fields',
+ fileSuffix: '.field.ts',
+ fileBaseName: buildPullFieldFileName({
+ objectName,
+ fieldName: fieldManifest.name,
+ fieldUniversalIdentifier: fieldManifest.universalIdentifier,
+ }),
+ parentName: objectName,
+ });
+ }
+
+ for (const indexManifest of manifest.indexes ?? []) {
+ if (
+ !writtenObjectUniversalIdentifiers.has(
+ indexManifest.objectUniversalIdentifier,
+ )
+ ) {
+ skipped.push({
+ kind: 'index',
+ universalIdentifier: indexManifest.universalIdentifier,
+ reason: 'its object is not part of the written source',
+ });
+ continue;
+ }
+
+ const objectName = getObjectNameForPullFile({
+ objectUniversalIdentifier: indexManifest.objectUniversalIdentifier,
+ manifest,
+ });
+
+ entities.push({
+ kind: 'index',
+ universalIdentifier: indexManifest.universalIdentifier,
+ definer: 'defineIndex',
+ config: indexManifest,
+ enumBindings: INDEX_ENUM_BINDINGS,
+ defaultFolder: 'src/indexes',
+ fileSuffix: '.index.ts',
+ fileBaseName: buildIndexFileBaseName({
+ indexManifest,
+ objectName,
+ fieldLocationByUniversalIdentifier,
+ }),
+ parentName: objectName,
+ });
+ }
+
+ for (const permissionFlagManifest of manifest.permissionFlags ?? []) {
+ entities.push({
+ kind: 'permissionFlag',
+ universalIdentifier: permissionFlagManifest.universalIdentifier,
+ definer: 'definePermissionFlag',
+ config: permissionFlagManifest,
+ enumBindings: [],
+ defaultFolder: 'src/permission-flags',
+ fileSuffix: '.permission-flag.ts',
+ fileBaseName: toFileBaseName({
+ segments: [permissionFlagManifest.key],
+ universalIdentifier: permissionFlagManifest.universalIdentifier,
+ }),
+ parentName: null,
+ });
+ }
+
+ for (const roleManifest of manifest.roles ?? []) {
+ entities.push({
+ kind: 'role',
+ universalIdentifier: roleManifest.universalIdentifier,
+ definer:
+ roleManifest.universalIdentifier ===
+ manifest.application.defaultRoleUniversalIdentifier
+ ? 'defineApplicationRole'
+ : 'defineRole',
+ config: fromRoleManifestToRoleConfig({
+ roleManifest,
+ applicationUniversalIdentifier,
+ }),
+ enumBindings: ROLE_ENUM_BINDINGS,
+ defaultFolder: 'src/roles',
+ fileSuffix: '.role.ts',
+ fileBaseName: toFileBaseName({
+ segments: [roleManifest.label],
+ universalIdentifier: roleManifest.universalIdentifier,
+ }),
+ parentName: null,
+ });
+ }
+
+ for (const viewManifest of manifest.views ?? []) {
+ entities.push({
+ kind: 'view',
+ universalIdentifier: viewManifest.universalIdentifier,
+ definer: 'defineView',
+ config: viewManifest,
+ enumBindings: VIEW_ENUM_BINDINGS,
+ defaultFolder: 'src/views',
+ fileSuffix: '.view.ts',
+ fileBaseName: toFileBaseName({
+ segments: [viewManifest.name],
+ universalIdentifier: viewManifest.universalIdentifier,
+ }),
+ parentName: getObjectNameForPullFile({
+ objectUniversalIdentifier: viewManifest.objectUniversalIdentifier,
+ manifest,
+ }),
+ });
+ }
+
+ for (const viewFieldManifest of manifest.viewFields ?? []) {
+ entities.push({
+ kind: 'viewField',
+ universalIdentifier: viewFieldManifest.universalIdentifier,
+ definer: 'defineViewField',
+ config: viewFieldManifest,
+ enumBindings: VIEW_FIELD_ENUM_BINDINGS,
+ defaultFolder: 'src/view-fields',
+ fileSuffix: '.view-field.ts',
+ fileBaseName: buildViewFieldFileBaseName({
+ viewFieldManifest,
+ fieldLocationByUniversalIdentifier,
+ }),
+ parentName: null,
+ });
+ }
+
+ for (const pageLayoutManifest of manifest.pageLayouts ?? []) {
+ entities.push({
+ kind: 'pageLayout',
+ universalIdentifier: pageLayoutManifest.universalIdentifier,
+ definer: 'definePageLayout',
+ config: stripGraphqlTypename(pageLayoutManifest),
+ enumBindings: PAGE_LAYOUT_ENUM_BINDINGS,
+ defaultFolder: 'src/page-layouts',
+ fileSuffix: '.page-layout.ts',
+ fileBaseName: toFileBaseName({
+ segments: [pageLayoutManifest.name],
+ universalIdentifier: pageLayoutManifest.universalIdentifier,
+ }),
+ parentName: isDefined(pageLayoutManifest.objectUniversalIdentifier)
+ ? getObjectNameForPullFile({
+ objectUniversalIdentifier:
+ pageLayoutManifest.objectUniversalIdentifier,
+ manifest,
+ })
+ : null,
+ });
+ }
+
+ for (const pageLayoutTabManifest of manifest.pageLayoutTabs ?? []) {
+ const { pageLayoutUniversalIdentifier } = pageLayoutTabManifest;
+
+ if (!isDefined(pageLayoutUniversalIdentifier)) {
+ skipped.push({
+ kind: 'pageLayoutTab',
+ universalIdentifier: pageLayoutTabManifest.universalIdentifier,
+ reason: 'it does not name the page layout it belongs to',
+ });
+ continue;
+ }
+
+ entities.push({
+ kind: 'pageLayoutTab',
+ universalIdentifier: pageLayoutTabManifest.universalIdentifier,
+ definer: 'definePageLayoutTab',
+ config: stripGraphqlTypename(pageLayoutTabManifest),
+ enumBindings: PAGE_LAYOUT_TAB_ENUM_BINDINGS,
+ defaultFolder: 'src/page-layout-tabs',
+ fileSuffix: '.page-layout-tab.ts',
+ fileBaseName: toFileBaseName({
+ segments: [pageLayoutTabManifest.title],
+ universalIdentifier: pageLayoutTabManifest.universalIdentifier,
+ }),
+ parentName: getPageLayoutNameForPullFile({
+ pageLayoutUniversalIdentifier,
+ manifest,
+ }),
+ });
+ }
+
+ for (const navigationMenuItemManifest of manifest.navigationMenuItems ?? []) {
+ const { folderUniversalIdentifier } = navigationMenuItemManifest;
+
+ entities.push({
+ kind: 'navigationMenuItem',
+ universalIdentifier: navigationMenuItemManifest.universalIdentifier,
+ definer: 'defineNavigationMenuItem',
+ config: navigationMenuItemManifest,
+ enumBindings: NAVIGATION_MENU_ITEM_ENUM_BINDINGS,
+ defaultFolder: 'src/navigation-menu-items',
+ fileSuffix: '.navigation-menu-item.ts',
+ fileBaseName: buildPullNavigationMenuItemFileName({
+ navigationMenuItemManifest,
+ manifest,
+ }),
+ parentName: isDefined(folderUniversalIdentifier)
+ ? getNavigationFolderNameForPullFile({
+ folderUniversalIdentifier,
+ manifest,
+ })
+ : null,
+ });
+ }
+
+ for (const pageLayoutWidgetManifest of manifest.pageLayoutWidgets ?? []) {
+ const { objectUniversalIdentifier } = pageLayoutWidgetManifest;
+
+ entities.push({
+ kind: 'pageLayoutWidget',
+ universalIdentifier: pageLayoutWidgetManifest.universalIdentifier,
+ definer: 'definePageLayoutWidget',
+ config: stripGraphqlTypename(pageLayoutWidgetManifest),
+ enumBindings: PAGE_LAYOUT_WIDGET_ENUM_BINDINGS,
+ defaultFolder: 'src/page-layout-widgets',
+ fileSuffix: '.page-layout-widget.ts',
+ fileBaseName: toFileBaseName({
+ segments: [pageLayoutWidgetManifest.title],
+ universalIdentifier: pageLayoutWidgetManifest.universalIdentifier,
+ }),
+ parentName: isDefined(objectUniversalIdentifier)
+ ? getObjectNameForPullFile({ objectUniversalIdentifier, manifest })
+ : null,
+ });
+ }
+
+ return { entities, skipped };
+};
diff --git a/packages/twenty-cli/src/app/pull/build-pull-field-file-name.ts b/packages/twenty-cli/src/app/pull/build-pull-field-file-name.ts
new file mode 100644
index 00000000000..8a73070ded4
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/build-pull-field-file-name.ts
@@ -0,0 +1,15 @@
+import { toFileBaseName } from '@/app/pull/pull-file-base-name';
+
+export const buildPullFieldFileName = ({
+ objectName,
+ fieldName,
+ fieldUniversalIdentifier,
+}: {
+ objectName: string | null;
+ fieldName: string;
+ fieldUniversalIdentifier: string;
+}): string =>
+ toFileBaseName({
+ segments: [objectName, fieldName],
+ universalIdentifier: fieldUniversalIdentifier,
+ });
diff --git a/packages/twenty-cli/src/app/pull/build-pull-navigation-menu-item-file-name.ts b/packages/twenty-cli/src/app/pull/build-pull-navigation-menu-item-file-name.ts
new file mode 100644
index 00000000000..c155ef3f902
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/build-pull-navigation-menu-item-file-name.ts
@@ -0,0 +1,110 @@
+import { getObjectNameForPullFile } from '@/app/pull/get-object-name-for-pull-file';
+import { getPageLayoutNameForPullFile } from '@/app/pull/get-page-layout-name-for-pull-file';
+import {
+ isUsableFileNameSegment,
+ toFileBaseName,
+} from '@/app/pull/pull-file-base-name';
+import {
+ getSystemViewUniversalIdentifier,
+ type Manifest,
+ type NavigationMenuItemManifest,
+ SYSTEM_VIEW_KEYS,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { NavigationMenuItemType } from 'twenty-shared/types';
+
+const getViewName = ({
+ viewUniversalIdentifier,
+ manifest,
+}: {
+ viewUniversalIdentifier: string;
+ manifest: Manifest;
+}): string | null => {
+ const viewManifest = manifest.views?.find(
+ (candidate) => candidate.universalIdentifier === viewUniversalIdentifier,
+ );
+
+ if (isDefined(viewManifest)) {
+ return viewManifest.name;
+ }
+
+ const objectMetadataApplicationUniversalIdentifier =
+ manifest.application.universalIdentifier;
+
+ for (const objectManifest of manifest.objects ?? []) {
+ if (
+ getSystemViewUniversalIdentifier({
+ objectMetadataApplicationUniversalIdentifier,
+ objectUniversalIdentifier: objectManifest.universalIdentifier,
+ viewKey: SYSTEM_VIEW_KEYS.INDEX,
+ }) === viewUniversalIdentifier
+ ) {
+ return `${objectManifest.nameSingular}IndexView`;
+ }
+ }
+
+ return null;
+};
+
+const getNavigationMenuItemName = ({
+ navigationMenuItemManifest,
+ manifest,
+}: {
+ navigationMenuItemManifest: NavigationMenuItemManifest;
+ manifest: Manifest;
+}): string | null => {
+ const {
+ type,
+ name,
+ targetObjectUniversalIdentifier,
+ viewUniversalIdentifier,
+ pageLayoutUniversalIdentifier,
+ } = navigationMenuItemManifest;
+
+ if (isUsableFileNameSegment(name)) {
+ return name;
+ }
+
+ if (
+ type === NavigationMenuItemType.OBJECT &&
+ isDefined(targetObjectUniversalIdentifier)
+ ) {
+ return getObjectNameForPullFile({
+ objectUniversalIdentifier: targetObjectUniversalIdentifier,
+ manifest,
+ });
+ }
+
+ if (
+ type === NavigationMenuItemType.VIEW &&
+ isDefined(viewUniversalIdentifier)
+ ) {
+ return getViewName({ viewUniversalIdentifier, manifest });
+ }
+
+ if (
+ type === NavigationMenuItemType.PAGE_LAYOUT &&
+ isDefined(pageLayoutUniversalIdentifier)
+ ) {
+ return getPageLayoutNameForPullFile({
+ pageLayoutUniversalIdentifier,
+ manifest,
+ });
+ }
+
+ return null;
+};
+
+export const buildPullNavigationMenuItemFileName = ({
+ navigationMenuItemManifest,
+ manifest,
+}: {
+ navigationMenuItemManifest: NavigationMenuItemManifest;
+ manifest: Manifest;
+}): string =>
+ toFileBaseName({
+ segments: [
+ getNavigationMenuItemName({ navigationMenuItemManifest, manifest }),
+ ],
+ universalIdentifier: navigationMenuItemManifest.universalIdentifier,
+ });
diff --git a/packages/twenty-cli/src/app/pull/collect-identifiers.ts b/packages/twenty-cli/src/app/pull/collect-identifiers.ts
new file mode 100644
index 00000000000..cb3ef1a2c91
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/collect-identifiers.ts
@@ -0,0 +1,21 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+export const collectIdentifiers = ({
+ value,
+ identifiers,
+}: {
+ value: unknown;
+ identifiers: Set<string>;
+}): void => {
+ if (isArray(value)) {
+ value.forEach((entry) => collectIdentifiers({ value: entry, identifiers }));
+ } else if (isPlainObject(value)) {
+ if (isString(value.universalIdentifier)) {
+ identifiers.add(value.universalIdentifier.toLowerCase());
+ }
+ Object.values(value).forEach((entry) =>
+ collectIdentifiers({ value: entry, identifiers }),
+ );
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts b/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts
new file mode 100644
index 00000000000..bb2453e34ab
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts
@@ -0,0 +1,31 @@
+import { readFile } from 'node:fs/promises';
+import { relative, sep } from 'node:path';
+
+import { glob } from 'tinyglobby';
+
+import { hashContent } from '@/utils/hash-content';
+import { listApplicationSourceFiles } from '@/app/source/list-application-source-files';
+import {
+ COMPILED_LOCALES_DIR,
+ LOCALES_DIR,
+} from '@/app/translations/constants';
+
+export const collectSourceFingerprints = async (
+ appPath: string,
+): Promise<Record<string, string>> => {
+ const localeFilePaths = await glob(
+ [`${LOCALES_DIR}/*.json`, `${COMPILED_LOCALES_DIR}/*.json`],
+ { cwd: appPath, absolute: true, onlyFiles: true },
+ );
+ const fingerprints: Record<string, string> = {};
+
+ for (const filePath of [
+ ...(await listApplicationSourceFiles(appPath)),
+ ...localeFilePaths.sort(),
+ ]) {
+ fingerprints[relative(appPath, filePath).split(sep).join('/')] =
+ hashContent(await readFile(filePath));
+ }
+
+ return fingerprints;
+};
diff --git a/packages/twenty-cli/src/app/pull/create-pull-base-write.ts b/packages/twenty-cli/src/app/pull/create-pull-base-write.ts
new file mode 100644
index 00000000000..6266d25eab9
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/create-pull-base-write.ts
@@ -0,0 +1,45 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';
+import { normalizePullTarget } from '@/app/pull/normalize-pull-target';
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+import { type PullTarget } from '@/app/types/pull-target.type';
+
+const compareRelativePaths = (
+ [first]: [string, string],
+ [second]: [string, string],
+) => (first < second ? -1 : first > second ? 1 : 0);
+
+export const createPullBaseWrite = ({
+ manifest,
+ target,
+ unreconciledUniversalIdentifiers = [],
+ sourceFingerprints,
+}: {
+ manifest: ExportedManifest;
+ target: PullTarget;
+ unreconciledUniversalIdentifiers?: string[];
+ sourceFingerprints?: Record<string, string>;
+}) => ({
+ relativePath: PULL_BASE_FILE_PATH,
+ content: `${JSON.stringify(
+ {
+ version: 2,
+ target: normalizePullTarget(target),
+ applicationUniversalIdentifier: manifest.application.universalIdentifier,
+ manifest,
+ ...(unreconciledUniversalIdentifiers.length > 0
+ ? { unreconciledUniversalIdentifiers }
+ : {}),
+ ...(isDefined(sourceFingerprints)
+ ? {
+ sourceFingerprints: Object.fromEntries(
+ Object.entries(sourceFingerprints).sort(compareRelativePaths),
+ ),
+ }
+ : {}),
+ },
+ null,
+ 2,
+ )}\n`,
+});
diff --git a/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts
new file mode 100644
index 00000000000..518af651115
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts
@@ -0,0 +1,17 @@
+import { type PullEntityKind } from '@/app/pull/build-pull-entities';
+import { type ManifestEntityKey } from '@/app/source/extract-define-entity';
+
+export const ENTITY_KEY_BY_KIND: Record<PullEntityKind, ManifestEntityKey> = {
+ application: 'application',
+ object: 'objects',
+ field: 'fields',
+ index: 'indexes',
+ permissionFlag: 'permissionFlags',
+ role: 'roles',
+ view: 'views',
+ viewField: 'viewFields',
+ pageLayout: 'pageLayouts',
+ pageLayoutTab: 'pageLayoutTabs',
+ navigationMenuItem: 'navigationMenuItems',
+ pageLayoutWidget: 'pageLayoutWidgets',
+};
diff --git a/packages/twenty-cli/src/app/pull/format-pull-report.ts b/packages/twenty-cli/src/app/pull/format-pull-report.ts
new file mode 100644
index 00000000000..ce563ecbf46
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/format-pull-report.ts
@@ -0,0 +1,229 @@
+import { type AppExportCoverageEntry } from '@/app/types/app-export.type';
+import { type SkippedPullEntity } from '@/app/pull/build-pull-entities';
+import { type PullDeletion } from '@/app/pull/plan-pull-writes';
+import { type PullAppResult } from '@/app/pull/types';
+import { isDefined } from 'twenty-shared/utils';
+
+const MAX_LISTED_IDENTIFIERS = 20;
+
+const COVERAGE_SECTIONS = [
+ {
+ status: 'UNSUPPORTED' as const,
+ title: 'Not written, unsupported by this version',
+ },
+ {
+ status: 'FOREIGN_OWNED' as const,
+ title: 'Owned by another application, not written',
+ },
+ {
+ status: 'EXCLUDED' as const,
+ title: 'Excluded as workspace runtime state',
+ },
+ {
+ status: 'ENGINE_DERIVED' as const,
+ title: 'Derived by the engine, rebuilt on apply',
+ },
+] as const;
+
+const formatFileGroup = ({
+ title,
+ relativePaths,
+}: {
+ title: string;
+ relativePaths: string[];
+}): string[] =>
+ relativePaths.length === 0
+ ? []
+ : relativePaths
+ .slice()
+ .sort()
+ .map((relativePath) => ` ${title.padEnd(13)}${relativePath}`);
+
+type CoverageGroup = {
+ metadataName: string;
+ reason: string | null;
+ identifiers: string[];
+};
+
+const groupCoverageByMetadataNameAndReason = (
+ coverage: AppExportCoverageEntry[],
+): CoverageGroup[] => {
+ const groupByKey = new Map<string, CoverageGroup>();
+
+ for (const entry of coverage) {
+ const key = JSON.stringify([entry.metadataName, entry.reason]);
+ const group = groupByKey.get(key) ?? {
+ metadataName: entry.metadataName,
+ reason: entry.reason,
+ identifiers: [],
+ };
+
+ group.identifiers.push(entry.universalIdentifier);
+ groupByKey.set(key, group);
+ }
+
+ return [...groupByKey.values()].sort(
+ (left, right) =>
+ left.metadataName.localeCompare(right.metadataName) ||
+ (left.reason ?? '').localeCompare(right.reason ?? ''),
+ );
+};
+
+export const formatPullReport = ({
+ writes,
+ deletions,
+ unchangedCount,
+ skipped,
+ coverage,
+ localOnlyRelativePaths,
+ unreadableRelativePaths = [],
+ compiledTranslationEntryCountByLocale = {},
+ entityLabelByUniversalIdentifier = {},
+ verbose = false,
+}: {
+ writes: PullAppResult['writes'];
+ deletions: PullDeletion[];
+ unchangedCount: number;
+ skipped: SkippedPullEntity[];
+ coverage: AppExportCoverageEntry[];
+ localOnlyRelativePaths: string[];
+ unreadableRelativePaths?: string[];
+ compiledTranslationEntryCountByLocale?: Record<string, number>;
+ entityLabelByUniversalIdentifier?: Record<string, string>;
+ verbose?: boolean;
+}): string => {
+ const lines: string[] = [
+ ...formatFileGroup({
+ title: 'written',
+ relativePaths: writes
+ .filter((write) => !write.isRegeneration)
+ .map((write) => write.relativePath),
+ }),
+ ...formatFileGroup({
+ title: 'regenerated',
+ relativePaths: writes
+ .filter((write) => write.isRegeneration)
+ .map((write) => write.relativePath),
+ }),
+ ...formatFileGroup({
+ title: 'deleted',
+ relativePaths: deletions.map((deletion) => deletion.relativePath),
+ }),
+ ];
+
+ if (unchangedCount > 0) {
+ lines.push(` unchanged ${unchangedCount} file(s)`);
+ }
+
+ if (skipped.length > 0) {
+ lines.push('', 'Not written by the writer:');
+
+ for (const skippedEntity of skipped) {
+ lines.push(` ${skippedEntity.kind} ${skippedEntity.reason}`);
+ }
+ }
+
+ if (unreadableRelativePaths.length > 0) {
+ lines.push(
+ '',
+ 'Could not be read, so a second file may now define the same entity (check their diagnostics and SDK dependencies before pulling again):',
+ ...unreadableRelativePaths
+ .slice()
+ .sort()
+ .map((relativePath) => ` ${relativePath}`),
+ );
+ }
+
+ if (localOnlyRelativePaths.length > 0) {
+ lines.push(
+ '',
+ 'Local entities the workspace does not have (left untouched):',
+ ...localOnlyRelativePaths
+ .slice()
+ .sort()
+ .map((relativePath) => ` ${relativePath}`),
+ );
+ }
+
+ const writtenWithoutLocalState = coverage
+ .filter((entry) => entry.status === 'EXPORTED' && isDefined(entry.reason))
+ .map(
+ (entry) =>
+ ` ${entry.metadataName} ${
+ entityLabelByUniversalIdentifier[entry.universalIdentifier] ??
+ entry.universalIdentifier
+ }: ${entry.reason}`,
+ )
+ .sort();
+
+ if (writtenWithoutLocalState.length > 0) {
+ const listedWrittenWithoutLocalState = verbose
+ ? writtenWithoutLocalState
+ : writtenWithoutLocalState.slice(0, MAX_LISTED_IDENTIFIERS);
+
+ lines.push(
+ '',
+ `Written without their workspace-local state (${writtenWithoutLocalState.length} row(s)):`,
+ ...listedWrittenWithoutLocalState,
+ );
+
+ if (
+ writtenWithoutLocalState.length > listedWrittenWithoutLocalState.length
+ ) {
+ lines.push(
+ ` …and ${writtenWithoutLocalState.length - listedWrittenWithoutLocalState.length} more, listed with --verbose`,
+ );
+ }
+ }
+
+ for (const section of COVERAGE_SECTIONS) {
+ const sectionEntries = coverage.filter(
+ (entry) => entry.status === section.status,
+ );
+
+ if (sectionEntries.length === 0) {
+ continue;
+ }
+
+ lines.push('', `${section.title} (${sectionEntries.length} row(s)):`);
+
+ for (const {
+ metadataName,
+ reason,
+ identifiers,
+ } of groupCoverageByMetadataNameAndReason(sectionEntries)) {
+ lines.push(
+ ` ${metadataName.padEnd(34)}${String(identifiers.length).padEnd(6)}${reason ?? ''}`.trimEnd(),
+ );
+
+ if (verbose) {
+ for (const identifier of identifiers.slice(0, MAX_LISTED_IDENTIFIERS)) {
+ lines.push(` ${identifier}`);
+ }
+
+ if (identifiers.length > MAX_LISTED_IDENTIFIERS) {
+ lines.push(
+ ` …and ${identifiers.length - MAX_LISTED_IDENTIFIERS} more`,
+ );
+ }
+ }
+ }
+ }
+
+ const compiledLocales = Object.entries(compiledTranslationEntryCountByLocale)
+ .filter(([, count]) => count > 0)
+ .sort(([left], [right]) => left.localeCompare(right));
+
+ if (compiledLocales.length > 0) {
+ lines.push(
+ '',
+ 'Translations kept in compiled form until their source strings are in this tree (see locales/compiled/):',
+ ...compiledLocales.map(
+ ([locale, count]) =>
+ ` ${locale.padEnd(13)}${count} ${count === 1 ? 'entry' : 'entries'}`,
+ ),
+ );
+ }
+
+ return lines.join('\n');
+};
diff --git a/packages/twenty-cli/src/app/pull/from-application-manifest-to-application-config.ts b/packages/twenty-cli/src/app/pull/from-application-manifest-to-application-config.ts
new file mode 100644
index 00000000000..5c31c680538
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/from-application-manifest-to-application-config.ts
@@ -0,0 +1,63 @@
+import {
+ type ApplicationManifest,
+ type Manifest,
+} from 'twenty-shared/application';
+
+const APPLICATION_PROPERTIES_TO_STRIP = [
+ 'packageJsonChecksum',
+ 'yarnLockChecksum',
+ 'requiredServerVersionRange',
+ 'aboutDescription',
+ 'postInstallLogicFunction',
+ 'preInstallLogicFunction',
+ 'uninstallLogicFunction',
+ 'healthCheckLogicFunction',
+ 'settingsFrontComponent',
+ 'settingsCustomTabFrontComponentUniversalIdentifier',
+ 'frontComponentSharedDependencies',
+ 'logoUrl',
+ 'screenshots',
+] as const;
+
+const APPLICATION_PROPERTY_NAMES_TO_STRIP = new Set<string>(
+ APPLICATION_PROPERTIES_TO_STRIP,
+);
+
+const GENERATED_COVER_GALLERY_IMAGE = 'public/cover.generated.png';
+
+const isDefaultRoleExported = (manifest: Manifest): boolean =>
+ (manifest.roles ?? []).some(
+ ({ universalIdentifier }) =>
+ universalIdentifier ===
+ manifest.application.defaultRoleUniversalIdentifier,
+ );
+
+export const fromApplicationManifestToApplicationConfig = (
+ manifest: Manifest,
+): Partial<ApplicationManifest> => {
+ const applicationConfig = Object.fromEntries(
+ Object.entries(manifest.application).filter(
+ ([property]) =>
+ !APPLICATION_PROPERTY_NAMES_TO_STRIP.has(property) &&
+ !(
+ property === 'defaultRoleUniversalIdentifier' &&
+ isDefaultRoleExported(manifest)
+ ),
+ ),
+ ) as Partial<ApplicationManifest>;
+
+ const { galleryImages } = applicationConfig;
+
+ if (
+ !Array.isArray(galleryImages) ||
+ galleryImages.length === 0 ||
+ galleryImages.every((image) => image === GENERATED_COVER_GALLERY_IMAGE)
+ ) {
+ const { galleryImages: _galleryImages, ...withoutGalleryImages } =
+ applicationConfig;
+
+ return withoutGalleryImages;
+ }
+
+ return applicationConfig;
+};
diff --git a/packages/twenty-cli/src/app/pull/from-role-manifest-to-role-config.ts b/packages/twenty-cli/src/app/pull/from-role-manifest-to-role-config.ts
new file mode 100644
index 00000000000..0ce6933e498
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/from-role-manifest-to-role-config.ts
@@ -0,0 +1,67 @@
+import {
+ getFieldPermissionUniversalIdentifier,
+ getObjectPermissionUniversalIdentifier,
+ type RoleManifest,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+const omitDerivedUniversalIdentifiers = <
+ TPermission extends { universalIdentifier?: string },
+>({
+ permissions,
+ getDerivedUniversalIdentifier,
+}: {
+ permissions: TPermission[];
+ getDerivedUniversalIdentifier: (
+ permission: Omit<TPermission, 'universalIdentifier'>,
+ ) => string;
+}) =>
+ permissions.map(({ universalIdentifier, ...permission }) =>
+ universalIdentifier === getDerivedUniversalIdentifier(permission)
+ ? permission
+ : { universalIdentifier, ...permission },
+ );
+
+export const fromRoleManifestToRoleConfig = ({
+ roleManifest,
+ applicationUniversalIdentifier,
+}: {
+ roleManifest: RoleManifest;
+ applicationUniversalIdentifier: string;
+}): RoleManifest => {
+ const {
+ universalIdentifier: roleUniversalIdentifier,
+ objectPermissions,
+ fieldPermissions,
+ } = roleManifest;
+
+ return {
+ ...roleManifest,
+ ...(isDefined(objectPermissions)
+ ? {
+ objectPermissions: omitDerivedUniversalIdentifiers({
+ permissions: objectPermissions,
+ getDerivedUniversalIdentifier: ({ objectUniversalIdentifier }) =>
+ getObjectPermissionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ roleUniversalIdentifier,
+ objectUniversalIdentifier,
+ }),
+ }),
+ }
+ : {}),
+ ...(isDefined(fieldPermissions)
+ ? {
+ fieldPermissions: omitDerivedUniversalIdentifiers({
+ permissions: fieldPermissions,
+ getDerivedUniversalIdentifier: ({ fieldUniversalIdentifier }) =>
+ getFieldPermissionUniversalIdentifier({
+ applicationUniversalIdentifier,
+ roleUniversalIdentifier,
+ fieldUniversalIdentifier,
+ }),
+ }),
+ }
+ : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/get-navigation-folder-name-for-pull-file.ts b/packages/twenty-cli/src/app/pull/get-navigation-folder-name-for-pull-file.ts
new file mode 100644
index 00000000000..8920d03f6e6
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/get-navigation-folder-name-for-pull-file.ts
@@ -0,0 +1,16 @@
+import { isUsableFileNameSegment } from '@/app/pull/pull-file-base-name';
+import { type Manifest } from 'twenty-shared/application';
+
+export const getNavigationFolderNameForPullFile = ({
+ folderUniversalIdentifier,
+ manifest,
+}: {
+ folderUniversalIdentifier: string;
+ manifest: Manifest;
+}): string | null => {
+ const folderName = manifest.navigationMenuItems?.find(
+ (candidate) => candidate.universalIdentifier === folderUniversalIdentifier,
+ )?.name;
+
+ return isUsableFileNameSegment(folderName) ? folderName : null;
+};
diff --git a/packages/twenty-cli/src/app/pull/get-object-name-for-pull-file.ts b/packages/twenty-cli/src/app/pull/get-object-name-for-pull-file.ts
new file mode 100644
index 00000000000..3cc202acfcf
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/get-object-name-for-pull-file.ts
@@ -0,0 +1,22 @@
+import { type Manifest } from 'twenty-shared/application';
+import { STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/metadata';
+
+const STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER = new Map<string, string>(
+ Object.entries(STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS).map(
+ ([name, universalIdentifier]) => [universalIdentifier, name] as const,
+ ),
+);
+
+export const getObjectNameForPullFile = ({
+ objectUniversalIdentifier,
+ manifest,
+}: {
+ objectUniversalIdentifier: string;
+ manifest: Manifest;
+}): string | null =>
+ (manifest.objects ?? []).find(
+ (objectManifest) =>
+ objectManifest.universalIdentifier === objectUniversalIdentifier,
+ )?.nameSingular ??
+ STANDARD_OBJECT_NAME_BY_UNIVERSAL_IDENTIFIER.get(objectUniversalIdentifier) ??
+ null;
diff --git a/packages/twenty-cli/src/app/pull/get-overwritten-local-changes.ts b/packages/twenty-cli/src/app/pull/get-overwritten-local-changes.ts
new file mode 100644
index 00000000000..1f35a8ca5d7
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/get-overwritten-local-changes.ts
@@ -0,0 +1,88 @@
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { type Manifest } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type PullEntity } from '@/app/pull/build-pull-entities';
+import { hashContent } from '@/utils/hash-content';
+import { type PullDeletion, type PullWrite } from '@/app/pull/plan-pull-writes';
+import { planTranslationWrites } from '@/app/pull/plan-translation-writes';
+import { writeDefineFile } from '@/app/pull/write-define-file';
+
+export const getOverwrittenLocalChanges = async ({
+ appPath,
+ baseManifest,
+ writes,
+ deletions,
+ frontComponentSourcePaths,
+ sourceFingerprints,
+ baseEntities,
+}: {
+ appPath: string;
+ baseManifest: Manifest | null;
+ writes: PullWrite[];
+ deletions: PullDeletion[];
+ frontComponentSourcePaths: string[];
+ sourceFingerprints?: Record<string, string>;
+ baseEntities: PullEntity[];
+}): Promise<PullDeletion[]> => {
+ if (!isDefined(baseManifest)) {
+ return [];
+ }
+
+ const baseContents = new Map(
+ baseEntities.map((entity) => [
+ entity.universalIdentifier,
+ writeDefineFile({
+ definer: entity.definer,
+ config: entity.config,
+ enumBindings: entity.enumBindings,
+ }).content,
+ ]),
+ );
+ const translationPlan = await planTranslationWrites({
+ appPath,
+ manifest: baseManifest,
+ baseManifest: null,
+ frontComponentSourcePaths,
+ });
+ const translationContents = new Map(
+ translationPlan.writes.map((write) => [write.relativePath, write.content]),
+ );
+ const baselineAbsentTranslationPaths = new Set(
+ translationPlan.deletions.map(({ relativePath }) => relativePath),
+ );
+ const overwrittenLocalChanges: PullDeletion[] = [];
+
+ for (const { universalIdentifier, relativePath } of [
+ ...writes.filter((write) => write.isRegeneration),
+ ...deletions,
+ ]) {
+ const sourceFingerprint = sourceFingerprints?.[relativePath];
+
+ if (isDefined(sourceFingerprint)) {
+ if (
+ hashContent(await readFile(join(appPath, relativePath))) !==
+ sourceFingerprint
+ ) {
+ overwrittenLocalChanges.push({ universalIdentifier, relativePath });
+ }
+
+ continue;
+ }
+
+ const baseContent =
+ baseContents.get(universalIdentifier) ??
+ translationContents.get(relativePath);
+
+ if (
+ baselineAbsentTranslationPaths.has(relativePath) ||
+ (isDefined(baseContent) &&
+ (await readFile(join(appPath, relativePath), 'utf8')) !== baseContent)
+ ) {
+ overwrittenLocalChanges.push({ universalIdentifier, relativePath });
+ }
+ }
+
+ return overwrittenLocalChanges;
+};
diff --git a/packages/twenty-cli/src/app/pull/get-page-layout-name-for-pull-file.ts b/packages/twenty-cli/src/app/pull/get-page-layout-name-for-pull-file.ts
new file mode 100644
index 00000000000..36e08ebb669
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/get-page-layout-name-for-pull-file.ts
@@ -0,0 +1,70 @@
+import {
+ getSystemRecordFormPageLayoutUniversalIdentifier,
+ getSystemRecordPageLayoutUniversalIdentifier,
+ type Manifest,
+} from 'twenty-shared/application';
+import { STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+const STANDARD_PAGE_LAYOUT_NAME_BY_UNIVERSAL_IDENTIFIER = new Map<
+ string,
+ string
+>(
+ Object.entries(STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS).map(
+ ([name, { universalIdentifier }]) => [universalIdentifier, name] as const,
+ ),
+);
+
+export const getPageLayoutNameForPullFile = ({
+ pageLayoutUniversalIdentifier,
+ manifest,
+}: {
+ pageLayoutUniversalIdentifier: string;
+ manifest: Manifest;
+}): string | null => {
+ const pageLayoutManifest = manifest.pageLayouts?.find(
+ (candidate) =>
+ candidate.universalIdentifier === pageLayoutUniversalIdentifier,
+ );
+
+ if (isDefined(pageLayoutManifest)) {
+ return pageLayoutManifest.name;
+ }
+
+ const standardPageLayoutName =
+ STANDARD_PAGE_LAYOUT_NAME_BY_UNIVERSAL_IDENTIFIER.get(
+ pageLayoutUniversalIdentifier,
+ );
+
+ if (isDefined(standardPageLayoutName)) {
+ return standardPageLayoutName;
+ }
+
+ const objectMetadataApplicationUniversalIdentifier =
+ manifest.application.universalIdentifier;
+
+ for (const objectManifest of manifest.objects ?? []) {
+ const systemPageLayoutUniversalIdentifiers = {
+ objectMetadataApplicationUniversalIdentifier,
+ objectUniversalIdentifier: objectManifest.universalIdentifier,
+ };
+
+ if (
+ getSystemRecordPageLayoutUniversalIdentifier(
+ systemPageLayoutUniversalIdentifiers,
+ ) === pageLayoutUniversalIdentifier
+ ) {
+ return `${objectManifest.nameSingular}RecordPage`;
+ }
+
+ if (
+ getSystemRecordFormPageLayoutUniversalIdentifier(
+ systemPageLayoutUniversalIdentifiers,
+ ) === pageLayoutUniversalIdentifier
+ ) {
+ return `${objectManifest.nameSingular}RecordForm`;
+ }
+ }
+
+ return null;
+};
diff --git a/packages/twenty-cli/src/app/pull/is-exported-manifest.ts b/packages/twenty-cli/src/app/pull/is-exported-manifest.ts
new file mode 100644
index 00000000000..263b32cc9b2
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/is-exported-manifest.ts
@@ -0,0 +1,45 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { ENTITY_KEY_BY_KIND } from '@/app/pull/entity-key-by-kind.constant';
+import { isLocaleCatalog } from '@/app/translations/is-locale-catalog';
+
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+
+const isEntityCollection = (value: unknown, children: string[] = []): boolean =>
+ !isDefined(value) ||
+ (isArray(value) &&
+ value.every(
+ (entry) =>
+ isPlainObject(entry) &&
+ isString(entry.universalIdentifier) &&
+ children.every((key) =>
+ isEntityCollection(entry[key], key === 'tabs' ? ['widgets'] : []),
+ ),
+ ));
+
+export const isExportedManifest = (value: unknown): value is ExportedManifest =>
+ isPlainObject(value) &&
+ isPlainObject(value.application) &&
+ isString(value.application.universalIdentifier) &&
+ (!isDefined(value.translations) ||
+ (isPlainObject(value.translations) &&
+ Object.values(value.translations).every(isLocaleCatalog))) &&
+ Object.values(ENTITY_KEY_BY_KIND)
+ .filter((key) => key !== 'application')
+ .every((key) =>
+ isEntityCollection(
+ value[key],
+ key === 'objects' || key === 'views'
+ ? ['fields']
+ : key === 'pageLayouts'
+ ? ['tabs']
+ : key === 'pageLayoutTabs'
+ ? ['widgets']
+ : [],
+ ),
+ ) &&
+ (!isArray(value.objects) ||
+ value.objects.every(
+ (entry) => isPlainObject(entry) && isString(entry.nameSingular),
+ ));
diff --git a/packages/twenty-cli/src/app/pull/is-source-fingerprints.ts b/packages/twenty-cli/src/app/pull/is-source-fingerprints.ts
new file mode 100644
index 00000000000..672d26a9b9b
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/is-source-fingerprints.ts
@@ -0,0 +1,13 @@
+import { isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
+
+export const isSourceFingerprints = (
+ value: unknown,
+): value is Record<string, string> =>
+ isPlainObject(value) &&
+ Object.values(value).every(
+ (fingerprint) =>
+ isString(fingerprint) && SHA256_HEX_PATTERN.test(fingerprint),
+ );
diff --git a/packages/twenty-cli/src/app/pull/kebab-case.ts b/packages/twenty-cli/src/app/pull/kebab-case.ts
new file mode 100644
index 00000000000..34ea1ad580c
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/kebab-case.ts
@@ -0,0 +1,9 @@
+export const kebabCase = (input: string): string =>
+ input
+ .replace(/([a-z])([A-Z])/g, '$1-$2')
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
+ .replace(/([a-zA-Z])(\d)/g, '$1-$2')
+ .replace(/(\d)([a-zA-Z])/g, '$1-$2')
+ .replace(/[\s_]+/g, '-')
+ .replace(/[^a-zA-Z0-9-]+/g, '-')
+ .toLowerCase();
diff --git a/packages/twenty-cli/src/app/pull/normalize-pull-target.ts b/packages/twenty-cli/src/app/pull/normalize-pull-target.ts
new file mode 100644
index 00000000000..26b198d438f
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/normalize-pull-target.ts
@@ -0,0 +1,19 @@
+import { isValidUuid } from 'twenty-shared/utils';
+
+import { type PullTarget } from '@/app/types/pull-target.type';
+import { CliError } from '@/output/cli-error';
+import { parseApiUrl } from '@/target/parse-api-url';
+
+export const normalizePullTarget = (target: PullTarget): PullTarget => {
+ if (!isValidUuid(target.workspaceId)) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The pull base requires a workspace UUID.',
+ });
+ }
+
+ return {
+ apiUrl: parseApiUrl({ rawUrl: target.apiUrl, sourceName: 'Pull target' }),
+ workspaceId: target.workspaceId.toLowerCase(),
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/parse-pull-data.ts b/packages/twenty-cli/src/app/pull/parse-pull-data.ts
new file mode 100644
index 00000000000..7197fd96f3b
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/parse-pull-data.ts
@@ -0,0 +1,97 @@
+import { isArray, isBoolean, isNumber, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import {
+ PULL_ENTITY_KINDS,
+ type PullEntityKind,
+ type SkippedPullEntity,
+} from '@/app/pull/build-pull-entities';
+import { type PullDeletion } from '@/app/pull/plan-pull-writes';
+import { type PullAppResult } from '@/app/pull/types';
+
+const isPullEntityKind = (value: unknown): value is PullEntityKind =>
+ isString(value) && PULL_ENTITY_KINDS.some((kind) => kind === value);
+
+const isPath = (value: unknown): value is PullDeletion =>
+ isPlainObject(value) &&
+ isString(value.universalIdentifier) &&
+ isString(value.relativePath);
+
+const isWrite = (value: unknown): value is PullAppResult['writes'][number] =>
+ isPlainObject(value) &&
+ (isPullEntityKind(value.kind) || value.kind === 'translation') &&
+ isBoolean(value.isRegeneration) &&
+ isPath(value);
+
+const isSkipped = (value: unknown): value is SkippedPullEntity =>
+ isPlainObject(value) &&
+ isPullEntityKind(value.kind) &&
+ isString(value.universalIdentifier) &&
+ isString(value.reason);
+
+const isStringMap = (value: unknown): value is Record<string, string> =>
+ isPlainObject(value) && Object.values(value).every(isString);
+
+const isNumberMap = (value: unknown): value is Record<string, number> =>
+ isPlainObject(value) && Object.values(value).every(isNumber);
+
+export const parsePullData = (
+ value: unknown,
+): { data: PullAppResult } | undefined => {
+ if (
+ !isPlainObject(value) ||
+ !isPlainObject(value.application) ||
+ !isString(value.application.universalIdentifier) ||
+ !isString(value.application.displayName) ||
+ !isPlainObject(value.base) ||
+ !isArray(value.writes) ||
+ !value.writes.every(isWrite) ||
+ !isArray(value.deletions) ||
+ !value.deletions.every(isPath) ||
+ !isArray(value.overwrittenLocalChanges) ||
+ !value.overwrittenLocalChanges.every(isPath) ||
+ !isNumber(value.unchangedCount) ||
+ !isArray(value.localOnlyRelativePaths) ||
+ !value.localOnlyRelativePaths.every(isString) ||
+ !isArray(value.unreadableRelativePaths) ||
+ !value.unreadableRelativePaths.every(isString) ||
+ !isArray(value.skipped) ||
+ !value.skipped.every(isSkipped) ||
+ !isNumberMap(value.compiledTranslationEntryCountByLocale) ||
+ !isStringMap(value.entityLabelByUniversalIdentifier)
+ ) {
+ return undefined;
+ }
+
+ const status = value.base.status;
+
+ if (
+ status !== 'used' &&
+ status !== 'missing' &&
+ status !== 'other-target' &&
+ status !== 'unbound' &&
+ status !== 'unreadable'
+ ) {
+ return undefined;
+ }
+
+ return {
+ data: {
+ application: {
+ universalIdentifier: value.application.universalIdentifier,
+ displayName: value.application.displayName,
+ },
+ base: { status },
+ writes: value.writes,
+ deletions: value.deletions,
+ overwrittenLocalChanges: value.overwrittenLocalChanges,
+ unchangedCount: value.unchangedCount,
+ localOnlyRelativePaths: value.localOnlyRelativePaths,
+ unreadableRelativePaths: value.unreadableRelativePaths,
+ skipped: value.skipped,
+ compiledTranslationEntryCountByLocale:
+ value.compiledTranslationEntryCountByLocale,
+ entityLabelByUniversalIdentifier: value.entityLabelByUniversalIdentifier,
+ },
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/plan-pull-writes.ts b/packages/twenty-cli/src/app/pull/plan-pull-writes.ts
new file mode 100644
index 00000000000..61d081b7c37
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/plan-pull-writes.ts
@@ -0,0 +1,292 @@
+import { type ManifestEntityKey } from '@/app/source/extract-define-entity';
+import { collectIdentifiers } from '@/app/pull/collect-identifiers';
+import { ENTITY_KEY_BY_KIND } from '@/app/pull/entity-key-by-kind.constant';
+import {
+ type PullEntity,
+ type PullEntityKind,
+} from '@/app/pull/build-pull-entities';
+import { resolvePullFileNameCollisions } from '@/app/pull/resolve-pull-file-name-collisions';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+import { writeDefineFile } from '@/app/pull/write-define-file';
+import { dirname, posix } from 'node:path';
+import { isDefined } from 'twenty-shared/utils';
+
+export type PullWriteKind = PullEntityKind | 'translation';
+
+export type PullWrite = {
+ kind: PullWriteKind;
+ universalIdentifier: string;
+ relativePath: string;
+ content: string;
+ requiredSdkExports: string[];
+ isRegeneration: boolean;
+};
+
+export type PullDeletion = {
+ universalIdentifier: string;
+ relativePath: string;
+};
+
+export type PullWritePlan = {
+ writes: PullWrite[];
+ unchanged: PullEntity[];
+ deletions: PullDeletion[];
+ localOnlyRelativePaths: string[];
+};
+
+const toReservationKey = (relativePath: string): string =>
+ relativePath.toLowerCase();
+
+const toPosixPath = (value: string): string => value.split('\\').join('/');
+
+const findExistingFolderForKind = ({
+ scannedFiles,
+ entityKey,
+}: {
+ scannedFiles: ScannedSourceFile[];
+ entityKey: ManifestEntityKey;
+}): string | null => {
+ const folderCounts = new Map<string, number>();
+
+ for (const scannedFile of scannedFiles) {
+ if (scannedFile.entityKey !== entityKey) {
+ continue;
+ }
+
+ const folder = toPosixPath(dirname(scannedFile.relativePath));
+
+ folderCounts.set(folder, (folderCounts.get(folder) ?? 0) + 1);
+ }
+
+ const sortedFolders = [...folderCounts.entries()].sort(
+ ([leftFolder, leftCount], [rightFolder, rightCount]) =>
+ rightCount - leftCount || leftFolder.localeCompare(rightFolder),
+ );
+
+ return sortedFolders[0]?.[0] ?? null;
+};
+
+const reserveRelativePath = ({
+ folder,
+ fileBaseName,
+ fileSuffix,
+ universalIdentifier,
+ takenRelativePaths,
+}: {
+ folder: string;
+ fileBaseName: string;
+ fileSuffix: string;
+ universalIdentifier: string;
+ takenRelativePaths: Set<string>;
+}): string => {
+ const identifierPrefix = universalIdentifier.slice(0, 8);
+ const candidates = [
+ fileBaseName,
+ `${identifierPrefix}-${fileBaseName}`,
+ ...Array.from(
+ { length: 100 },
+ (_unused, index) => `${identifierPrefix}-${fileBaseName}-${index + 2}`,
+ ),
+ ];
+
+ for (const candidate of candidates) {
+ const candidatePath = posix.join(folder, `${candidate}${fileSuffix}`);
+
+ if (!takenRelativePaths.has(toReservationKey(candidatePath))) {
+ return candidatePath;
+ }
+ }
+
+ throw new Error(
+ `Could not find a free file name for ${universalIdentifier} in ${folder}`,
+ );
+};
+
+const findExistingSourceFile = ({
+ entity,
+ applicationFile,
+ scannedFileByUniversalIdentifier,
+}: {
+ entity: PullEntity;
+ applicationFile: ScannedSourceFile | undefined;
+ scannedFileByUniversalIdentifier: Map<string, ScannedSourceFile>;
+}): ScannedSourceFile | undefined =>
+ entity.kind === 'application'
+ ? applicationFile
+ : scannedFileByUniversalIdentifier.get(
+ entity.universalIdentifier.toLowerCase(),
+ );
+
+export const planPullWrites = ({
+ entities,
+ baseEntities,
+ scannedFiles,
+ workspaceUniversalIdentifiers,
+ unreconciledUniversalIdentifiers,
+}: {
+ entities: PullEntity[];
+ baseEntities: PullEntity[];
+ scannedFiles: ScannedSourceFile[];
+ workspaceUniversalIdentifiers: ReadonlySet<string>;
+ unreconciledUniversalIdentifiers?: ReadonlySet<string>;
+}): PullWritePlan => {
+ const exportedUniversalIdentifiers = new Set(
+ entities.map((entity) => entity.universalIdentifier.toLowerCase()),
+ );
+ const baseConfigByUniversalIdentifier = new Map(
+ baseEntities.map((entity) => [
+ entity.universalIdentifier,
+ JSON.stringify(entity.config),
+ ]),
+ );
+ const fileBaseNameByUniversalIdentifier =
+ resolvePullFileNameCollisions(entities);
+
+ const scannedFileByUniversalIdentifier = new Map<string, ScannedSourceFile>();
+ const applicationFile = scannedFiles.find(
+ (scannedFile) => scannedFile.entityKey === 'application',
+ );
+
+ for (const scannedFile of scannedFiles) {
+ if (isDefined(scannedFile.universalIdentifier)) {
+ scannedFileByUniversalIdentifier.set(
+ scannedFile.universalIdentifier.toLowerCase(),
+ scannedFile,
+ );
+ }
+ }
+
+ const writes: PullWrite[] = [];
+ const unchanged: PullEntity[] = [];
+ const usedRelativePaths = new Set<string>();
+ const takenRelativePaths = new Set(
+ scannedFiles.map((scannedFile) =>
+ toReservationKey(toPosixPath(scannedFile.relativePath)),
+ ),
+ );
+
+ for (const entity of entities) {
+ const existingSourceFile = findExistingSourceFile({
+ entity,
+ applicationFile,
+ scannedFileByUniversalIdentifier,
+ });
+ const existingPath = isDefined(existingSourceFile)
+ ? toPosixPath(existingSourceFile.relativePath)
+ : undefined;
+
+ const folder =
+ findExistingFolderForKind({
+ scannedFiles,
+ entityKey: ENTITY_KEY_BY_KIND[entity.kind],
+ }) ?? entity.defaultFolder;
+ const fileBaseName =
+ fileBaseNameByUniversalIdentifier.get(entity.universalIdentifier) ??
+ entity.fileBaseName;
+ const relativePath =
+ existingPath ??
+ reserveRelativePath({
+ folder,
+ fileBaseName,
+ fileSuffix: entity.fileSuffix,
+ universalIdentifier: entity.universalIdentifier,
+ takenRelativePaths,
+ });
+
+ usedRelativePaths.add(relativePath);
+ takenRelativePaths.add(toReservationKey(relativePath));
+
+ const baseConfig = baseConfigByUniversalIdentifier.get(
+ entity.universalIdentifier,
+ );
+ const localIdentifiers = new Set<string>();
+ const exportedIdentifiers = new Set<string>();
+
+ collectIdentifiers({
+ value: existingSourceFile?.config,
+ identifiers: localIdentifiers,
+ });
+ collectIdentifiers({
+ value: entity.config,
+ identifiers: exportedIdentifiers,
+ });
+
+ const hasDuplicatedDefinition = [...localIdentifiers].some(
+ (identifier) =>
+ !exportedIdentifiers.has(identifier) &&
+ exportedUniversalIdentifiers.has(identifier),
+ );
+
+ if (
+ isDefined(existingSourceFile) &&
+ existingSourceFile.targetFunctionName === entity.definer &&
+ !hasDuplicatedDefinition &&
+ !unreconciledUniversalIdentifiers?.has(
+ entity.universalIdentifier.toLowerCase(),
+ ) &&
+ isDefined(baseConfig) &&
+ baseConfig === JSON.stringify(entity.config)
+ ) {
+ unchanged.push(entity);
+ continue;
+ }
+
+ writes.push({
+ kind: entity.kind,
+ universalIdentifier: entity.universalIdentifier,
+ relativePath,
+ ...writeDefineFile({
+ definer: entity.definer,
+ config: entity.config,
+ enumBindings: entity.enumBindings,
+ }),
+ isRegeneration: isDefined(existingPath),
+ });
+ }
+
+ const deletions: PullDeletion[] = [];
+
+ for (const baseUniversalIdentifier of baseConfigByUniversalIdentifier.keys()) {
+ if (
+ exportedUniversalIdentifiers.has(baseUniversalIdentifier.toLowerCase())
+ ) {
+ continue;
+ }
+
+ const scannedFile = scannedFileByUniversalIdentifier.get(
+ baseUniversalIdentifier.toLowerCase(),
+ );
+ const relativePath = isDefined(scannedFile)
+ ? toPosixPath(scannedFile.relativePath)
+ : undefined;
+
+ if (!isDefined(relativePath) || usedRelativePaths.has(relativePath)) {
+ continue;
+ }
+
+ deletions.push({
+ universalIdentifier: baseUniversalIdentifier,
+ relativePath,
+ });
+ }
+
+ const localOnlyRelativePaths = scannedFiles
+ .filter(
+ (scannedFile) =>
+ isDefined(scannedFile.universalIdentifier) &&
+ !exportedUniversalIdentifiers.has(
+ scannedFile.universalIdentifier.toLowerCase(),
+ ) &&
+ !baseConfigByUniversalIdentifier.has(scannedFile.universalIdentifier) &&
+ !workspaceUniversalIdentifiers.has(scannedFile.universalIdentifier) &&
+ !usedRelativePaths.has(toPosixPath(scannedFile.relativePath)),
+ )
+ .map((scannedFile) => toPosixPath(scannedFile.relativePath));
+
+ return {
+ writes,
+ unchanged,
+ deletions,
+ localOnlyRelativePaths,
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/plan-translation-writes.ts b/packages/twenty-cli/src/app/pull/plan-translation-writes.ts
new file mode 100644
index 00000000000..caeb3f64298
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/plan-translation-writes.ts
@@ -0,0 +1,253 @@
+import { pathExists } from '@/app/fs-utils';
+import { type PullDeletion, type PullWrite } from '@/app/pull/plan-pull-writes';
+import {
+ type PulledLocaleCatalog,
+ splitPulledTranslations,
+} from '@/app/pull/split-pulled-translations';
+import {
+ COMPILED_LOCALES_DIR,
+ LOCALES_DIR,
+} from '@/app/translations/constants';
+import { isLocaleCatalog } from '@/app/translations/is-locale-catalog';
+import { isSupportedLocale } from '@/app/translations/is-supported-locale';
+import {
+ buildLocaleCatalog,
+ flattenLocaleCatalog,
+ type LocaleCatalogEntry,
+} from '@/app/translations/locale-catalog-format';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { type Manifest } from 'twenty-shared/application';
+import { generateMessageId } from 'twenty-shared/i18n';
+import { isDefined } from 'twenty-shared/utils';
+
+export type TranslationWritePlan = {
+ writes: PullWrite[];
+ deletions: PullDeletion[];
+ compiledEntryCountByLocale: Record<string, number>;
+};
+
+type LocaleFile = {
+ relativePath: string;
+ content: string;
+ isWanted: boolean;
+ existingContent: string | null;
+};
+
+type LocaleCatalogs = Partial<Record<string, Record<string, string>>>;
+
+const isLocaleCatalogs = (value: unknown): value is LocaleCatalogs =>
+ isDefined(value) && typeof value === 'object' && !Array.isArray(value);
+
+const serializeLocaleFile = (value: unknown): string =>
+ `${JSON.stringify(value, null, 2)}\n`;
+
+const parseLocaleFile = (content: string | null): Record<string, unknown> => {
+ if (!isDefined(content)) {
+ return {};
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(content);
+
+ return isDefined(parsed) && typeof parsed === 'object'
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+};
+
+const getEntryKey = ({ message, context }: LocaleCatalogEntry): string =>
+ JSON.stringify([context ?? null, message]);
+
+const promoteDecodedEntries = ({
+ catalog,
+ existingAuthoredContent,
+ existingCompiledContent,
+}: {
+ catalog: PulledLocaleCatalog;
+ existingAuthoredContent: string | null;
+ existingCompiledContent: string | null;
+}): Record<string, string | Record<string, string>> | null => {
+ const authoredMessageIds = new Set(
+ flattenLocaleCatalog(catalog.authored).map((entry) =>
+ generateMessageId(entry.message, entry.context),
+ ),
+ );
+ const promotedMessageIds = new Set(
+ Object.keys(parseLocaleFile(existingCompiledContent)).filter(
+ (messageId) =>
+ !(messageId in catalog.compiled) && authoredMessageIds.has(messageId),
+ ),
+ );
+
+ if (promotedMessageIds.size === 0) {
+ return null;
+ }
+
+ const existingEntries = flattenLocaleCatalog(
+ parseLocaleFile(existingAuthoredContent),
+ );
+ const existingKeys = new Set(existingEntries.map(getEntryKey));
+ const promotedEntries = flattenLocaleCatalog(catalog.authored).filter(
+ (entry) =>
+ promotedMessageIds.has(generateMessageId(entry.message, entry.context)) &&
+ !existingKeys.has(getEntryKey(entry)),
+ );
+
+ return buildLocaleCatalog([...existingEntries, ...promotedEntries]);
+};
+
+const getAuthoredRelativePath = (locale: string): string =>
+ `${LOCALES_DIR}/${locale}.json`;
+
+const getCompiledRelativePath = (locale: string): string =>
+ `${COMPILED_LOCALES_DIR}/${locale}.json`;
+
+const readExistingContent = async (
+ absolutePath: string,
+): Promise<string | null> =>
+ (await pathExists(absolutePath))
+ ? await readFile(absolutePath, 'utf8')
+ : null;
+
+export const planTranslationWrites = async ({
+ appPath,
+ manifest,
+ baseManifest,
+ frontComponentSourcePaths,
+}: {
+ appPath: string;
+ manifest: Manifest;
+ baseManifest: Manifest | null;
+ frontComponentSourcePaths: string[];
+}): Promise<TranslationWritePlan> => {
+ const writes: PullWrite[] = [];
+ const deletions: PullDeletion[] = [];
+ const compiledEntryCountByLocale: Record<string, number> = {};
+ const exportedTranslations = manifest.translations;
+
+ if (!isLocaleCatalogs(exportedTranslations)) {
+ return { writes, deletions, compiledEntryCountByLocale };
+ }
+
+ const catalogs = await splitPulledTranslations({
+ manifest,
+ frontComponentSourcePaths,
+ });
+ const exportedLocales = new Set(Object.keys(exportedTranslations));
+ const baseTranslations: LocaleCatalogs = isLocaleCatalogs(
+ baseManifest?.translations,
+ )
+ ? baseManifest.translations
+ : {};
+ const currentTranslations: LocaleCatalogs = exportedTranslations;
+
+ for (const catalog of catalogs) {
+ const { locale, authored, compiled } = catalog;
+ const compiledEntryCount = Object.keys(compiled).length;
+
+ if (compiledEntryCount > 0) {
+ compiledEntryCountByLocale[locale] = compiledEntryCount;
+ }
+
+ const authoredRelativePath = getAuthoredRelativePath(locale);
+ const compiledRelativePath = getCompiledRelativePath(locale);
+ const existingAuthoredContent = await readExistingContent(
+ join(appPath, authoredRelativePath),
+ );
+ const existingCompiledContent = await readExistingContent(
+ join(appPath, compiledRelativePath),
+ );
+ const catalogUnchangedSinceBase =
+ locale in baseTranslations &&
+ JSON.stringify(baseTranslations[locale]) ===
+ JSON.stringify(currentTranslations[locale]);
+ const everyWantedFileExists =
+ (Object.keys(authored).length === 0 ||
+ isDefined(existingAuthoredContent)) &&
+ (compiledEntryCount === 0 || isDefined(existingCompiledContent));
+ const promotedAuthored =
+ catalogUnchangedSinceBase && everyWantedFileExists
+ ? promoteDecodedEntries({
+ catalog,
+ existingAuthoredContent,
+ existingCompiledContent,
+ })
+ : null;
+
+ if (
+ catalogUnchangedSinceBase &&
+ everyWantedFileExists &&
+ !isDefined(promotedAuthored)
+ ) {
+ continue;
+ }
+
+ const localeFiles: LocaleFile[] = [
+ {
+ relativePath: authoredRelativePath,
+ content: serializeLocaleFile(promotedAuthored ?? authored),
+ isWanted: Object.keys(promotedAuthored ?? authored).length > 0,
+ existingContent: existingAuthoredContent,
+ },
+ {
+ relativePath: compiledRelativePath,
+ content: serializeLocaleFile(compiled),
+ isWanted: compiledEntryCount > 0,
+ existingContent: existingCompiledContent,
+ },
+ ];
+
+ for (const {
+ relativePath,
+ content,
+ isWanted,
+ existingContent,
+ } of localeFiles) {
+ const exists = isDefined(existingContent);
+
+ if (!isWanted) {
+ if (exists && relativePath === compiledRelativePath) {
+ deletions.push({ universalIdentifier: locale, relativePath });
+ }
+ continue;
+ }
+
+ if (existingContent === content) {
+ continue;
+ }
+
+ writes.push({
+ kind: 'translation',
+ requiredSdkExports: [],
+ universalIdentifier: locale,
+ relativePath,
+ content,
+ isRegeneration: exists,
+ });
+ }
+ }
+
+ for (const [locale, baseCatalog] of Object.entries(baseTranslations)) {
+ if (
+ exportedLocales.has(locale) ||
+ !isSupportedLocale(locale) ||
+ !isLocaleCatalog(baseCatalog)
+ ) {
+ continue;
+ }
+
+ for (const relativePath of [
+ getAuthoredRelativePath(locale),
+ getCompiledRelativePath(locale),
+ ]) {
+ if (await pathExists(join(appPath, relativePath))) {
+ deletions.push({ universalIdentifier: locale, relativePath });
+ }
+ }
+ }
+
+ return { writes, deletions, compiledEntryCountByLocale };
+};
diff --git a/packages/twenty-cli/src/app/pull/prepare-app-pull.ts b/packages/twenty-cli/src/app/pull/prepare-app-pull.ts
new file mode 100644
index 00000000000..ffee2ab896c
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/prepare-app-pull.ts
@@ -0,0 +1,51 @@
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';
+import { assertPullPaths } from '@/app/pull/assert-pull-paths';
+import { normalizePullTarget } from '@/app/pull/normalize-pull-target';
+import { type PullAppOptions } from '@/app/pull/types';
+import { readApplicationIdentity } from '@/app/source/read-application-identity';
+
+export const prepareAppPull = async ({
+ appPath,
+ applicationExport,
+ target,
+ signal,
+}: PullAppOptions) => {
+ signal.throwIfAborted();
+
+ const normalizedTarget = normalizePullTarget(target);
+
+ await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });
+
+ const packageJson: unknown = JSON.parse(
+ await readFile(join(appPath, 'package.json'), 'utf8'),
+ );
+
+ if (!isPlainObject(packageJson)) {
+ throw new Error('Pull requires a project with a package.json object.');
+ }
+
+ if (applicationExport.files.length > 0) {
+ throw new Error(
+ 'This CLI cannot reconcile exported source or dependency files.',
+ );
+ }
+
+ const identity = await readApplicationIdentity({ appPath, signal });
+
+ if (
+ isDefined(identity.application) &&
+ identity.application.universalIdentifier.toLowerCase() !==
+ applicationExport.application.universalIdentifier.toLowerCase()
+ ) {
+ throw new Error(
+ `This project declares application ${identity.application.universalIdentifier}, but the export belongs to ${applicationExport.application.universalIdentifier}. Pull it into a different directory.`,
+ );
+ }
+ signal.throwIfAborted();
+
+ return { applicationExport, target: normalizedTarget };
+};
diff --git a/packages/twenty-cli/src/app/pull/prepare-pull-entities.ts b/packages/twenty-cli/src/app/pull/prepare-pull-entities.ts
new file mode 100644
index 00000000000..45ee1a4fe07
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/prepare-pull-entities.ts
@@ -0,0 +1,43 @@
+import { type Manifest } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildPullBaseEntities } from '@/app/pull/build-pull-base-entities';
+import { buildPullEntities } from '@/app/pull/build-pull-entities';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+
+export const preparePullEntities = ({
+ manifest,
+ baseManifest,
+ scannedFiles,
+ unreconciledUniversalIdentifiers,
+}: {
+ manifest: Manifest;
+ baseManifest: Manifest | null;
+ scannedFiles: ScannedSourceFile[];
+ unreconciledUniversalIdentifiers?: ReadonlySet<string>;
+}) => {
+ const sourceFileByUniversalIdentifier = new Map<string, ScannedSourceFile>();
+
+ for (const file of scannedFiles) {
+ if (file.isReadable && isDefined(file.universalIdentifier)) {
+ sourceFileByUniversalIdentifier.set(
+ file.universalIdentifier.toLowerCase(),
+ file,
+ );
+ }
+ }
+
+ const { entities, skipped } = buildPullEntities(
+ manifest,
+ sourceFileByUniversalIdentifier,
+ );
+ const baseEntities = buildPullBaseEntities({
+ entities: isDefined(baseManifest)
+ ? buildPullEntities(baseManifest, sourceFileByUniversalIdentifier)
+ .entities
+ : [],
+ unreconciledUniversalIdentifiers,
+ });
+
+ return { entities, baseEntities, skipped };
+};
diff --git a/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts b/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts
new file mode 100644
index 00000000000..6a2f33c8208
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts
@@ -0,0 +1,142 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { collectIdentifiers } from '@/app/pull/collect-identifiers';
+import {
+ type PullEntity,
+ type SkippedPullEntity,
+} from '@/app/pull/build-pull-entities';
+import { type PullWrite, type PullDeletion } from '@/app/pull/plan-pull-writes';
+import { type ScannedSourceFile } from '@/app/source/scan-project-source-files';
+
+export const preserveNestedPullEntities = ({
+ entities,
+ baseEntities,
+ protectedIdentifiers,
+ writes,
+ deletions,
+ scannedFiles,
+}: {
+ entities: PullEntity[];
+ baseEntities: PullEntity[];
+ protectedIdentifiers: ReadonlySet<string>;
+ writes: PullWrite[];
+ deletions: PullDeletion[];
+ scannedFiles: ScannedSourceFile[];
+}): {
+ writes: PullWrite[];
+ deletions: PullDeletion[];
+ skipped: SkippedPullEntity[];
+} => {
+ const baseIdentifiers = new Set<string>();
+
+ collectIdentifiers({ value: baseEntities, identifiers: baseIdentifiers });
+
+ const localIdentifiersByPath = new Map(
+ scannedFiles.map((file) => {
+ const identifiers = new Set<string>();
+
+ collectIdentifiers({ value: file.config, identifiers });
+
+ return [file.relativePath.split('\\').join('/'), identifiers];
+ }),
+ );
+ const exportedConfigByIdentifier = new Map(
+ entities.map((entity) => [
+ entity.universalIdentifier.toLowerCase(),
+ entity.config,
+ ]),
+ );
+ const baseEntityByIdentifier = new Map(
+ baseEntities.map((entity) => [
+ entity.universalIdentifier.toLowerCase(),
+ entity,
+ ]),
+ );
+ const changes = [
+ ...writes.filter(
+ (write) => write.kind !== 'translation' && write.isRegeneration,
+ ),
+ ...deletions.flatMap((deletion) => {
+ const entity = baseEntityByIdentifier.get(
+ deletion.universalIdentifier.toLowerCase(),
+ );
+
+ return isDefined(entity) ? [{ ...deletion, kind: entity.kind }] : [];
+ }),
+ ];
+ const skipped: SkippedPullEntity[] = [];
+ const skippedPaths = new Set<string>();
+
+ let previousSkippedCount: number;
+
+ do {
+ previousSkippedCount = skippedPaths.size;
+ const retainedIdentifiersByPath = new Map(localIdentifiersByPath);
+
+ for (const write of writes) {
+ if (
+ write.kind === 'translation' ||
+ skippedPaths.has(write.relativePath)
+ ) {
+ continue;
+ }
+
+ const identifiers = new Set<string>();
+
+ collectIdentifiers({
+ value: exportedConfigByIdentifier.get(
+ write.universalIdentifier.toLowerCase(),
+ ),
+ identifiers,
+ });
+ retainedIdentifiersByPath.set(write.relativePath, identifiers);
+ }
+
+ for (const deletion of deletions) {
+ if (!skippedPaths.has(deletion.relativePath)) {
+ retainedIdentifiersByPath.delete(deletion.relativePath);
+ }
+ }
+
+ const retainedIdentifiers = new Set(
+ [...retainedIdentifiersByPath.values()].flatMap((identifiers) => [
+ ...identifiers,
+ ]),
+ );
+
+ for (const change of changes) {
+ if (
+ skippedPaths.has(change.relativePath) ||
+ change.kind === 'translation'
+ ) {
+ continue;
+ }
+
+ const omittedIdentifier = [
+ ...(localIdentifiersByPath.get(change.relativePath) ?? []),
+ ].find(
+ (identifier) =>
+ !retainedIdentifiers.has(identifier) &&
+ (protectedIdentifiers.has(identifier) ||
+ !baseIdentifiers.has(identifier)),
+ );
+
+ if (isDefined(omittedIdentifier)) {
+ skippedPaths.add(change.relativePath);
+ skipped.push({
+ kind: change.kind,
+ universalIdentifier: change.universalIdentifier,
+ reason: `preserving ${change.relativePath}, replacement would remove nested local definition ${omittedIdentifier} without a confirmed remote deletion`,
+ });
+ }
+ }
+ } while (skippedPaths.size !== previousSkippedCount);
+
+ return {
+ writes: writes.filter((write) => !skippedPaths.has(write.relativePath)),
+ deletions: deletions.filter(
+ (deletion) => !skippedPaths.has(deletion.relativePath),
+ ),
+ skipped,
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/print-typescript-value.ts b/packages/twenty-cli/src/app/pull/print-typescript-value.ts
new file mode 100644
index 00000000000..eb31e497a44
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/print-typescript-value.ts
@@ -0,0 +1,102 @@
+import { isDefined } from 'twenty-shared/utils';
+
+const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
+
+const PROTOTYPE_KEY = '__proto__';
+
+export type EnumSymbolResolver = (params: {
+ path: string[];
+ value: string;
+}) => string | undefined;
+
+const printString = (value: string): string =>
+ `'${value
+ .replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(/\n/g, '\\n')
+ .replace(/\r/g, '\\r')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029')
+ .replace(
+ /[\uD800-\uDFFF]/g,
+ (character) =>
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,
+ )}'`;
+
+const printKey = (key: string): string => {
+ if (key === PROTOTYPE_KEY) {
+ return `[${printString(key)}]`;
+ }
+
+ return IDENTIFIER_PATTERN.test(key) ? key : printString(key);
+};
+
+const indentOf = (depth: number): string => ' '.repeat(depth);
+
+export const printTypescriptValue = ({
+ value,
+ depth = 0,
+ path = [],
+ resolveEnumSymbol,
+}: {
+ value: unknown;
+ depth?: number;
+ path?: string[];
+ resolveEnumSymbol?: EnumSymbolResolver;
+}): string => {
+ if (value === null) {
+ return 'null';
+ }
+
+ if (typeof value === 'string') {
+ const enumSymbol = resolveEnumSymbol?.({ path, value });
+
+ return isDefined(enumSymbol) ? enumSymbol : printString(value);
+ }
+
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value);
+ }
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ return '[]';
+ }
+
+ const items = value.map(
+ (item) =>
+ `${indentOf(depth + 1)}${printTypescriptValue({
+ value: item,
+ depth: depth + 1,
+ path: [...path, '[]'],
+ resolveEnumSymbol,
+ })},`,
+ );
+
+ return `[\n${items.join('\n')}\n${indentOf(depth)}]`;
+ }
+
+ if (typeof value === 'object') {
+ const entries = Object.entries(value as Record<string, unknown>).filter(
+ ([, entryValue]) => entryValue !== undefined,
+ );
+
+ if (entries.length === 0) {
+ return '{}';
+ }
+
+ const properties = entries.map(
+ ([key, entryValue]) =>
+ `${indentOf(depth + 1)}${printKey(key)}: ${printTypescriptValue({
+ value: entryValue,
+ depth: depth + 1,
+ path: [...path, key],
+ resolveEnumSymbol,
+ })},`,
+ );
+
+ return `{\n${properties.join('\n')}\n${indentOf(depth)}}`;
+ }
+
+ return 'null';
+};
diff --git a/packages/twenty-cli/src/app/pull/pull-application.ts b/packages/twenty-cli/src/app/pull/pull-application.ts
new file mode 100644
index 00000000000..1b1ac4b4b01
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/pull-application.ts
@@ -0,0 +1,205 @@
+import { join } from 'node:path';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import { assertPullPaths } from '@/app/pull/assert-pull-paths';
+import { collectIdentifiers } from '@/app/pull/collect-identifiers';
+import { getOverwrittenLocalChanges } from '@/app/pull/get-overwritten-local-changes';
+import { prepareAppPull } from '@/app/pull/prepare-app-pull';
+import { preparePullEntities } from '@/app/pull/prepare-pull-entities';
+import { preserveNestedPullEntities } from '@/app/pull/preserve-nested-pull-entities';
+import { reconcilePullBaseManifest } from '@/app/pull/reconcile-pull-base-manifest';
+import { createPullBaseWrite } from '@/app/pull/create-pull-base-write';
+import { readTargetBoundPullBase } from '@/app/pull/read-target-bound-pull-base';
+import { type PullAppOptions, type PullAppResult } from '@/app/pull/types';
+import { type ToolingResult } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+import { toPullManifest } from '@/app/pull/to-pull-manifest';
+import { assertPullSdkExports } from '@/app/pull/assert-pull-sdk-exports';
+import { applyPullWrites } from '@/app/pull/apply-pull-writes';
+import { buildManifestEntityLabelByUniversalIdentifier } from '@/app/pull/build-manifest-entity-label-by-universal-identifier';
+import { planPullWrites } from '@/app/pull/plan-pull-writes';
+import { planTranslationWrites } from '@/app/pull/plan-translation-writes';
+import { scanProjectSourceFiles } from '@/app/source/scan-project-source-files';
+import { updateSourceFingerprints } from '@/app/pull/update-source-fingerprints';
+
+export const pullApplication = async (
+ options: PullAppOptions,
+): Promise<ToolingResult<PullAppResult>> => {
+ const { appPath, signal } = options;
+ try {
+ const { applicationExport, target } = await prepareAppPull(options);
+ const manifest = toPullManifest(applicationExport.manifest);
+ const base = await readTargetBoundPullBase({
+ appPath,
+ target,
+ applicationUniversalIdentifier:
+ applicationExport.application.universalIdentifier,
+ });
+ const baseManifest = isDefined(base.manifest)
+ ? toPullManifest(base.manifest)
+ : null;
+ const scannedFiles = await scanProjectSourceFiles({
+ appPath,
+ includeConfig: true,
+ signal,
+ });
+ const unreconciledBaseIdentifiers = new Set(
+ base.unreconciledUniversalIdentifiers,
+ );
+ const {
+ entities,
+ baseEntities,
+ skipped: skippedEntities,
+ } = preparePullEntities({
+ manifest,
+ baseManifest,
+ scannedFiles,
+ unreconciledUniversalIdentifiers: unreconciledBaseIdentifiers,
+ });
+
+ signal?.throwIfAborted();
+
+ const workspaceUniversalIdentifiers = new Set(
+ applicationExport.coverage.map((entry) => entry.universalIdentifier),
+ );
+ const plan = planPullWrites({
+ entities,
+ baseEntities,
+ scannedFiles,
+ workspaceUniversalIdentifiers,
+ unreconciledUniversalIdentifiers: unreconciledBaseIdentifiers,
+ });
+ const protectedIdentifiers = new Set<string>();
+
+ collectIdentifiers({ value: manifest, identifiers: protectedIdentifiers });
+ collectIdentifiers({
+ value: applicationExport.coverage,
+ identifiers: protectedIdentifiers,
+ });
+
+ const frontComponentSourcePaths = scannedFiles
+ .filter((file) => file.entityKey === 'frontComponents')
+ .map((file) => join(appPath, file.relativePath));
+ const translationPlan = await planTranslationWrites({
+ appPath,
+ manifest,
+ baseManifest,
+ frontComponentSourcePaths,
+ });
+ const safePlan = preserveNestedPullEntities({
+ entities,
+ baseEntities,
+ protectedIdentifiers,
+ writes: plan.writes,
+ deletions: plan.deletions.filter(
+ (deletion) =>
+ !protectedIdentifiers.has(deletion.universalIdentifier.toLowerCase()),
+ ),
+ scannedFiles,
+ });
+ const writes = [...safePlan.writes, ...translationPlan.writes];
+ const deletions = [
+ ...safePlan.deletions,
+ ...translationPlan.deletions.filter(
+ (deletion) =>
+ isDefined(baseManifest?.translations) &&
+ deletion.universalIdentifier in baseManifest.translations,
+ ),
+ ];
+ const skipped = [...skippedEntities, ...safePlan.skipped];
+ const unreconciledUniversalIdentifiers = new Set(
+ skipped.map((entry) => entry.universalIdentifier.toLowerCase()),
+ );
+ const finalWrite = createPullBaseWrite({
+ target,
+ manifest: reconcilePullBaseManifest({
+ manifest: applicationExport.manifest,
+ baseManifest: base.manifest,
+ unreconciledUniversalIdentifiers,
+ protectedIdentifiers,
+ }),
+ unreconciledUniversalIdentifiers: [...unreconciledUniversalIdentifiers],
+ sourceFingerprints: updateSourceFingerprints({
+ sourceFingerprints: base.sourceFingerprints,
+ writes,
+ deletions,
+ }),
+ });
+
+ await assertPullPaths({
+ appPath,
+ relativePaths: [
+ ...writes.map((write) => write.relativePath),
+ ...deletions.map((deletion) => deletion.relativePath),
+ finalWrite.relativePath,
+ ],
+ });
+
+ const overwrittenLocalChanges = await getOverwrittenLocalChanges({
+ appPath,
+ baseManifest,
+ writes,
+ deletions,
+ frontComponentSourcePaths,
+ baseEntities,
+ sourceFingerprints: base.sourceFingerprints,
+ });
+ const entityLabelByUniversalIdentifier =
+ buildManifestEntityLabelByUniversalIdentifier(manifest);
+
+ assertPullSdkExports({ appPath, writes });
+ signal?.throwIfAborted();
+ await applyPullWrites({ appPath, writes, deletions, finalWrite, signal });
+
+ return {
+ success: true,
+ data: {
+ application: {
+ universalIdentifier:
+ applicationExport.application.universalIdentifier,
+ displayName: applicationExport.application.displayName,
+ },
+ base: { status: base.status },
+ writes: writes.map(
+ ({
+ content: _content,
+ requiredSdkExports: _requiredSdkExports,
+ ...write
+ }) => write,
+ ),
+ deletions,
+ overwrittenLocalChanges,
+ unchangedCount: plan.unchanged.length,
+ localOnlyRelativePaths: plan.localOnlyRelativePaths,
+ unreadableRelativePaths: scannedFiles
+ .filter((file) => !file.isReadable)
+ .map((file) => file.relativePath),
+ skipped,
+ compiledTranslationEntryCountByLocale:
+ translationPlan.compiledEntryCountByLocale,
+ entityLabelByUniversalIdentifier,
+ },
+ diagnostics: [],
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code:
+ signal?.aborted && Object.is(error, signal.reason)
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'PULL_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ details: {
+ outcome: 'unchanged',
+ ...(error instanceof CliError ? error.details : {}),
+ },
+ },
+ diagnostics: [],
+ };
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/pull-file-base-name.ts b/packages/twenty-cli/src/app/pull/pull-file-base-name.ts
new file mode 100644
index 00000000000..633b934b50e
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/pull-file-base-name.ts
@@ -0,0 +1,101 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { kebabCase } from '@/app/pull/kebab-case';
+import {
+ type IndexManifest,
+ type StandaloneViewFieldManifest,
+} from 'twenty-shared/application';
+import { STANDARD_OBJECT_FIELDS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+export type FieldLocation = {
+ objectName: string | null;
+ fieldName: string;
+};
+
+const MAX_FILE_BASE_NAME_LENGTH = 80;
+
+const STANDARD_FIELD_LOCATION_BY_UNIVERSAL_IDENTIFIER = new Map<
+ string,
+ FieldLocation
+>(
+ Object.entries(STANDARD_OBJECT_FIELDS).flatMap(([objectName, fields]) =>
+ Object.entries(fields).map(
+ ([fieldName, { universalIdentifier }]) =>
+ [universalIdentifier, { objectName, fieldName }] as const,
+ ),
+ ),
+);
+
+export const isUsableFileNameSegment = (
+ value: string | undefined,
+): value is string =>
+ isNonEmptyString(value) &&
+ isNonEmptyString(kebabCase(value).replace(/-+/g, ''));
+
+export const capFileBaseName = (fileBaseName: string): string =>
+ fileBaseName.slice(0, MAX_FILE_BASE_NAME_LENGTH).replace(/-+$/g, '');
+
+export const toFileBaseName = ({
+ segments,
+ universalIdentifier,
+}: {
+ segments: (string | null)[];
+ universalIdentifier: string;
+}): string => {
+ const fileBaseName = capFileBaseName(
+ segments
+ .filter(isDefined)
+ .map(kebabCase)
+ .join('-')
+ .replace(/-{2,}/g, '-')
+ .replace(/^-+|-+$/g, ''),
+ );
+
+ return isNonEmptyString(fileBaseName)
+ ? fileBaseName
+ : universalIdentifier.slice(0, 8);
+};
+
+export const buildIndexFileBaseName = ({
+ indexManifest,
+ objectName,
+ fieldLocationByUniversalIdentifier,
+}: {
+ indexManifest: IndexManifest;
+ objectName: string | null;
+ fieldLocationByUniversalIdentifier: Map<string, FieldLocation>;
+}): string =>
+ toFileBaseName({
+ segments: [
+ objectName,
+ ...indexManifest.fields.map(
+ ({ fieldUniversalIdentifier }) =>
+ fieldLocationByUniversalIdentifier.get(fieldUniversalIdentifier)
+ ?.fieldName ?? null,
+ ),
+ ],
+ universalIdentifier: indexManifest.universalIdentifier,
+ });
+
+export const buildViewFieldFileBaseName = ({
+ viewFieldManifest,
+ fieldLocationByUniversalIdentifier,
+}: {
+ viewFieldManifest: StandaloneViewFieldManifest;
+ fieldLocationByUniversalIdentifier: Map<string, FieldLocation>;
+}): string => {
+ const fieldLocation =
+ fieldLocationByUniversalIdentifier.get(
+ viewFieldManifest.fieldMetadataUniversalIdentifier,
+ ) ??
+ STANDARD_FIELD_LOCATION_BY_UNIVERSAL_IDENTIFIER.get(
+ viewFieldManifest.fieldMetadataUniversalIdentifier,
+ );
+
+ return toFileBaseName({
+ segments: isDefined(fieldLocation)
+ ? [fieldLocation.objectName, fieldLocation.fieldName]
+ : [],
+ universalIdentifier: viewFieldManifest.universalIdentifier,
+ });
+};
diff --git a/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts b/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts
new file mode 100644
index 00000000000..3d27a80e1b5
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts
@@ -0,0 +1,95 @@
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { isArray, isString } from '@sniptt/guards';
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';
+import { assertPullPaths } from '@/app/pull/assert-pull-paths';
+import { normalizePullTarget } from '@/app/pull/normalize-pull-target';
+import { isExportedManifest } from '@/app/pull/is-exported-manifest';
+import { isSourceFingerprints } from '@/app/pull/is-source-fingerprints';
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+import { type PullTarget } from '@/app/types/pull-target.type';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+export const readTargetBoundPullBase = async ({
+ appPath,
+ target,
+ applicationUniversalIdentifier,
+}: {
+ appPath: string;
+ target: PullTarget;
+ applicationUniversalIdentifier: string;
+}): Promise<{
+ status: 'used' | 'missing' | 'other-target' | 'unbound' | 'unreadable';
+ manifest: ExportedManifest | null;
+ unreconciledUniversalIdentifiers?: string[];
+ sourceFingerprints?: Record<string, string>;
+}> => {
+ await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });
+
+ const normalizedTarget = normalizePullTarget(target);
+
+ try {
+ const base: unknown = JSON.parse(
+ await readFile(join(appPath, PULL_BASE_FILE_PATH), 'utf8'),
+ );
+
+ if (isPlainObject(base) && base.version === 1) {
+ return { status: 'unbound', manifest: null };
+ }
+
+ if (
+ !isPlainObject(base) ||
+ base.version !== 2 ||
+ !isPlainObject(base.target) ||
+ !isString(base.target.apiUrl) ||
+ !isString(base.target.workspaceId) ||
+ !isString(base.applicationUniversalIdentifier) ||
+ !isExportedManifest(base.manifest) ||
+ base.applicationUniversalIdentifier.toLowerCase() !==
+ base.manifest.application.universalIdentifier.toLowerCase() ||
+ (isDefined(base.unreconciledUniversalIdentifiers) &&
+ (!isArray(base.unreconciledUniversalIdentifiers) ||
+ !base.unreconciledUniversalIdentifiers.every(
+ (identifier) =>
+ isString(identifier) && isValidUniversalIdentifier(identifier),
+ ))) ||
+ (isDefined(base.sourceFingerprints) &&
+ !isSourceFingerprints(base.sourceFingerprints))
+ ) {
+ return { status: 'unreadable', manifest: null };
+ }
+
+ const baseTarget = normalizePullTarget({
+ apiUrl: base.target.apiUrl,
+ workspaceId: base.target.workspaceId,
+ });
+
+ if (
+ baseTarget.apiUrl !== normalizedTarget.apiUrl ||
+ baseTarget.workspaceId !== normalizedTarget.workspaceId ||
+ base.applicationUniversalIdentifier.toLowerCase() !==
+ applicationUniversalIdentifier.toLowerCase()
+ ) {
+ return { status: 'other-target', manifest: null };
+ }
+
+ return {
+ status: 'used',
+ manifest: base.manifest,
+ unreconciledUniversalIdentifiers: base.unreconciledUniversalIdentifiers
+ ?.filter(isString)
+ .map((identifier) => identifier.toLowerCase()),
+ sourceFingerprints: isSourceFingerprints(base.sourceFingerprints)
+ ? base.sourceFingerprints
+ : undefined,
+ };
+ } catch (error) {
+ return {
+ status: hasErrorCode(error, 'ENOENT') ? 'missing' : 'unreadable',
+ manifest: null,
+ };
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/reconcile-pull-base-manifest.ts b/packages/twenty-cli/src/app/pull/reconcile-pull-base-manifest.ts
new file mode 100644
index 00000000000..1fc35d672a1
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/reconcile-pull-base-manifest.ts
@@ -0,0 +1,112 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+
+export const reconcilePullBaseManifest = ({
+ manifest,
+ baseManifest,
+ unreconciledUniversalIdentifiers,
+ protectedIdentifiers,
+}: {
+ manifest: ExportedManifest;
+ baseManifest: ExportedManifest | null;
+ unreconciledUniversalIdentifiers: ReadonlySet<string>;
+ protectedIdentifiers: ReadonlySet<string>;
+}): ExportedManifest => {
+ const getIdentifier = (value: unknown): string | undefined =>
+ isPlainObject(value) && isString(value.universalIdentifier)
+ ? value.universalIdentifier.toLowerCase()
+ : undefined;
+
+ const reconcileEntries = (
+ currentEntries: unknown[],
+ previousEntries: unknown[],
+ ): unknown[] => {
+ const previousEntryByIdentifier = new Map(
+ previousEntries.map((entry) => [getIdentifier(entry), entry]),
+ );
+ const entries = currentEntries
+ .filter((entry) => {
+ const identifier = getIdentifier(entry);
+
+ return (
+ !isDefined(identifier) ||
+ !unreconciledUniversalIdentifiers.has(identifier)
+ );
+ })
+ .map((entry) => {
+ const identifier = getIdentifier(entry);
+ const previousEntry = previousEntryByIdentifier.get(identifier);
+
+ if (
+ !isDefined(identifier) ||
+ !isPlainObject(entry) ||
+ !isPlainObject(previousEntry)
+ ) {
+ return entry;
+ }
+
+ return reconcileCollections(entry, previousEntry);
+ });
+
+ const identifiers = new Set(entries.map(getIdentifier));
+
+ const retainedEntries = previousEntries.filter((entry) => {
+ const identifier = getIdentifier(entry);
+
+ return (
+ isDefined(identifier) &&
+ !identifiers.has(identifier) &&
+ (unreconciledUniversalIdentifiers.has(identifier) ||
+ protectedIdentifiers.has(identifier))
+ );
+ });
+
+ return [...entries, ...retainedEntries];
+ };
+ const reconcileCollections = (
+ current: Record<string, unknown>,
+ previous: Record<string, unknown> | null,
+ ): Record<string, unknown> => {
+ const reconciled = { ...current };
+
+ for (const key of new Set([
+ ...Object.keys(current),
+ ...Object.keys(previous ?? {}),
+ ])) {
+ const currentEntries = current[key];
+ const previousEntries = previous?.[key];
+
+ if (!isArray(currentEntries) && !isArray(previousEntries)) {
+ continue;
+ }
+
+ const entries = reconcileEntries(
+ isArray(currentEntries) ? currentEntries : [],
+ isArray(previousEntries) ? previousEntries : [],
+ );
+
+ if (isArray(currentEntries) || entries.length > 0) {
+ reconciled[key] = entries;
+ }
+ }
+
+ return reconciled;
+ };
+ const reconciled: ExportedManifest = {
+ ...manifest,
+ ...reconcileCollections(manifest, baseManifest),
+ };
+
+ if (
+ isDefined(baseManifest) &&
+ unreconciledUniversalIdentifiers.has(
+ manifest.application.universalIdentifier.toLowerCase(),
+ )
+ ) {
+ reconciled.application = baseManifest.application;
+ }
+
+ return reconciled;
+};
diff --git a/packages/twenty-cli/src/app/pull/resolve-pull-file-name-collisions.ts b/packages/twenty-cli/src/app/pull/resolve-pull-file-name-collisions.ts
new file mode 100644
index 00000000000..c3f79e43ae8
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/resolve-pull-file-name-collisions.ts
@@ -0,0 +1,61 @@
+import { type PullEntity } from '@/app/pull/build-pull-entities';
+import { kebabCase } from '@/app/pull/kebab-case';
+import { capFileBaseName } from '@/app/pull/pull-file-base-name';
+import { isDefined } from 'twenty-shared/utils';
+
+export const resolvePullFileNameCollisions = (
+ entities: PullEntity[],
+): Map<string, string> => {
+ const entitiesByCandidate = new Map<string, PullEntity[]>();
+
+ for (const entity of entities) {
+ const candidate = `${entity.defaultFolder}/${entity.fileBaseName}${entity.fileSuffix}`;
+ const existing = entitiesByCandidate.get(candidate) ?? [];
+
+ existing.push(entity);
+ entitiesByCandidate.set(candidate, existing);
+ }
+
+ const fileBaseNameByUniversalIdentifier = new Map<string, string>();
+
+ for (const collidingEntities of entitiesByCandidate.values()) {
+ if (collidingEntities.length === 1) {
+ fileBaseNameByUniversalIdentifier.set(
+ collidingEntities[0].universalIdentifier,
+ collidingEntities[0].fileBaseName,
+ );
+ continue;
+ }
+
+ const qualifiedNames = collidingEntities.map((entity) =>
+ isDefined(entity.parentName)
+ ? capFileBaseName(
+ `${kebabCase(entity.parentName)}-${entity.fileBaseName}`,
+ )
+ : entity.fileBaseName,
+ );
+
+ const qualifiedNameCounts = new Map<string, number>();
+
+ for (const name of qualifiedNames) {
+ qualifiedNameCounts.set(name, (qualifiedNameCounts.get(name) ?? 0) + 1);
+ }
+
+ collidingEntities.forEach((entity, index) => {
+ const qualifiedName = qualifiedNames[index];
+ const isQualifiedNameUnique =
+ qualifiedNameCounts.get(qualifiedName) === 1;
+
+ fileBaseNameByUniversalIdentifier.set(
+ entity.universalIdentifier,
+ isQualifiedNameUnique
+ ? qualifiedName
+ : capFileBaseName(
+ `${entity.universalIdentifier.slice(0, 8)}-${qualifiedName}`,
+ ),
+ );
+ });
+ }
+
+ return fileBaseNameByUniversalIdentifier;
+};
diff --git a/packages/twenty-cli/src/app/pull/split-pulled-translations.ts b/packages/twenty-cli/src/app/pull/split-pulled-translations.ts
new file mode 100644
index 00000000000..b04f7c35fba
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/split-pulled-translations.ts
@@ -0,0 +1,68 @@
+import { collectFrontComponentStrings } from '@/app/translations/collect-front-component-strings';
+import { collectTranslatableStrings } from '@/app/translations/collect-translatable-strings';
+import {
+ buildLocaleCatalog,
+ type LocaleCatalogEntry,
+} from '@/app/translations/locale-catalog-format';
+import { isLocaleCatalog } from '@/app/translations/is-locale-catalog';
+import { isSupportedLocale } from '@/app/translations/is-supported-locale';
+import { type MessageDescriptor } from '@/app/translations/message';
+import { type Manifest } from 'twenty-shared/application';
+import { generateMessageId } from 'twenty-shared/i18n';
+import { type AppLocale } from 'twenty-shared/translations';
+import { isDefined } from 'twenty-shared/utils';
+
+export type PulledLocaleCatalog = {
+ locale: AppLocale;
+ authored: Record<string, string | Record<string, string>>;
+ compiled: Record<string, string>;
+};
+
+export const splitPulledTranslations = async ({
+ manifest,
+ frontComponentSourcePaths,
+}: {
+ manifest: Manifest;
+ frontComponentSourcePaths: string[];
+}): Promise<PulledLocaleCatalog[]> => {
+ const descriptors: MessageDescriptor[] = [
+ ...collectTranslatableStrings(manifest),
+ ...(await collectFrontComponentStrings(frontComponentSourcePaths)),
+ ];
+ const descriptorByMessageId = new Map(
+ descriptors.map(
+ (descriptor) =>
+ [
+ generateMessageId(descriptor.message, descriptor.context),
+ descriptor,
+ ] as const,
+ ),
+ );
+
+ return Object.entries(manifest.translations ?? {})
+ .filter(
+ (entry): entry is [AppLocale, Record<string, string>] =>
+ isSupportedLocale(entry[0]) && isLocaleCatalog(entry[1]),
+ )
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([locale, messages]) => {
+ const entries: LocaleCatalogEntry[] = [];
+ const compiled: Record<string, string> = {};
+
+ for (const [messageId, translation] of Object.entries(messages)) {
+ const descriptor = descriptorByMessageId.get(messageId);
+
+ if (isDefined(descriptor)) {
+ entries.push({
+ message: descriptor.message,
+ context: descriptor.context,
+ translation,
+ });
+ } else {
+ compiled[messageId] = translation;
+ }
+ }
+
+ return { locale, authored: buildLocaleCatalog(entries), compiled };
+ });
+};
diff --git a/packages/twenty-cli/src/app/pull/strip-graphql-typename.ts b/packages/twenty-cli/src/app/pull/strip-graphql-typename.ts
new file mode 100644
index 00000000000..ee2214ee6e5
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/strip-graphql-typename.ts
@@ -0,0 +1,17 @@
+const GRAPHQL_TYPENAME_KEY = '__typename';
+
+export const stripGraphqlTypename = <TValue>(value: TValue): TValue => {
+ if (Array.isArray(value)) {
+ return value.map(stripGraphqlTypename) as TValue;
+ }
+
+ if (value === null || typeof value !== 'object') {
+ return value;
+ }
+
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([key]) => key !== GRAPHQL_TYPENAME_KEY)
+ .map(([key, entry]) => [key, stripGraphqlTypename(entry)]),
+ ) as TValue;
+};
diff --git a/packages/twenty-cli/src/app/pull/to-pull-manifest.ts b/packages/twenty-cli/src/app/pull/to-pull-manifest.ts
new file mode 100644
index 00000000000..7997a67a160
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/to-pull-manifest.ts
@@ -0,0 +1,5 @@
+import { type Manifest } from 'twenty-shared/application';
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+
+export const toPullManifest = (manifest: ExportedManifest): Manifest =>
+ manifest as Manifest;
diff --git a/packages/twenty-cli/src/app/pull/types.ts b/packages/twenty-cli/src/app/pull/types.ts
new file mode 100644
index 00000000000..697e22e4726
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/types.ts
@@ -0,0 +1,32 @@
+import { type SkippedPullEntity } from '@/app/pull/build-pull-entities';
+import { type PullDeletion, type PullWrite } from '@/app/pull/plan-pull-writes';
+import { type AppExport } from '@/app/types/app-export.type';
+import { type PullTarget } from '@/app/types/pull-target.type';
+
+export type PullAppOptions = {
+ appPath: string;
+ applicationExport: AppExport;
+ target: PullTarget;
+ signal: AbortSignal;
+};
+
+export type PullBaseStatus =
+ | 'used'
+ | 'missing'
+ | 'other-target'
+ | 'unbound'
+ | 'unreadable';
+
+export type PullAppResult = {
+ application: { universalIdentifier: string; displayName: string };
+ base: { status: PullBaseStatus };
+ writes: Omit<PullWrite, 'content' | 'requiredSdkExports'>[];
+ deletions: PullDeletion[];
+ overwrittenLocalChanges: PullDeletion[];
+ unchangedCount: number;
+ localOnlyRelativePaths: string[];
+ unreadableRelativePaths: string[];
+ skipped: SkippedPullEntity[];
+ compiledTranslationEntryCountByLocale: Record<string, number>;
+ entityLabelByUniversalIdentifier: Record<string, string>;
+};
diff --git a/packages/twenty-cli/src/app/pull/update-source-fingerprints.ts b/packages/twenty-cli/src/app/pull/update-source-fingerprints.ts
new file mode 100644
index 00000000000..03cc2ee4989
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/update-source-fingerprints.ts
@@ -0,0 +1,27 @@
+import { hashContent } from '@/utils/hash-content';
+import { type PullDeletion, type PullWrite } from '@/app/pull/plan-pull-writes';
+
+export const updateSourceFingerprints = ({
+ sourceFingerprints = {},
+ writes,
+ deletions,
+}: {
+ sourceFingerprints?: Record<string, string>;
+ writes: Pick<PullWrite, 'relativePath' | 'content'>[];
+ deletions: PullDeletion[];
+}): Record<string, string> => {
+ const deletedRelativePaths = new Set(
+ deletions.map((deletion) => deletion.relativePath),
+ );
+
+ return {
+ ...Object.fromEntries(
+ Object.entries(sourceFingerprints).filter(
+ ([relativePath]) => !deletedRelativePaths.has(relativePath),
+ ),
+ ),
+ ...Object.fromEntries(
+ writes.map((write) => [write.relativePath, hashContent(write.content)]),
+ ),
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/write-define-file.ts b/packages/twenty-cli/src/app/pull/write-define-file.ts
new file mode 100644
index 00000000000..9c8899bc022
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/write-define-file.ts
@@ -0,0 +1,257 @@
+import {
+ type EnumSymbolResolver,
+ printTypescriptValue,
+} from '@/app/pull/print-typescript-value';
+import {
+ AggregateOperations,
+ DateDisplayFormat,
+ FieldMetadataType,
+ IndexType,
+ MetadataWritability,
+ NavigationMenuItemType,
+ NumberDataType,
+ ObjectOpenRecordIn,
+ ObjectRecordGroupByDateGranularity,
+ PageLayoutTabLayoutMode,
+ PageLayoutType,
+ RelationOnDeleteAction,
+ RelationType,
+ RowLevelPermissionPredicateGroupLogicalOperator,
+ RowLevelPermissionPredicateOperand,
+ ViewCalendarLayout,
+ ViewFilterGroupLogicalOperator,
+ ViewFilterOperand,
+ ViewOpenRecordIn,
+ ViewSortDirection,
+ ViewType,
+ ViewVisibility,
+ WidgetType,
+} from 'twenty-shared/types';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+
+const MAX_IMPORT_LINE_LENGTH = 80;
+
+export type EnumBinding = {
+ path: string[];
+ symbol: string;
+ members: Record<string, string>;
+};
+
+const buildFieldEnumBindings = (prefix: string[]): EnumBinding[] => [
+ {
+ path: [...prefix, 'type'],
+ symbol: 'FieldType',
+ members: FieldMetadataType,
+ },
+ {
+ path: [...prefix, 'writability'],
+ symbol: 'MetadataWritability',
+ members: MetadataWritability,
+ },
+ {
+ path: [...prefix, 'universalSettings', 'relationType'],
+ symbol: 'RelationType',
+ members: RelationType,
+ },
+ {
+ path: [...prefix, 'universalSettings', 'onDelete'],
+ symbol: 'OnDeleteAction',
+ members: RelationOnDeleteAction,
+ },
+ {
+ path: [...prefix, 'universalSettings', 'dataType'],
+ symbol: 'NumberDataType',
+ members: NumberDataType,
+ },
+ {
+ path: [...prefix, 'universalSettings', 'displayFormat'],
+ symbol: 'DateDisplayFormat',
+ members: DateDisplayFormat,
+ },
+];
+
+export const FIELD_ENUM_BINDINGS: EnumBinding[] = buildFieldEnumBindings([]);
+
+export const OBJECT_ENUM_BINDINGS: EnumBinding[] = [
+ {
+ path: ['writability'],
+ symbol: 'MetadataWritability',
+ members: MetadataWritability,
+ },
+ {
+ path: ['openRecordIn'],
+ symbol: 'ObjectOpenRecordIn',
+ members: ObjectOpenRecordIn,
+ },
+ ...buildFieldEnumBindings(['fields', '[]']),
+];
+
+export const INDEX_ENUM_BINDINGS: EnumBinding[] = [
+ { path: ['indexType'], symbol: 'IndexType', members: IndexType },
+];
+
+export const ROLE_ENUM_BINDINGS: EnumBinding[] = [
+ {
+ path: ['rowLevelPermissionPredicateGroups', '[]', 'logicalOperator'],
+ symbol: 'RowLevelPermissionPredicateGroupLogicalOperator',
+ members: RowLevelPermissionPredicateGroupLogicalOperator,
+ },
+ {
+ path: ['rowLevelPermissionPredicates', '[]', 'operand'],
+ symbol: 'RowLevelPermissionPredicateOperand',
+ members: RowLevelPermissionPredicateOperand,
+ },
+ {
+ path: ['permissionFlagUniversalIdentifiers', '[]'],
+ symbol: 'SystemPermissionFlag',
+ members: SystemPermissionFlag,
+ },
+];
+
+const buildAggregateOperationBinding = (path: string[]): EnumBinding => ({
+ path,
+ symbol: 'AggregateOperations',
+ members: AggregateOperations,
+});
+
+export const VIEW_FIELD_ENUM_BINDINGS: EnumBinding[] = [
+ buildAggregateOperationBinding(['aggregateOperation']),
+];
+
+export const VIEW_ENUM_BINDINGS: EnumBinding[] = [
+ { path: ['type'], symbol: 'ViewType', members: ViewType },
+ { path: ['visibility'], symbol: 'ViewVisibility', members: ViewVisibility },
+ {
+ path: ['openRecordIn'],
+ symbol: 'ViewOpenRecordIn',
+ members: ViewOpenRecordIn,
+ },
+ buildAggregateOperationBinding(['kanbanAggregateOperation']),
+ {
+ path: ['calendarLayout'],
+ symbol: 'ViewCalendarLayout',
+ members: ViewCalendarLayout,
+ },
+ buildAggregateOperationBinding(['fields', '[]', 'aggregateOperation']),
+ {
+ path: ['filters', '[]', 'operand'],
+ symbol: 'ViewFilterOperand',
+ members: ViewFilterOperand,
+ },
+ {
+ path: ['filterGroups', '[]', 'logicalOperator'],
+ symbol: 'ViewFilterGroupLogicalOperator',
+ members: ViewFilterGroupLogicalOperator,
+ },
+ {
+ path: ['sorts', '[]', 'direction'],
+ symbol: 'ViewSortDirection',
+ members: ViewSortDirection,
+ },
+];
+
+const buildPageLayoutWidgetEnumBindings = (prefix: string[]): EnumBinding[] => [
+ { path: [...prefix, 'type'], symbol: 'WidgetType', members: WidgetType },
+ {
+ path: [...prefix, 'position', 'layoutMode'],
+ symbol: 'PageLayoutTabLayoutMode',
+ members: PageLayoutTabLayoutMode,
+ },
+ buildAggregateOperationBinding([
+ ...prefix,
+ 'configuration',
+ 'aggregateOperation',
+ ]),
+ ...[
+ 'dateGranularity',
+ 'primaryAxisDateGranularity',
+ 'secondaryAxisGroupByDateGranularity',
+ ].map((key) => ({
+ path: [...prefix, 'configuration', key],
+ symbol: 'ObjectRecordGroupByDateGranularity',
+ members: ObjectRecordGroupByDateGranularity,
+ })),
+];
+
+const buildPageLayoutTabEnumBindings = (prefix: string[]): EnumBinding[] => [
+ {
+ path: [...prefix, 'layoutMode'],
+ symbol: 'PageLayoutTabLayoutMode',
+ members: PageLayoutTabLayoutMode,
+ },
+ ...buildPageLayoutWidgetEnumBindings([...prefix, 'widgets', '[]']),
+];
+
+export const PAGE_LAYOUT_WIDGET_ENUM_BINDINGS: EnumBinding[] =
+ buildPageLayoutWidgetEnumBindings([]);
+
+export const PAGE_LAYOUT_TAB_ENUM_BINDINGS: EnumBinding[] =
+ buildPageLayoutTabEnumBindings([]);
+
+export const NAVIGATION_MENU_ITEM_ENUM_BINDINGS: EnumBinding[] = [
+ {
+ path: ['type'],
+ symbol: 'NavigationMenuItemType',
+ members: NavigationMenuItemType,
+ },
+];
+
+export const PAGE_LAYOUT_ENUM_BINDINGS: EnumBinding[] = [
+ { path: ['type'], symbol: 'PageLayoutType', members: PageLayoutType },
+ ...buildPageLayoutTabEnumBindings(['tabs', '[]']),
+];
+
+const isSamePath = (left: string[], right: string[]): boolean =>
+ left.length === right.length &&
+ left.every((segment, index) => segment === right[index]);
+
+export const writeDefineFile = ({
+ definer,
+ config,
+ enumBindings = [],
+}: {
+ definer: string;
+ config: unknown;
+ enumBindings?: EnumBinding[];
+}): { content: string; requiredSdkExports: string[] } => {
+ const usedSymbols = new Set<string>();
+
+ const resolveEnumSymbol: EnumSymbolResolver = ({ path, value }) => {
+ const binding = enumBindings.find((candidate) =>
+ isSamePath(candidate.path, path),
+ );
+
+ if (!isDefined(binding)) {
+ return undefined;
+ }
+
+ const memberName = Object.keys(binding.members).find(
+ (key) => binding.members[key] === value,
+ );
+
+ if (!isDefined(memberName)) {
+ return undefined;
+ }
+
+ usedSymbols.add(binding.symbol);
+
+ return `${binding.symbol}.${memberName}`;
+ };
+
+ const body = printTypescriptValue({ value: config, resolveEnumSymbol });
+ const imported = [definer, ...[...usedSymbols].sort()];
+ const singleLineImport = `import { ${imported.join(', ')} } from 'twenty-sdk/define';`;
+ const importStatement =
+ singleLineImport.length <= MAX_IMPORT_LINE_LENGTH
+ ? singleLineImport
+ : `import {\n${imported.map((name) => ` ${name},`).join('\n')}\n} from 'twenty-sdk/define';`;
+
+ return {
+ content: `${importStatement}
+
+export default ${definer}(${body});
+`,
+ requiredSdkExports: imported,
+ };
+};
diff --git a/packages/twenty-cli/src/app/pull/write-pull-base.ts b/packages/twenty-cli/src/app/pull/write-pull-base.ts
new file mode 100644
index 00000000000..80496336d7a
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/write-pull-base.ts
@@ -0,0 +1,56 @@
+import { randomUUID } from 'node:crypto';
+import { mkdir, open, rename, rm } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+
+import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';
+import { assertPullPaths } from '@/app/pull/assert-pull-paths';
+import { createPullBaseWrite } from '@/app/pull/create-pull-base-write';
+import { type PullTarget } from '@/app/types/pull-target.type';
+import { CliError } from '@/output/cli-error';
+
+export const writePullBase = async ({
+ appPath,
+ manifest,
+ target,
+ sourceFingerprints,
+ signal,
+}: {
+ appPath: string;
+ manifest: ExportedManifest;
+ target: PullTarget;
+ sourceFingerprints?: Record<string, string>;
+ signal: AbortSignal;
+}) => {
+ const basePath = join(appPath, PULL_BASE_FILE_PATH);
+ const temporaryPath = `${basePath}.${randomUUID()}.tmp`;
+ let temporaryFile: Awaited<ReturnType<typeof open>> | undefined;
+
+ try {
+ signal.throwIfAborted();
+ await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });
+ await mkdir(dirname(basePath), { recursive: true });
+ temporaryFile = await open(temporaryPath, 'wx', 0o600);
+ await temporaryFile.writeFile(
+ createPullBaseWrite({ manifest, target, sourceFingerprints }).content,
+ );
+ await temporaryFile.sync();
+ await temporaryFile.close();
+ await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });
+ signal.throwIfAborted();
+ await rename(temporaryPath, basePath);
+ } catch (error) {
+ await temporaryFile?.close().catch(() => undefined);
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
+
+ if (signal.aborted && Object.is(error, signal.reason)) {
+ throw error;
+ }
+
+ throw new CliError({
+ code: 'PULL_BASE_RECORD_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/app/read-app-identity.ts b/packages/twenty-cli/src/app/read-app-identity.ts
new file mode 100644
index 00000000000..54c34a59b0b
--- /dev/null
+++ b/packages/twenty-cli/src/app/read-app-identity.ts
@@ -0,0 +1,94 @@
+import { isNull, isString } from '@sniptt/guards';
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { parseToolingResult } from '@/app/parse-tooling-result';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { runAppWorker } from '@/app/run-app-worker';
+import { type AppSourceIdentity } from '@/app/source/types/app-source-identity.type';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+const parseIdentity = (
+ value: unknown,
+): { data: AppSourceIdentity } | undefined => {
+ if (!isPlainObject(value)) {
+ return undefined;
+ }
+
+ if (isNull(value.application)) {
+ return { data: { application: null } };
+ }
+
+ const application = value.application;
+
+ if (
+ !isPlainObject(application) ||
+ !isString(application.universalIdentifier) ||
+ !isValidUniversalIdentifier(application.universalIdentifier) ||
+ (!isString(application.displayName) && !isNull(application.displayName))
+ ) {
+ return undefined;
+ }
+
+ return {
+ data: {
+ application: {
+ universalIdentifier: application.universalIdentifier,
+ displayName: application.displayName,
+ },
+ },
+ };
+};
+
+export const readAppIdentity = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+}) => {
+ signal.throwIfAborted();
+
+ const sdk = await resolveSourceSdk({ appPath });
+ const worker = await runAppWorker({
+ request: { type: 'readSourceIdentity', appPath },
+ signal,
+ });
+
+ if (signal.aborted) {
+ throw createCancelledError();
+ }
+
+ const result = parseToolingResult({
+ value: worker.result,
+ parseData: parseIdentity,
+ });
+ const diagnostics = [
+ ...result.diagnostics,
+ ...toWorkerOutputDiagnostics(worker.output),
+ ];
+
+ if (!result.success) {
+ throw new CliError({
+ code:
+ result.error.code === 'SDK_SOURCE_UNSUPPORTED'
+ ? 'SDK_SOURCE_UNSUPPORTED'
+ : 'IDENTITY_READ_FAILED',
+ message: result.error.message,
+ hint:
+ result.error.hint ??
+ (result.error.code === 'SDK_SOURCE_UNSUPPORTED'
+ ? 'Use the SDK define functions, rename local helpers with the same names, or install a compatible twenty-sdk version.'
+ : undefined),
+ details: {
+ ...result.error.details,
+ sdkVersion: sdk.version,
+ diagnostics,
+ },
+ });
+ }
+
+ return { ...result.data, diagnostics };
+};
diff --git a/packages/twenty-cli/src/app/read-json-object.ts b/packages/twenty-cli/src/app/read-json-object.ts
new file mode 100644
index 00000000000..6040257b07a
--- /dev/null
+++ b/packages/twenty-cli/src/app/read-json-object.ts
@@ -0,0 +1,13 @@
+import { readFile } from 'node:fs/promises';
+
+import { isPlainObject } from 'twenty-shared/utils';
+
+export const readJsonObject = async (filePath: string) => {
+ try {
+ const value: unknown = JSON.parse(await readFile(filePath, 'utf8'));
+
+ return isPlainObject(value) ? value : undefined;
+ } catch {
+ return undefined;
+ }
+};
diff --git a/packages/twenty-cli/src/app/record-pull-base.ts b/packages/twenty-cli/src/app/record-pull-base.ts
new file mode 100644
index 00000000000..87c86ed1f57
--- /dev/null
+++ b/packages/twenty-cli/src/app/record-pull-base.ts
@@ -0,0 +1,58 @@
+import { fetchAppExport } from '@/app/fetch-app-export';
+import { fetchWorkspaceId } from '@/app/fetch-workspace-id';
+import { writePullBase } from '@/app/pull/write-pull-base';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { createCancelledError } from '@/output/create-cancelled-error';
+import { toCliError } from '@/output/to-cli-error';
+
+export type PullBaseRecording = 'recorded' | 'failed' | 'unsupported';
+
+export const recordPullBase = async ({
+ appPath,
+ universalIdentifier,
+ sourceFingerprints,
+ context: { target, signal, output },
+}: {
+ appPath: string;
+ universalIdentifier: string;
+ sourceFingerprints?: Record<string, string>;
+ context: TargetCommandContext;
+}): Promise<PullBaseRecording> => {
+ output.progress('Recording the pull base…');
+
+ try {
+ const workspaceId = await fetchWorkspaceId({ target, signal });
+ const applicationExport = await fetchAppExport({
+ universalIdentifier,
+ target,
+ signal,
+ });
+
+ await writePullBase({
+ appPath,
+ manifest: applicationExport.manifest,
+ target: { apiUrl: target.apiUrl, workspaceId },
+ sourceFingerprints,
+ signal,
+ });
+
+ return 'recorded';
+ } catch (error) {
+ if (signal.aborted) {
+ throw createCancelledError();
+ }
+
+ const cliError = toCliError(error);
+
+ if (cliError.code === 'APP_EXPORT_UNSUPPORTED') {
+ return 'unsupported';
+ }
+
+ output.warn({
+ code: 'PULL_BASE_NOT_RECORDED',
+ message: `The app was applied, but its pull base was not updated: ${cliError.message} Any previous base was kept. A later pull may report changes from this apply as remote changes.`,
+ });
+
+ return 'failed';
+ }
+};
diff --git a/packages/twenty-cli/src/app/run-app-operation.ts b/packages/twenty-cli/src/app/run-app-operation.ts
new file mode 100644
index 00000000000..ed1cb67f72c
--- /dev/null
+++ b/packages/twenty-cli/src/app/run-app-operation.ts
@@ -0,0 +1,175 @@
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { createToolingFailure } from '@/app/create-tooling-failure';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import {
+ parseBuildData,
+ parseNullData,
+ parseToolingResult,
+} from '@/app/parse-tooling-result';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { runAppWorker } from '@/app/run-app-worker';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import { type AppOperation } from '@/app/types/app-operation.type';
+import { type AppProject } from '@/app/project/types/app-project.type';
+import { type AppWorkerOutput } from '@/app/types/app-worker-output.type';
+import { type ProjectSdk } from '@/app/project/types/project-sdk.type';
+import {
+ type ToolingBuild,
+ type ToolingDiagnostic,
+} from '@/app/types/tooling-result.type';
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+
+type AppOperationResult<TData> = {
+ data: TData;
+ diagnostics: ToolingDiagnostic[];
+};
+
+const PROGRESS_VERBS: Record<AppOperation, string> = {
+ build: 'Building',
+ typecheck: 'Typechecking',
+};
+
+const hasReleaseFailed = ({
+ release,
+ isSnapshotHeld,
+}: {
+ release?: unknown;
+ isSnapshotHeld: boolean;
+}) =>
+ isSnapshotHeld
+ ? !isPlainObject(release) || release.success !== true
+ : isPlainObject(release) && release.success === false;
+
+const runAppOperation = async <TData>({
+ operation,
+ parseData,
+ context: { options, output, outputMode, signal },
+ useHeldBuild,
+}: {
+ operation: AppOperation;
+ parseData: (data: unknown) => { data: TData } | undefined;
+ context: CommandContext;
+ useHeldBuild?: (
+ heldBuild: AppOperationResult<TData> & {
+ project: AppProject;
+ sdk: ProjectSdk;
+ },
+ ) => Promise<void>;
+}) => {
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const sdk = await resolveSourceSdk({
+ appPath: project.path,
+ });
+
+ output.progress(
+ `${PROGRESS_VERBS[operation]} ${project.name} with twenty ${CLI_VERSION}…`,
+ );
+
+ const startedAt = performance.now();
+ const readBuildResult = ({
+ result,
+ output: workerOutput,
+ }: {
+ result: unknown;
+ output: AppWorkerOutput;
+ }): AppOperationResult<TData> => {
+ const toolingResult = parseToolingResult({ value: result, parseData });
+ const diagnostics = [
+ ...toolingResult.diagnostics,
+ ...toWorkerOutputDiagnostics(workerOutput),
+ ];
+
+ if (outputMode === 'human') {
+ for (const diagnostic of diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+
+ if (!toolingResult.success) {
+ throw createToolingFailure({
+ error: toolingResult.error,
+ diagnostics,
+ sdkVersion: sdk.version,
+ });
+ }
+
+ return { data: toolingResult.data, diagnostics };
+ };
+ let heldBuildResult: AppOperationResult<TData> | undefined;
+
+ const workerRun = await runAppWorker({
+ request:
+ operation === 'build'
+ ? {
+ type: 'bundleSnapshot',
+ appPath: project.path,
+ holdSnapshot: isDefined(useHeldBuild),
+ }
+ : { type: 'typecheckSource', appPath: project.path },
+ signal,
+ ...(isDefined(useHeldBuild)
+ ? {
+ useHeldSnapshot: async (heldBuild) => {
+ heldBuildResult = readBuildResult(heldBuild);
+
+ await useHeldBuild({ project, sdk, ...heldBuildResult });
+ },
+ }
+ : {}),
+ });
+
+ if (!isDefined(heldBuildResult)) {
+ signal.throwIfAborted();
+ }
+
+ const { data, diagnostics } = heldBuildResult ?? readBuildResult(workerRun);
+
+ if (hasReleaseFailed(workerRun)) {
+ output.warn({
+ code: 'SNAPSHOT_RELEASE_FAILED',
+ message:
+ 'The temporary build snapshot could not be removed. You can delete .twenty/cli/snapshots once no build is running.',
+ });
+ }
+
+ return {
+ project,
+ sdk,
+ data,
+ diagnostics,
+ durationMilliseconds: Math.round(performance.now() - startedAt),
+ };
+};
+
+export const runAppBuild = ({
+ context,
+ useHeldBuild,
+}: {
+ context: CommandContext;
+ useHeldBuild?: (
+ heldBuild: AppOperationResult<ToolingBuild> & {
+ project: AppProject;
+ sdk: ProjectSdk;
+ },
+ ) => Promise<void>;
+}) =>
+ runAppOperation({
+ operation: 'build',
+ parseData: parseBuildData,
+ context,
+ useHeldBuild,
+ });
+
+export const runAppTypecheck = ({ context }: { context: CommandContext }) =>
+ runAppOperation({
+ operation: 'typecheck',
+ parseData: parseNullData,
+ context,
+ });
diff --git a/packages/twenty-cli/src/app/run-app-worker.ts b/packages/twenty-cli/src/app/run-app-worker.ts
new file mode 100644
index 00000000000..78f13320007
--- /dev/null
+++ b/packages/twenty-cli/src/app/run-app-worker.ts
@@ -0,0 +1,263 @@
+import { type WatchInputs } from '@/app/dev/types/watch-inputs.type';
+import { fork } from 'node:child_process';
+
+import { isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { APP_WORKER } from '@/app/constants/app-worker.constant';
+import { createAppWorkerEnvironment } from '@/app/create-app-worker-environment';
+import { createOutputCollector } from '@/app/create-output-collector';
+import { getAppWorkerLaunch } from '@/app/get-app-worker-launch';
+import { type AppWorkerOutput } from '@/app/types/app-worker-output.type';
+import {
+ type AppWorkerRequest,
+ type AppWorkerResponse,
+} from '@/app/types/app-worker-message.type';
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+type HeldBuild = {
+ result: unknown;
+ watchInputs?: WatchInputs;
+ output: AppWorkerOutput;
+};
+
+type HeldWorkOutcome =
+ | { isSuccessful: true }
+ | { isSuccessful: false; error: unknown };
+
+const isWorkerResponse = (value: unknown): value is AppWorkerResponse =>
+ isPlainObject(value) &&
+ ((value.type === 'result' &&
+ 'result' in value &&
+ (value.isSnapshotHeld === true || value.isSnapshotHeld === false)) ||
+ (value.type === 'released' && 'release' in value) ||
+ (value.type === 'failure' &&
+ isString(value.message) &&
+ (!isDefined(value.code) || isString(value.code)) &&
+ (!isDefined(value.hint) || isString(value.hint)) &&
+ (!isDefined(value.details) || isPlainObject(value.details))));
+
+export const runAppWorker = async ({
+ request,
+ signal,
+ useHeldSnapshot,
+}: {
+ request: Extract<
+ AppWorkerRequest,
+ {
+ type:
+ | 'generateSourceClient'
+ | 'readSourceIdentity'
+ | 'buildManifest'
+ | 'typecheckSource'
+ | 'bundleSnapshot'
+ | 'pull';
+ }
+ >;
+ signal: AbortSignal;
+ useHeldSnapshot?: (heldBuild: HeldBuild) => Promise<void>;
+}) => {
+ signal.throwIfAborted();
+
+ const { modulePath, execArgv } = getAppWorkerLaunch();
+ const worker = fork(modulePath, [], {
+ cwd: request.appPath,
+ env: createAppWorkerEnvironment(process.env),
+ execArgv,
+ serialization: 'json',
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
+ });
+ const stdout = createOutputCollector(APP_WORKER.OUTPUT_LIMIT_BYTES);
+ const stderr = createOutputCollector(APP_WORKER.OUTPUT_LIMIT_BYTES);
+
+ worker.stdout?.on('data', stdout.add);
+ worker.stderr?.on('data', stderr.add);
+
+ return new Promise<{
+ result: unknown;
+ watchInputs?: WatchInputs;
+ release?: unknown;
+ isSnapshotHeld: boolean;
+ output: AppWorkerOutput;
+ }>((resolve, reject) => {
+ let resultResponse:
+ | Extract<AppWorkerResponse, { type: 'result' }>
+ | undefined;
+ let failureResponse:
+ | Extract<AppWorkerResponse, { type: 'failure' }>
+ | undefined;
+ let releasedResponse:
+ | Extract<AppWorkerResponse, { type: 'released' }>
+ | undefined;
+ let heldWork: Promise<HeldWorkOutcome> | undefined;
+ let killTimer: NodeJS.Timeout | undefined;
+ let isSettled = false;
+
+ const readOutput = (): AppWorkerOutput => {
+ const standardOutput = stdout.read();
+ const standardError = stderr.read();
+
+ return {
+ stdout: standardOutput.text,
+ stderr: standardError.text,
+ isTruncated: standardOutput.isTruncated || standardError.isTruncated,
+ };
+ };
+ const askToStop = (stopRequest: AppWorkerRequest) => {
+ if (worker.connected) {
+ worker.send(stopRequest);
+ }
+
+ killTimer = setTimeout(
+ () => worker.kill('SIGKILL'),
+ APP_WORKER.CANCEL_GRACE_MILLISECONDS,
+ );
+ };
+ const cancel = () => askToStop({ type: 'cancel' });
+ const settle = (settleWith: () => void) => {
+ if (isSettled) {
+ return;
+ }
+
+ isSettled = true;
+ signal.removeEventListener('abort', cancel);
+ clearTimeout(killTimer);
+ settleWith();
+ };
+ const startHeldWork = (
+ response: Extract<AppWorkerResponse, { type: 'result' }>,
+ ) => {
+ signal.removeEventListener('abort', cancel);
+ clearTimeout(killTimer);
+
+ const runHeldWork = isDefined(useHeldSnapshot)
+ ? useHeldSnapshot({
+ result: response.result,
+ watchInputs: response.watchInputs,
+ output: readOutput(),
+ })
+ : Promise.resolve();
+
+ heldWork = runHeldWork
+ .then(
+ (): HeldWorkOutcome => ({ isSuccessful: true }),
+ (error: unknown): HeldWorkOutcome => ({
+ isSuccessful: false,
+ error,
+ }),
+ )
+ .finally(() => askToStop({ type: 'release' }));
+ };
+ const finish = ({
+ exitCode,
+ exitSignal,
+ heldOutcome,
+ }: {
+ exitCode: number | null;
+ exitSignal: NodeJS.Signals | null;
+ heldOutcome?: HeldWorkOutcome;
+ }) =>
+ settle(() => {
+ const output = readOutput();
+
+ if (isDefined(heldOutcome) && !heldOutcome.isSuccessful) {
+ reject(heldOutcome.error);
+
+ return;
+ }
+
+ if (isDefined(resultResponse)) {
+ resolve({
+ result: resultResponse.result,
+ watchInputs: resultResponse.watchInputs,
+ release: resultResponse.isSnapshotHeld
+ ? releasedResponse?.release
+ : resultResponse.release,
+ isSnapshotHeld: resultResponse.isSnapshotHeld,
+ output,
+ });
+
+ return;
+ }
+
+ if (signal.aborted) {
+ reject(createCancelledError());
+
+ return;
+ }
+
+ const stopReason = isDefined(exitSignal)
+ ? `signal ${exitSignal}`
+ : `exit code ${exitCode}`;
+
+ reject(
+ new CliError({
+ code: 'WORKER_FAILED',
+ message: isDefined(failureResponse)
+ ? `The app worker failed: ${failureResponse.message}`
+ : `The app worker stopped before finishing (${stopReason}). The app or the SDK may have exited the process.`,
+ hint: failureResponse?.hint,
+ details: {
+ ...failureResponse?.details,
+ workerErrorCode: failureResponse?.code,
+ exitCode,
+ signal: exitSignal,
+ output,
+ },
+ }),
+ );
+ });
+
+ signal.addEventListener('abort', cancel, { once: true });
+
+ worker.on('message', (message: unknown) => {
+ if (!isWorkerResponse(message)) {
+ return;
+ }
+
+ if (message.type === 'released') {
+ releasedResponse = message;
+
+ return;
+ }
+
+ if (message.type === 'failure') {
+ failureResponse = message;
+
+ return;
+ }
+
+ resultResponse = message;
+
+ if (message.isSnapshotHeld) {
+ startHeldWork(message);
+ }
+ });
+
+ worker.on('error', (error) =>
+ settle(() =>
+ reject(
+ new CliError({
+ code: 'WORKER_FAILED',
+ message: `The app worker could not run: ${error.message}`,
+ }),
+ ),
+ ),
+ );
+
+ worker.on('close', (exitCode, exitSignal) => {
+ if (!isDefined(heldWork)) {
+ finish({ exitCode, exitSignal });
+
+ return;
+ }
+
+ heldWork
+ .then((heldOutcome) => finish({ exitCode, exitSignal, heldOutcome }))
+ .catch((error: unknown) => settle(() => reject(error)));
+ });
+
+ worker.send(request);
+ });
+};
diff --git a/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts b/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts
new file mode 100644
index 00000000000..924554b5bdc
--- /dev/null
+++ b/packages/twenty-cli/src/app/snapshots/__tests__/snapshot-parity.spec.ts
@@ -0,0 +1,732 @@
+import { createHash } from 'node:crypto';
+import {
+ cp,
+ lstat,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import { build as bundle, stop } from 'esbuild';
+import { isPlainObject } from 'twenty-shared/utils';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { SORTED_GLOB_PLUGIN } from '@/app/__tests__/utils/sorted-glob-plugin';
+import { createAppProject } from '@/app/create-app-project';
+import { pathExists } from '@/app/fs-utils';
+import { runAppWorker } from '@/app/run-app-worker';
+import { buildSnapshot, releaseSnapshot } from '@/app/snapshots/build-snapshot';
+import { type ToolingBuild } from '@/app/types/tooling-result.type';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+vi.mock('@/app/get-app-template-directory', () => ({
+ getAppTemplateDirectory: () =>
+ join(REPOSITORY_ROOT, 'packages/create-twenty-app/src/constants/template'),
+}));
+vi.mock('@/app/get-app-template-overlay-directory', () => ({
+ getAppTemplateOverlayDirectory: () =>
+ join(REPOSITORY_ROOT, 'packages/twenty-cli/app-template-overlay'),
+}));
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const FIXTURES_DIRECTORY = join(
+ REPOSITORY_ROOT,
+ 'packages/twenty-apps/fixtures',
+);
+const FIXTURES = [
+ 'minimal-app',
+ 'rich-app',
+ 'function-execute-app',
+ 'shared-dependencies-app',
+ 'invalid-app',
+];
+const json = (value: unknown): unknown => JSON.parse(JSON.stringify(value));
+const hash = (bytes: Buffer | string) =>
+ createHash('sha256').update(bytes).digest('hex');
+const requireDirectory = (build: ToolingBuild) => {
+ if (!build.directory) throw new Error('Snapshot has no directory');
+ return build.directory;
+};
+const compareDirectory = async (
+ first: string,
+ second: string,
+ bundledFrontPaths: Set<string>,
+) => {
+ const entries = (
+ await readdir(first, { recursive: true, withFileTypes: true })
+ ).filter((entry) => entry.isFile());
+ expect((await readdir(second, { recursive: true })).sort()).toEqual(
+ (await readdir(first, { recursive: true })).sort(),
+ );
+ for (const entry of entries) {
+ const path = join(entry.parentPath, entry.name).slice(first.length + 1);
+ if (
+ path === 'manifest.json' ||
+ bundledFrontPaths.has(path) ||
+ (path.endsWith('.map') && bundledFrontPaths.has(path.slice(0, -4)))
+ )
+ continue;
+ const expected = await readFile(join(first, path));
+ const actual = await readFile(join(second, path));
+ if (path.endsWith('.map')) {
+ const normalize = (bytes: Buffer, directory: string) => {
+ const map = JSON.parse(bytes.toString());
+ map.sources = map.sources.map((source: string) =>
+ /^[a-z-]+:/i.test(source)
+ ? source
+ : resolve(dirname(join(directory, path)), source),
+ );
+ map.sourcesContent = map.sourcesContent.map(
+ (source: string, index: number) =>
+ map.sources[index] ===
+ 'twenty-sdk-define-stub:__twenty-sdk-define-stub__'
+ ? source.replace(
+ /^\/\/ Auto-generated stub for twenty-sdk\/define[^\r\n]*$/m,
+ '',
+ )
+ : source,
+ );
+ return map;
+ };
+ expect(normalize(actual, second), path).toEqual(
+ normalize(expected, first),
+ );
+ } else {
+ expect(actual.equals(expected), path).toBe(true);
+ }
+ }
+};
+
+const comparableSnapshot = (build: ToolingBuild) => {
+ const manifest = structuredClone(build.manifest);
+
+ if (Array.isArray(manifest.frontComponents)) {
+ for (const component of manifest.frontComponents) {
+ if (isPlainObject(component)) component.builtComponentChecksum = null;
+ }
+ }
+ if (
+ isPlainObject(manifest.application) &&
+ isPlainObject(manifest.application.frontComponentSharedDependencies)
+ ) {
+ manifest.application.frontComponentSharedDependencies.builtChecksum = null;
+ }
+
+ return {
+ ...build,
+ manifest,
+ buildId: '',
+ directory: '',
+ contentHash: '',
+ files: build.files.map((file) =>
+ file.role === 'built-front-component'
+ ? { ...file, sha256: '', size: 0 }
+ : file,
+ ),
+ };
+};
+
+describe('CLI snapshots preserve SDK manifests and non-frontend artifacts', () => {
+ let root: string;
+ let sdkEntryPath: string;
+ const copyFixture = async (name: string) => {
+ const appPath = await mkdtemp(join(root, `${name}-`));
+
+ await cp(join(FIXTURES_DIRECTORY, name), appPath, {
+ recursive: true,
+ filter: (source) =>
+ !source
+ .split('/')
+ .some((part) => ['node_modules', '.twenty', 'dist'].includes(part)),
+ });
+ await symlink(join(root, 'node_modules'), join(appPath, 'node_modules'));
+
+ return appPath;
+ };
+
+ const buildSdkSnapshot = async (
+ appPath: string,
+ useHeldSnapshot?: Parameters<typeof runAppWorker>[0]['useHeldSnapshot'],
+ ) => {
+ launch.modulePath = join(root, 'reference/app-worker.cjs');
+ try {
+ return await runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: true },
+ signal: new AbortController().signal,
+ useHeldSnapshot: async (snapshot) => {
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ await useHeldSnapshot?.(snapshot);
+ },
+ });
+ } finally {
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ }
+ };
+
+ const compareSnapshot = async (appPath: string) => {
+ const compareBuild = async ({ result }: { result: unknown }) => {
+ const expected = result as Awaited<ReturnType<typeof buildSnapshot>>;
+ const response = await runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: true },
+ signal: new AbortController().signal,
+ useHeldSnapshot: async ({ result }) => {
+ expect(result).toMatchObject({ success: true });
+ const actual = (result as { data: ToolingBuild }).data;
+ if (!expected.success) throw new Error(JSON.stringify(expected));
+ const directory = requireDirectory(actual);
+ expect(directory).toContain('/.twenty/cli/snapshots/build-');
+ expect(json(comparableSnapshot(actual))).toEqual(
+ json(comparableSnapshot(expected.data)),
+ );
+ expect(
+ JSON.parse(
+ await readFile(join(dirname(directory), 'lease.json'), 'utf8'),
+ ),
+ ).toMatchObject({
+ buildId: actual.buildId,
+ pid: expect.any(Number),
+ createdAt: expect.any(String),
+ });
+ for (const artifact of actual.files) {
+ const bytes = await readFile(join(directory, artifact.path));
+ expect(artifact.size).toBe(bytes.length);
+ expect(artifact.sha256).toBe(hash(bytes));
+ }
+ const manifestBytes = await readFile(
+ join(directory, 'manifest.json'),
+ );
+ expect(JSON.parse(manifestBytes.toString())).toEqual(
+ json(actual.manifest),
+ );
+ expect(actual.contentHash).toBe(
+ createHash('sha256')
+ .update(
+ JSON.stringify(
+ actual.files.map(({ path, role, sha256 }) => ({
+ path,
+ role,
+ sha256,
+ })),
+ ),
+ )
+ .update('\n')
+ .update(manifestBytes)
+ .digest('hex'),
+ );
+ const frontComponents = actual.manifest.frontComponents;
+ if (Array.isArray(frontComponents)) {
+ for (const component of frontComponents) {
+ if (isPlainObject(component)) {
+ expect(component.builtComponentChecksum).toBe(
+ actual.files.find(
+ (file) => file.path === component.builtComponentPath,
+ )?.sha256,
+ );
+ }
+ }
+ }
+ const application = actual.manifest.application;
+ if (
+ isPlainObject(application) &&
+ isPlainObject(application.frontComponentSharedDependencies)
+ ) {
+ const sharedDependencies =
+ application.frontComponentSharedDependencies;
+ const artifact = actual.files.find(
+ (file) => file.path === sharedDependencies.builtPath,
+ );
+ expect(artifact).toBeDefined();
+ expect(sharedDependencies.builtChecksum).toBe(artifact?.sha256);
+ }
+ const logicFunctions = actual.manifest.logicFunctions;
+ if (Array.isArray(logicFunctions)) {
+ for (const logicFunction of logicFunctions) {
+ if (isPlainObject(logicFunction)) {
+ const artifact = actual.files.find(
+ (file) => file.path === logicFunction.builtHandlerPath,
+ );
+ if (!artifact) throw new Error('Missing function artifact');
+ expect(logicFunction.builtHandlerChecksum).toBe(
+ createHash('md5')
+ .update(await readFile(join(directory, artifact.path)))
+ .digest('hex'),
+ );
+ }
+ }
+ }
+ await compareDirectory(
+ requireDirectory(expected.data),
+ directory,
+ new Set(
+ actual.files
+ .filter((file) => file.role === 'built-front-component')
+ .map((file) => file.path),
+ ),
+ );
+ },
+ });
+ if (!expected.success) {
+ expect(response.result).toEqual(json(expected));
+ } else {
+ expect(response.result, JSON.stringify(response.result)).toMatchObject({
+ success: true,
+ });
+ expect(response.release).toEqual({
+ success: true,
+ data: null,
+ diagnostics: [],
+ });
+ expect(
+ (response.result as { diagnostics: unknown }).diagnostics,
+ ).toEqual(json(expected.diagnostics));
+ }
+ expect(await readdir(join(appPath, '.twenty/cli/snapshots'))).toEqual([]);
+ };
+ const reference = await buildSdkSnapshot(appPath, compareBuild);
+ if (!reference.isSnapshotHeld) {
+ await compareBuild(reference);
+ }
+ return reference.result as Awaited<ReturnType<typeof buildSnapshot>>;
+ };
+ beforeAll(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-bundle-parity-'));
+ const modules = join(root, 'node_modules');
+ const sdkPath = join(modules, 'twenty-sdk');
+ const sourceSdk = join(REPOSITORY_ROOT, 'packages/twenty-sdk');
+ const sdkRequire = createRequire(join(sourceSdk, 'package.json'));
+
+ await mkdir(join(modules, '@sniptt'), { recursive: true });
+
+ for (const name of [
+ 'sharp',
+ 'react',
+ 'react-dom',
+ '@types',
+ '@sniptt/guards',
+ 'uuid',
+ 'esbuild',
+ 'typescript',
+ 'tinyglobby',
+ 'vitest',
+ 'vite-tsconfig-paths',
+ 'twenty-shared',
+ 'twenty-client-sdk',
+ 'twenty-ui',
+ ]) {
+ await symlink(
+ name === 'uuid'
+ ? dirname(sdkRequire.resolve(`${name}/package.json`))
+ : join(REPOSITORY_ROOT, 'node_modules', name),
+ join(modules, name),
+ );
+ }
+
+ const packageJson = JSON.parse(
+ await readFile(join(sourceSdk, 'package.json'), 'utf8'),
+ );
+ const exports: Record<string, unknown> = {};
+
+ for (const name of [
+ 'define',
+ 'front-component',
+ 'logic-function',
+ 'billing',
+ 'utils',
+ ]) {
+ await cp(join(sourceSdk, 'dist', name), join(sdkPath, 'dist', name), {
+ recursive: true,
+ });
+ exports[`./${name}`] = packageJson.exports[`./${name}`];
+ }
+
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: packageJson.name,
+ version: packageJson.version,
+ engines: packageJson.engines,
+ exports,
+ }),
+ );
+ expect(() =>
+ createRequire(join(root, 'package.json')).resolve('twenty-sdk/build'),
+ ).toThrow();
+
+ sdkEntryPath = join(root, 'sdk-reference.cjs');
+ const sdkSource = join(sourceSdk, 'src');
+
+ await bundle({
+ stdin: {
+ contents: `export { buildSnapshot as buildSourceSnapshot, releaseSnapshot as releaseSourceSnapshot } from './application-build/build-snapshot';`,
+ resolveDir: sdkSource,
+ },
+ outfile: sdkEntryPath,
+ alias: { '@': sdkSource },
+ bundle: true,
+ packages: 'external',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node24',
+ plugins: [SORTED_GLOB_PLUGIN],
+ });
+
+ await mkdir(join(root, 'assets'));
+ await cp(
+ join(sdkSource, 'cli/utilities/build/cover/assets/halftone-backdrop.png'),
+ join(root, 'assets/halftone-backdrop.png'),
+ );
+ await buildTestAppWorker(join(root, 'reference'), {
+ aliases: { '@/app/worker/build-source-snapshot': sdkEntryPath },
+ });
+ await buildTestAppWorker(join(root, 'cli'));
+ launch.modulePath = join(root, 'cli/app-worker.cjs');
+ }, 60000);
+
+ afterAll(async () => {
+ await stop();
+ await rm(root, { recursive: true, force: true });
+ });
+ it('covers every repository fixture', async () => {
+ expect(
+ (await readdir(FIXTURES_DIRECTORY, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort(),
+ ).toEqual([...FIXTURES].sort());
+ });
+ it.each(FIXTURES)(
+ 'preserves SDK manifest and non-frontend bytes, validates all artifact hashes for %s',
+ async (name) => {
+ const result = await compareSnapshot(await copyFixture(name));
+ expect(result.success, JSON.stringify(result)).toBe(
+ name !== 'invalid-app',
+ );
+ },
+ 60000,
+ );
+ it('typechecks the template test setup with an authoring-only SDK', async () => {
+ const appPath = join(root, 'fresh-app');
+ await createAppProject({
+ appDirectory: appPath,
+ appName: 'fresh-app',
+ appDisplayName: 'Fresh app',
+ appDescription: 'Bundle parity fixture',
+ signal: new AbortController().signal,
+ });
+ await symlink(join(root, 'node_modules'), join(appPath, 'node_modules'));
+ const configPath = join(appPath, 'tsconfig.json');
+ const config = JSON.parse(await readFile(configPath, 'utf8'));
+ config.exclude.push('vitest*.config.ts');
+ await writeFile(configPath, JSON.stringify(config));
+ const result = await compareSnapshot(appPath);
+ expect(result.success, JSON.stringify(result)).toBe(true);
+ expect(JSON.stringify(result)).not.toContain('twenty-sdk/cli');
+ }, 60000);
+ it('matches CSS, baked translations, README selection and immutable symlinked assets', async () => {
+ const appPath = await copyFixture('minimal-app');
+ await mkdir(join(appPath, 'locales'), { recursive: true });
+ await writeFile(
+ join(appPath, 'locales/fr-FR.json'),
+ JSON.stringify({ Hello: 'Bonjour' }),
+ );
+ await writeFile(join(appPath, 'README.md'), '# Keep the markdown readme\n');
+ await writeFile(join(appPath, 'README.txt'), 'Not preferred');
+ await writeFile(join(appPath, 'asset-source.txt'), 'original asset');
+ await mkdir(join(appPath, 'public'), { recursive: true });
+ await symlink(
+ join(appPath, 'asset-source.txt'),
+ join(appPath, 'public/asset.txt'),
+ );
+ const component = (await readdir(appPath)).find((file) =>
+ file.endsWith('.tsx'),
+ );
+ if (!component) throw new Error('No front component');
+ await writeFile(join(appPath, 'style.css'), 'div { color: red; }');
+ const componentPath = join(appPath, component);
+ await writeFile(
+ componentPath,
+ "import './style.css';\n" + (await readFile(componentPath, 'utf8')),
+ );
+ expect((await compareSnapshot(appPath)).success).toBe(true);
+ const first = await buildSnapshot({ appPath });
+ if (!first.success) throw new Error(JSON.stringify(first));
+ const directory = requireDirectory(first.data);
+ try {
+ expect(
+ (await lstat(join(directory, 'public/asset.txt'))).isSymbolicLink(),
+ ).toBe(false);
+ await writeFile(join(appPath, 'asset-source.txt'), 'changed asset');
+ expect(await readFile(join(directory, 'public/asset.txt'), 'utf8')).toBe(
+ 'original asset',
+ );
+ expect(await readFile(join(directory, 'README.md'), 'utf8')).toBe(
+ '# Keep the markdown readme\n',
+ );
+ expect(await pathExists(join(directory, 'README.txt'))).toBe(false);
+ } finally {
+ await releaseSnapshot({ buildId: first.data.buildId });
+ }
+ }, 60000);
+
+ it('uses optional sharp for identical covers and warns when it is missing', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const applicationPath = join(appPath, 'application.config.ts');
+ await writeFile(
+ applicationPath,
+ (await readFile(applicationPath, 'utf8')).replace(
+ "displayName: 'Root App',",
+ "displayName: 'Root App', logo: 'public/logo.png',",
+ ),
+ );
+ await mkdir(join(appPath, 'public'), { recursive: true });
+ await cp(
+ join(
+ REPOSITORY_ROOT,
+ 'packages/twenty-sdk/src/cli/utilities/build/cover/assets/halftone-backdrop.png',
+ ),
+ join(appPath, 'public/logo.png'),
+ );
+ const reference = await compareSnapshot(appPath);
+ expect(reference).toMatchObject({
+ success: true,
+ data: {
+ manifest: {
+ application: { galleryImages: ['public/cover.generated.png'] },
+ },
+ },
+ });
+ await rm(join(root, 'node_modules/sharp'));
+ try {
+ const response = await runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: false },
+ signal: new AbortController().signal,
+ });
+ expect(response.result).toMatchObject({
+ success: true,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ severity: 'warning',
+ message: expect.stringContaining('Skipped cover image generation:'),
+ }),
+ ]),
+ });
+ expect(
+ (response.result as { data: ToolingBuild }).data.files.some(
+ (file) => file.path === 'public/cover.generated.png',
+ ),
+ ).toBe(false);
+ expect(await readdir(join(appPath, '.twenty/cli/snapshots'))).toEqual([]);
+ } finally {
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules/sharp'),
+ join(root, 'node_modules/sharp'),
+ );
+ }
+ }, 60000);
+
+ it('keeps concurrent snapshots independent and releases only its own files', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const existingPaths = [
+ 'keep.txt',
+ '.twenty/output/keep.txt',
+ '.twenty/snapshots/build-sdk/keep.txt',
+ '.twenty/cli/snapshots/build-existing/keep.txt',
+ ];
+ for (const path of existingPaths) {
+ await mkdir(dirname(join(appPath, path)), { recursive: true });
+ await writeFile(join(appPath, path), 'existing content');
+ }
+ const snapshots = await Promise.all([
+ buildSnapshot({ appPath }),
+ buildSnapshot({ appPath }),
+ ]);
+ const [first, second] = snapshots;
+ if (!first.success || !second.success)
+ throw new Error(JSON.stringify(snapshots));
+ try {
+ expect(first.data.buildId).not.toBe(second.data.buildId);
+ expect(first.data.directory).not.toBe(second.data.directory);
+ expect(first.data.contentHash).toBe(second.data.contentHash);
+ expect(first.data.files).toEqual(second.data.files);
+ expect(
+ await releaseSnapshot({ buildId: first.data.buildId }),
+ ).toMatchObject({ success: true });
+ expect(
+ await releaseSnapshot({ buildId: first.data.buildId }),
+ ).toMatchObject({
+ success: false,
+ error: { code: 'SNAPSHOT_NOT_FOUND' },
+ });
+ expect(await releaseSnapshot({ buildId: 'unowned-build' })).toMatchObject(
+ { success: false, error: { code: 'SNAPSHOT_NOT_FOUND' } },
+ );
+ expect(await pathExists(requireDirectory(second.data))).toBe(true);
+ for (const path of existingPaths)
+ expect(await readFile(join(appPath, path), 'utf8')).toBe(
+ 'existing content',
+ );
+ } finally {
+ await Promise.all(
+ snapshots.map(
+ (snapshot) =>
+ snapshot.success &&
+ releaseSnapshot({ buildId: snapshot.data.buildId }),
+ ),
+ );
+ }
+ }, 60000);
+
+ it('cleans cancelled and failed builds without touching existing snapshots', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const snapshotsPath = join(appPath, '.twenty/cli/snapshots');
+ await mkdir(join(snapshotsPath, 'build-existing'), { recursive: true });
+ expect(
+ await buildSnapshot({ appPath, signal: AbortSignal.abort() }),
+ ).toMatchObject({ success: false, error: { code: 'CANCELLED' } });
+ await writeFile(
+ join(appPath, 'my.function.ts'),
+ 'export default defineLogicFunction({ broken syntax',
+ );
+ expect(await buildSnapshot({ appPath })).toMatchObject({
+ success: false,
+ error: { code: expect.stringMatching(/BUILD_FAILED/) },
+ });
+ expect(await readdir(snapshotsPath)).toEqual(['build-existing']);
+ expect(await buildSnapshot({ appPath: 'relative-path' })).toMatchObject({
+ success: false,
+ error: { code: 'INVALID_APP_PATH' },
+ });
+ }, 60000);
+
+ it.each(['source error', 'unbuilt project reference'])(
+ 'matches a build failure for %s and removes only the failed snapshot',
+ async (failure) => {
+ const appPath = await copyFixture('minimal-app');
+ const snapshotsPath = join(appPath, '.twenty/cli/snapshots');
+ await mkdir(join(snapshotsPath, 'build-existing'), { recursive: true });
+ const expectedCode = failure === 'source error' ? 'TS2322' : 'TS6305';
+ if (failure === 'source error') {
+ await writeFile(
+ join(appPath, 'type-error.ts'),
+ 'export const broken: number = "bad";',
+ );
+ } else {
+ await mkdir(join(appPath, 'referenced'));
+ await writeFile(
+ join(appPath, 'referenced/source.ts'),
+ 'export const value = 1;',
+ );
+ await writeFile(
+ join(appPath, 'referenced/tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { composite: true, outDir: 'dist', types: [] },
+ files: ['source.ts'],
+ }),
+ );
+ const configPath = join(appPath, 'tsconfig.json');
+ const config = JSON.parse(await readFile(configPath, 'utf8'));
+ config.references = [{ path: './referenced' }];
+ await writeFile(configPath, JSON.stringify(config));
+ }
+ const expected = (await buildSdkSnapshot(appPath)).result;
+ const response = await runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: true },
+ signal: new AbortController().signal,
+ });
+ expect(response.result).toEqual(json(expected));
+ expect(response.result).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({ code: expectedCode }),
+ ]),
+ });
+ expect(response.isSnapshotHeld).toBe(false);
+ expect(await readdir(snapshotsPath)).toEqual(['build-existing']);
+ },
+ 60000,
+ );
+
+ it('releases the held snapshot when its consumer fails', async () => {
+ const appPath = await copyFixture('minimal-app');
+ await expect(
+ runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: true },
+ signal: new AbortController().signal,
+ useHeldSnapshot: async () => {
+ throw new Error('Upload failed');
+ },
+ }),
+ ).rejects.toThrow('Upload failed');
+ expect(await readdir(join(appPath, '.twenty/cli/snapshots'))).toEqual([]);
+ }, 60000);
+
+ it('stubs the project SDK exports including its runtime constants', async () => {
+ const appPath = await copyFixture('minimal-app');
+ const sdkPath = join(root, 'node_modules/twenty-sdk');
+ const packagePath = join(sdkPath, 'package.json');
+ const originalPackage = await readFile(packagePath, 'utf8');
+ const packageJson = JSON.parse(originalPackage);
+ const defineEntry = createRequire(join(appPath, 'package.json')).resolve(
+ 'twenty-sdk/define',
+ );
+ await writeFile(
+ join(sdkPath, 'custom-define.cjs'),
+ `module.exports = { ...require(${JSON.stringify(defineEntry)}), CUSTOM_RUNTIME_CONSTANT: 42 };`,
+ );
+ await writeFile(
+ join(sdkPath, 'custom-define.d.ts'),
+ "export * from './dist/define/index'; export declare const CUSTOM_RUNTIME_CONSTANT: 42;",
+ );
+ packageJson.exports['./define'] = {
+ types: './custom-define.d.ts',
+ import: './custom-define.cjs',
+ require: './custom-define.cjs',
+ };
+ await writeFile(packagePath, JSON.stringify(packageJson));
+ const functionPath = join(appPath, 'my.function.ts');
+ await writeFile(
+ functionPath,
+ (await readFile(functionPath, 'utf8'))
+ .replace(
+ 'import { defineLogicFunction }',
+ 'import { defineLogicFunction, CUSTOM_RUNTIME_CONSTANT }',
+ )
+ .replace(
+ "return 'my-function-result'",
+ 'return CUSTOM_RUNTIME_CONSTANT',
+ ),
+ );
+ try {
+ await runAppWorker({
+ request: { type: 'bundleSnapshot', appPath, holdSnapshot: true },
+ signal: new AbortController().signal,
+ useHeldSnapshot: async ({ result }) => {
+ expect(result).toMatchObject({ success: true });
+ const snapshot = (result as { data: ToolingBuild }).data;
+ const builtFunction = await import(
+ pathToFileURL(join(requireDirectory(snapshot), 'my.function.mjs'))
+ .href
+ );
+ expect(builtFunction.default.config.handler()).toBe(42);
+ },
+ });
+ } finally {
+ await writeFile(packagePath, originalPackage);
+ }
+ }, 60000);
+});
diff --git a/packages/twenty-cli/src/app/snapshots/build-snapshot.ts b/packages/twenty-cli/src/app/snapshots/build-snapshot.ts
new file mode 100644
index 00000000000..9cafc512ff4
--- /dev/null
+++ b/packages/twenty-cli/src/app/snapshots/build-snapshot.ts
@@ -0,0 +1,155 @@
+import { randomUUID } from 'node:crypto';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { join, relative } from 'node:path';
+import { isDefined } from 'twenty-shared/utils';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import {
+ type ToolingBuild,
+ type ToolingDiagnostic,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import { compileApplication } from '@/app/bundles/compile-application';
+import { collectBuildSnapshot } from '@/app/snapshots/collect-build-snapshot';
+import { validateAppPath } from '@/app/snapshots/validate-app-path';
+import { CliError } from '@/output/cli-error';
+
+const snapshotDirectories = new Map<string, string>();
+
+export const buildSnapshot = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal?: AbortSignal;
+}): Promise<ToolingResult<ToolingBuild>> => {
+ const validation = await validateAppPath(appPath);
+
+ if (!validation.success) {
+ return validation;
+ }
+
+ let snapshotDirectory: string | undefined;
+ const diagnostics: ToolingDiagnostic[] = [];
+ const cleanupSnapshot = async () => {
+ if (!isDefined(snapshotDirectory)) {
+ return;
+ }
+
+ try {
+ await rm(snapshotDirectory, { recursive: true, force: true });
+ } catch (error) {
+ diagnostics.push({
+ severity: 'warning',
+ code: 'SNAPSHOT_CLEANUP_FAILED',
+ message: `Could not remove snapshot ${snapshotDirectory}: ${error instanceof Error ? error.message : String(error)}`,
+ });
+ }
+ };
+
+ try {
+ signal?.throwIfAborted();
+ const buildId = randomUUID();
+ const snapshotsDirectory = join(appPath, '.twenty', 'cli', 'snapshots');
+
+ await mkdir(snapshotsDirectory, { recursive: true });
+ snapshotDirectory = await mkdtemp(join(snapshotsDirectory, 'build-'));
+ await writeFile(
+ join(snapshotDirectory, 'lease.json'),
+ JSON.stringify({
+ buildId,
+ pid: process.pid,
+ createdAt: new Date().toISOString(),
+ }),
+ { flag: 'wx' },
+ );
+
+ const filesDirectory = join(snapshotDirectory, 'files');
+ const result = await compileApplication({
+ appPath,
+ outputDir: relative(appPath, filesDirectory),
+ dereferenceSymlinks: true,
+ signal,
+ });
+
+ diagnostics.push(...result.diagnostics);
+
+ if (!result.success) {
+ await cleanupSnapshot();
+
+ return {
+ ...result,
+ diagnostics,
+ };
+ }
+
+ const snapshot = await collectBuildSnapshot({
+ appPath,
+ buildId,
+ filesDirectory,
+ manifest: result.data.manifest,
+ builtFileInfos: result.data.builtFileInfos,
+ signal,
+ });
+
+ signal?.throwIfAborted();
+ snapshotDirectories.set(buildId, snapshotDirectory);
+
+ return {
+ success: true,
+ data: snapshot,
+ diagnostics,
+ };
+ } catch (error) {
+ await cleanupSnapshot();
+
+ return {
+ success: false,
+ error: {
+ code: signal?.aborted
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'BUILD_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ },
+ diagnostics,
+ };
+ }
+};
+
+export const releaseSnapshot = async ({
+ buildId,
+}: {
+ buildId: string;
+}): Promise<ToolingResult<null>> => {
+ const snapshotDirectory = snapshotDirectories.get(buildId);
+
+ if (!isDefined(snapshotDirectory)) {
+ return {
+ success: false,
+ error: {
+ code: 'SNAPSHOT_NOT_FOUND',
+ message: 'This CLI worker does not hold the requested snapshot.',
+ },
+ diagnostics: [],
+ };
+ }
+
+ try {
+ await rm(snapshotDirectory, { recursive: true, force: true });
+ snapshotDirectories.delete(buildId);
+
+ return { success: true, data: null, diagnostics: [] };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code: 'SNAPSHOT_RELEASE_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ diagnostics: [],
+ };
+ }
+};
diff --git a/packages/twenty-cli/src/app/snapshots/collect-build-snapshot.ts b/packages/twenty-cli/src/app/snapshots/collect-build-snapshot.ts
new file mode 100644
index 00000000000..e286fdc7e19
--- /dev/null
+++ b/packages/twenty-cli/src/app/snapshots/collect-build-snapshot.ts
@@ -0,0 +1,117 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { createHash } from 'node:crypto';
+import { createReadStream } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import { isAbsolute, join, relative, sep } from 'node:path';
+import { type Manifest } from 'twenty-shared/application';
+import { FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BuiltFileInfo } from '@/app/bundles/build-application';
+import {
+ type ToolingArtifact,
+ type ToolingBuild,
+} from '@/app/types/tooling-result.type';
+
+const ROLE_BY_FILE_FOLDER: Partial<
+ Record<FileFolder, ToolingArtifact['role']>
+> = {
+ [FileFolder.BuiltLogicFunction]: 'built-logic-function',
+ [FileFolder.BuiltFrontComponent]: 'built-front-component',
+ [FileFolder.Source]: 'source',
+ [FileFolder.Dependencies]: 'dependencies',
+ [FileFolder.PublicAsset]: 'public-asset',
+};
+
+export const collectBuildSnapshot = async ({
+ appPath,
+ buildId,
+ filesDirectory,
+ manifest,
+ builtFileInfos,
+ signal,
+}: {
+ appPath: string;
+ buildId: string;
+ filesDirectory: string;
+ manifest: Manifest;
+ builtFileInfos: Map<string, BuiltFileInfo>;
+ signal?: AbortSignal;
+}): Promise<ToolingBuild> => {
+ const files: ToolingArtifact[] = [];
+
+ for (const file of builtFileInfos.values()) {
+ signal?.throwIfAborted();
+ const absolutePath = join(appPath, file.builtPath);
+ const filePath = relative(filesDirectory, absolutePath);
+ const role = ROLE_BY_FILE_FOLDER[file.fileFolder];
+
+ if (
+ !isDefined(role) ||
+ isAbsolute(filePath) ||
+ filePath === '..' ||
+ filePath.startsWith(`..${sep}`)
+ ) {
+ throw new Error(`Invalid snapshot artifact: ${file.builtPath}`);
+ }
+
+ const hash = createHash('sha256');
+ let size = 0;
+
+ for await (const chunk of createReadStream(absolutePath, { signal })) {
+ hash.update(chunk);
+ size += chunk.length;
+ }
+
+ files.push({
+ path: filePath.split(sep).join('/'),
+ sourcePath: file.sourcePath.split(sep).join('/'),
+ role,
+ size,
+ sha256: hash.digest('hex'),
+ });
+ }
+
+ const sortedFiles = files.sort((first, second) => {
+ if (first.path < second.path) {
+ return -1;
+ }
+
+ if (first.path > second.path) {
+ return 1;
+ }
+
+ return 0;
+ });
+ const manifestBytes = await readFile(join(filesDirectory, 'manifest.json'));
+ const contentHash = createHash('sha256')
+ .update(
+ JSON.stringify(
+ sortedFiles.map(({ path, role, sha256 }) => ({ path, role, sha256 })),
+ ),
+ )
+ .update('\n')
+ .update(manifestBytes)
+ .digest('hex');
+ const packageJson: { name?: unknown } = JSON.parse(
+ await readFile(join(filesDirectory, 'package.json'), 'utf8'),
+ );
+
+ if (!isNonEmptyString(packageJson.name)) {
+ throw new Error('The app package.json must declare a name.');
+ }
+
+ return {
+ buildId,
+ directory: filesDirectory,
+ contentHash,
+ application: {
+ universalIdentifier: manifest.application.universalIdentifier,
+ name: packageJson.name,
+ displayName: manifest.application.displayName,
+ },
+ manifestFormat: 'twenty-application',
+ manifest,
+ files: sortedFiles,
+ };
+};
diff --git a/packages/twenty-cli/src/app/snapshots/validate-app-path.ts b/packages/twenty-cli/src/app/snapshots/validate-app-path.ts
new file mode 100644
index 00000000000..9b0f19e0d51
--- /dev/null
+++ b/packages/twenty-cli/src/app/snapshots/validate-app-path.ts
@@ -0,0 +1,24 @@
+import { stat } from 'node:fs/promises';
+import { isAbsolute } from 'node:path';
+
+import { type ToolingResult } from '@/app/types/tooling-result.type';
+
+export const validateAppPath = async (
+ appPath: string,
+): Promise<ToolingResult<null>> => {
+ if (
+ isAbsolute(appPath) &&
+ (await stat(appPath).catch(() => null))?.isDirectory()
+ ) {
+ return { success: true, data: null, diagnostics: [] };
+ }
+
+ return {
+ success: false,
+ error: {
+ code: 'INVALID_APP_PATH',
+ message: 'appPath must be an absolute path to an existing directory.',
+ },
+ diagnostics: [],
+ };
+};
diff --git a/packages/twenty-cli/src/app/source/README.md b/packages/twenty-cli/src/app/source/README.md
new file mode 100644
index 00000000000..4d0e4b7e2ef
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/README.md
@@ -0,0 +1,33 @@
+# App source loading
+
+This CLI-owned source loader powers `twenty app pull` and the [manifest builder](../manifest/README.md) used by public build, plan and apply commands.
+
+Package boundaries are documented in the
+[app tooling overview](../README.md).
+
+## Boundary
+
+`readAppIdentity` checks the installed SDK without importing it, then evaluates the application's definition in a disposable CLI worker. Source is trusted executable developer code. The child contains exits, captures bounded output and can be killed on cancellation; it is not a filesystem or network sandbox. Selected workspace credentials are removed from its environment by the worker launcher.
+
+`scanProjectSourceFiles` stays inside the worker. Its configs may contain functions and React components, so reconciliation runs in that same worker rather than send configs over JSON IPC. Only the application UUID, display name and diagnostics cross the identity boundary.
+
+## Compatibility
+
+- The app supplies its own `twenty-sdk`, version `>=1.23.0`, with resolvable `twenty-sdk/define` and `twenty-sdk/front-component` entry points. The installed SDK's Node requirement is checked.
+- There is no upper SDK version cap. Every evaluated definition must return the public `ValidationResult` shape: boolean `success`, object `config`, string-array `errors`, and optional string-array `warnings`. An incompatible shape fails with `SDK_SOURCE_UNSUPPORTED`. This validates the loader contract, not every future SDK behavior.
+- The CLI owns esbuild, its TypeScript parser and tinyglobby as runtime dependencies. These load only for source operations. The app does not need to install TypeScript for source loading. Build and typecheck use the project's compiler separately.
+- The pull writer separately checks the authoring exports its generated files use; this loader floor does not establish that every SDK since 1.23 supports all current manifest collections.
+
+## Source contract
+
+Source discovery covers root and nested `.ts`/`.tsx` files, excluding declarations, `node_modules`, `dist` and `.twenty`. Only a direct top-level `export default defineX(...)` is classified as a definition. Aliases, namespace calls and variable re-exports remain unsupported. Helpers reserve their paths without being evaluated on their own; imported helpers run as dependencies of a definition.
+
+Definitions are bundled using the app's tsconfig and imports, then evaluated with a require rooted at the app. React resolves from the app. UI and generated-client imports use extraction stubs; these are not working UI or client implementations. CSS imports are ignored and conditional-availability expressions are transformed for extraction.
+
+An ordinary extraction failure marks a scanned definition unreadable, retaining its path so reconciliation can avoid overwriting it. SDK validation errors leave the config available for reporting. Reading identity evaluates only application definitions, rejects duplicate or invalid application UUIDs, and returns `null` when no application is declared.
+
+The loader checks SDK compatibility, validation-result shape and cancellation between files. Discovery is sorted: the loader, the identity reader and the scanner share `listApplicationSourceFiles`, so results do not depend on filesystem timing. Detection uses the function name rather than its import origin: a local helper named `defineObject`, for example, must be renamed if it returns an incompatible shape. Such a mismatch fails the scan. Source rewriting and reconciliation live in the adjacent `pull` module.
+
+## Verification
+
+Run the source-loader, SDK-resolution and worker tests with the CLI Vitest configuration. The repository-SDK fixture requires its existing SDK/UI/shared artifacts to be built, as do the other CLI app tests. Worker tests use an authoring-only SDK without a project compiler, exercise output and credential isolation, and cover source exits and cancellation.
diff --git a/packages/twenty-cli/src/app/source/__tests__/conditional-availability-transform-plugin.spec.ts b/packages/twenty-cli/src/app/source/__tests__/conditional-availability-transform-plugin.spec.ts
new file mode 100644
index 00000000000..6a28b8c0c59
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/__tests__/conditional-availability-transform-plugin.spec.ts
@@ -0,0 +1,29 @@
+import * as esbuild from 'esbuild';
+import { expect, it } from 'vitest';
+import { conditionalAvailabilityTransformPlugin } from '@/app/source/conditional-availability-transform-plugin';
+
+it('allows other plugins to load virtual TypeScript modules', async () => {
+ const result = await esbuild.build({
+ stdin: { contents: "export { value } from 'generated.ts';" },
+ bundle: true,
+ format: 'esm',
+ write: false,
+ plugins: [
+ conditionalAvailabilityTransformPlugin,
+ {
+ name: 'generated',
+ setup(build) {
+ build.onResolve({ filter: /^generated\.ts$/ }, () => ({
+ path: 'generated.ts',
+ namespace: 'generated',
+ }));
+ build.onLoad({ filter: /.*/, namespace: 'generated' }, () => ({
+ contents: "export const value: string = 'generated';",
+ loader: 'ts',
+ }));
+ },
+ },
+ ],
+ });
+ expect(result.outputFiles[0].text).toContain('generated');
+});
diff --git a/packages/twenty-cli/src/app/source/__tests__/list-application-source-files.spec.ts b/packages/twenty-cli/src/app/source/__tests__/list-application-source-files.spec.ts
new file mode 100644
index 00000000000..06ce8625482
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/__tests__/list-application-source-files.spec.ts
@@ -0,0 +1,49 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { listApplicationSourceFiles } from '@/app/source/list-application-source-files';
+
+describe('listApplicationSourceFiles', () => {
+ let appPath: string;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-source-files-'));
+
+ for (const file of [
+ 'z.tsx',
+ 'b/second.ts',
+ 'a/nested/deep.ts',
+ 'a/first.ts',
+ 'node_modules/package/index.ts',
+ 'types.d.ts',
+ 'dist/output.ts',
+ '.twenty/cli/snapshot.ts',
+ 'notes.md',
+ ]) {
+ await mkdir(dirname(join(appPath, file)), { recursive: true });
+ await writeFile(join(appPath, file), '');
+ }
+ });
+
+ afterEach(async () => {
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('lists app source files in the same sorted order on every run', async () => {
+ const runs = await Promise.all(
+ Array.from({ length: 10 }, () => listApplicationSourceFiles(appPath)),
+ );
+
+ for (const files of runs) {
+ expect(files.map((file) => relative(appPath, file))).toEqual([
+ 'a/first.ts',
+ 'a/nested/deep.ts',
+ 'b/second.ts',
+ 'z.tsx',
+ ]);
+ }
+ });
+});
diff --git a/packages/twenty-cli/src/app/source/__tests__/source-loading.spec.ts b/packages/twenty-cli/src/app/source/__tests__/source-loading.spec.ts
new file mode 100644
index 00000000000..05e30e98c25
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/__tests__/source-loading.spec.ts
@@ -0,0 +1,267 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { stop } from 'esbuild';
+import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { extractDefineEntity } from '@/app/source/extract-define-entity';
+import { extractManifestFromFile } from '@/app/source/extract-manifest-from-file';
+import { readApplicationIdentity } from '@/app/source/read-application-identity';
+import { scanProjectSourceFiles } from '@/app/source/scan-project-source-files';
+import {
+ createSourceTestApp,
+ sourceApplication,
+ SOURCE_TEST_APPLICATION_ID,
+} from '@/app/source/__tests__/utils/create-source-test-app';
+
+describe('CLI app source loading', () => {
+ let appPath: string;
+ let signal: AbortSignal;
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-source-'));
+ signal = new AbortController().signal;
+ await createSourceTestApp(appPath);
+ });
+
+ afterEach(async () => rm(appPath, { recursive: true, force: true }));
+ afterAll(async () => stop());
+
+ it.each(['app.ts', 'src/app.ts'])(
+ 'finds %s, skips output and declarations, and does not execute helper files',
+ async (appFile) => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(join(appPath, appFile), sourceApplication());
+ await writeFile(
+ join(appPath, 'helper.ts'),
+ 'throw new Error("not a definition");',
+ );
+
+ for (const directory of [
+ 'dist',
+ '.twenty',
+ 'node_modules/another-package',
+ ]) {
+ await mkdir(join(appPath, directory), { recursive: true });
+ await writeFile(
+ join(appPath, directory, 'app.ts'),
+ sourceApplication(),
+ );
+ }
+
+ await writeFile(join(appPath, 'extra.d.ts'), sourceApplication());
+ expect(await readApplicationIdentity({ appPath, signal })).toEqual({
+ application: {
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ displayName: 'Source app',
+ },
+ });
+ const files = await scanProjectSourceFiles({ appPath, signal });
+
+ expect(files.map((file) => file.relativePath).sort()).toEqual(
+ [appFile, 'helper.ts'].sort(),
+ );
+ expect(files.find((file) => file.relativePath === 'helper.ts')).toEqual({
+ relativePath: 'helper.ts',
+ entityKey: null,
+ targetFunctionName: null,
+ universalIdentifier: null,
+ isReadable: true,
+ });
+ },
+ );
+
+ it('retains the supported default define-call syntax', () => {
+ expect(
+ extractDefineEntity(
+ '// export default defineObject({});\nexport default defineApplication({});',
+ ),
+ ).toBe('defineApplication');
+ for (const source of [
+ 'export default sdk.defineApplication({});',
+ 'const app = defineApplication({}); export default app;',
+ 'export = defineApplication({});',
+ 'export = defineObject({}); export default defineApplication({});',
+ 'export default renamedDefine({});',
+ 'function helper() { return defineApplication({}); }',
+ ]) {
+ expect(extractDefineEntity(source)).toBeUndefined();
+ }
+ });
+
+ it('distinguishes missing, duplicate, and invalid application identities', async () => {
+ expect(await readApplicationIdentity({ appPath, signal })).toEqual({
+ application: null,
+ });
+ await writeFile(join(appPath, 'app.ts'), sourceApplication());
+ await writeFile(join(appPath, 'other.ts'), sourceApplication());
+ await expect(readApplicationIdentity({ appPath, signal })).rejects.toThrow(
+ 'more than one application',
+ );
+ await rm(join(appPath, 'other.ts'));
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication().replace(SOURCE_TEST_APPLICATION_ID, 'not-a-uuid'),
+ );
+ await expect(readApplicationIdentity({ appPath, signal })).rejects.toThrow(
+ 'Could not read the application identifier in app.ts',
+ );
+ });
+
+ it('evaluates imports and tsconfig aliases while preserving function-valued config in the worker', async () => {
+ await mkdir(join(appPath, 'src'));
+ await writeFile(
+ join(appPath, 'src/constants.ts'),
+ `export const identifier = '${SOURCE_TEST_APPLICATION_ID}';`,
+ );
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: {
+ baseUrl: '.',
+ paths: { '@app/*': ['src/*'] },
+ },
+ }),
+ );
+ await writeFile(
+ join(appPath, 'function.ts'),
+ `
+ import { defineLogicFunction } from 'twenty-sdk/define';
+ import { identifier } from '@app/constants';
+ export default defineLogicFunction({ universalIdentifier: identifier, handler: () => 'kept' });
+ `,
+ );
+ const files = await scanProjectSourceFiles({
+ appPath,
+ signal,
+ includeConfig: true,
+ });
+
+ expect(
+ files.find((file) => file.relativePath === 'function.ts'),
+ ).toMatchObject({
+ entityKey: 'logicFunctions',
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ isReadable: true,
+ config: { handler: expect.any(Function) },
+ });
+ });
+
+ it('mocks UI and generated clients and converts conditional availability without evaluating the expression', async () => {
+ await writeFile(
+ join(appPath, 'command.ts'),
+ `
+ import { defineCommandMenuItem } from 'twenty-sdk/define';
+ import { IconTest } from 'twenty-ui/icon';
+ import { CoreApiClient } from 'twenty-client-sdk/core';
+ import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+ export default defineCommandMenuItem({
+ universalIdentifier: '${SOURCE_TEST_APPLICATION_ID}',
+ component: () => { new CoreApiClient(); new MetadataApiClient(); return IconTest; },
+ conditionalAvailabilityExpression: selectedRecords.length === 1 && !isSelected,
+ });
+ `,
+ );
+ const result = await extractManifestFromFile({
+ appPath,
+ filePath: join(appPath, 'command.ts'),
+ });
+
+ expect(result.config.conditionalAvailabilityExpression).toBe(
+ 'arrayLength(selectedRecords) == 1 and not isSelected',
+ );
+ expect(result.config.component).toBeTypeOf('function');
+ });
+
+ it('keeps an unreadable definition occupied and preserves config even when SDK validation fails', async () => {
+ await writeFile(
+ join(appPath, 'broken.ts'),
+ 'export default defineObject({broken: });',
+ );
+ const sdkPath = join(appPath, 'node_modules/twenty-sdk/define.cjs');
+
+ await writeFile(
+ sdkPath,
+ (await readFile(sdkPath, 'utf8')).replace(
+ 'success: true, config, errors: []',
+ 'success: false, config, errors: ["missing label"]',
+ ),
+ );
+ await writeFile(
+ join(appPath, 'object.ts'),
+ `
+ import { defineObject } from 'twenty-sdk/define';
+ export default defineObject({ universalIdentifier: '${SOURCE_TEST_APPLICATION_ID}' });
+ `,
+ );
+ const files = await scanProjectSourceFiles({
+ appPath,
+ signal,
+ includeConfig: true,
+ });
+
+ expect(
+ files.find((file) => file.relativePath === 'broken.ts'),
+ ).toMatchObject({
+ entityKey: 'objects',
+ isReadable: false,
+ universalIdentifier: null,
+ });
+ expect(
+ files.find((file) => file.relativePath === 'object.ts'),
+ ).toMatchObject({
+ entityKey: 'objects',
+ isReadable: true,
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ });
+ });
+
+ it('reports an incompatible SDK return shape instead of treating it as unreadable source', async () => {
+ await writeFile(
+ join(appPath, 'node_modules/twenty-sdk/define.cjs'),
+ 'exports.defineApplication = (config) => config;',
+ );
+ await writeFile(join(appPath, 'app.ts'), sourceApplication());
+ await expect(
+ scanProjectSourceFiles({ appPath, signal }),
+ ).rejects.toMatchObject({ code: 'SDK_SOURCE_UNSUPPORTED' });
+ });
+
+ it('reloads edited source without using a stale compiled wrapper', async () => {
+ await writeFile(join(appPath, 'app.ts'), sourceApplication());
+ await readApplicationIdentity({ appPath, signal });
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication().replace('Source app', 'Changed app'),
+ );
+ expect(await readApplicationIdentity({ appPath, signal })).toMatchObject({
+ application: { displayName: 'Changed app' },
+ });
+ });
+
+ it('loads the repository SDK and a real React component importing UI CSS', async () => {
+ const fixturePath = fileURLToPath(
+ new URL(
+ '../../../../../twenty-apps/fixtures/minimal-app/',
+ import.meta.url,
+ ),
+ );
+ const identity = await readApplicationIdentity({
+ appPath: fixturePath,
+ signal,
+ });
+ const component = await extractManifestFromFile({
+ appPath: fixturePath,
+ filePath: join(fixturePath, 'my.front-component.tsx'),
+ });
+
+ expect(identity.application?.displayName).toBe('Root App');
+ expect(component.errors).toEqual([]);
+ expect(component.config.universalIdentifier).toBe(
+ 'e1e2e3e4-e5e6-4000-8000-000000000020',
+ );
+ expect(component.config.component).toBeTypeOf('function');
+ }, 30_000);
+});
diff --git a/packages/twenty-cli/src/app/source/__tests__/utils/create-source-test-app.ts b/packages/twenty-cli/src/app/source/__tests__/utils/create-source-test-app.ts
new file mode 100644
index 00000000000..63175ba31a3
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/__tests__/utils/create-source-test-app.ts
@@ -0,0 +1,55 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+export const SOURCE_TEST_APPLICATION_ID =
+ 'e1e2e3e4-e5e6-4000-8000-000000000001';
+
+export const createSourceTestApp = async (appPath: string) => {
+ const sdkPath = join(appPath, 'node_modules', 'twenty-sdk');
+
+ await mkdir(sdkPath, { recursive: true });
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'source-test-app',
+ dependencies: { 'twenty-sdk': '2.44.0' },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version: '2.44.0',
+ exports: {
+ './define': './define.cjs',
+ './front-component': './front-component.cjs',
+ },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'define.cjs'),
+ `
+ const define = (config) => ({ success: true, config, errors: [] });
+ exports.defineApplication = define;
+ exports.defineObject = define;
+ exports.defineLogicFunction = define;
+ exports.defineFrontComponent = define;
+ exports.defineCommandMenuItem = define;
+ `,
+ );
+ await writeFile(
+ join(sdkPath, 'front-component.cjs'),
+ 'exports.useRecord = () => undefined;',
+ );
+
+ return sdkPath;
+};
+
+export const sourceApplication = (extraSource = '') => `
+ import { defineApplication } from 'twenty-sdk/define';
+ ${extraSource}
+ export default defineApplication({
+ universalIdentifier: '${SOURCE_TEST_APPLICATION_ID}',
+ displayName: 'Source app',
+ });
+`;
diff --git a/packages/twenty-cli/src/app/source/application-source-globs.ts b/packages/twenty-cli/src/app/source/application-source-globs.ts
new file mode 100644
index 00000000000..c1e39aa2530
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/application-source-globs.ts
@@ -0,0 +1,8 @@
+export const APPLICATION_SOURCE_GLOBS = ['**/*.ts', '**/*.tsx'];
+
+export const APPLICATION_SOURCE_IGNORED_GLOBS = [
+ '**/node_modules/**',
+ '**/*.d.ts',
+ '**/dist/**',
+ '**/.twenty/**',
+];
diff --git a/packages/twenty-cli/src/app/source/conditional-availability-transform-plugin.ts b/packages/twenty-cli/src/app/source/conditional-availability-transform-plugin.ts
new file mode 100644
index 00000000000..75ad77af76d
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/conditional-availability-transform-plugin.ts
@@ -0,0 +1,30 @@
+import * as fs from 'node:fs/promises';
+
+import type * as esbuild from 'esbuild';
+
+import { transformConditionalAvailabilityExpressionsForEsBuildPlugin } from '@/app/source/transform-conditional-availability-expressions';
+
+export const conditionalAvailabilityTransformPlugin: esbuild.Plugin = {
+ name: 'conditional-availability-transform',
+ setup: (build) => {
+ build.onLoad({ filter: /\.tsx?$/, namespace: 'file' }, async (args) => {
+ const source = await fs.readFile(args.path, 'utf8');
+
+ if (!source.includes('conditionalAvailabilityExpression')) {
+ return null;
+ }
+
+ const transformedSource =
+ transformConditionalAvailabilityExpressionsForEsBuildPlugin(source);
+
+ if (transformedSource === source) {
+ return null;
+ }
+
+ return {
+ contents: transformedSource,
+ loader: args.path.endsWith('.tsx') ? 'tsx' : 'ts',
+ };
+ });
+ },
+};
diff --git a/packages/twenty-cli/src/app/source/extract-define-entity.ts b/packages/twenty-cli/src/app/source/extract-define-entity.ts
new file mode 100644
index 00000000000..2ac0f363f3e
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/extract-define-entity.ts
@@ -0,0 +1,69 @@
+import * as ts from 'typescript';
+
+export const DEFINE_ENTITY_KEYS = {
+ defineApplication: 'application',
+ defineApplicationRole: 'roles',
+ defineField: 'fields',
+ defineIndex: 'indexes',
+ defineLogicFunction: 'logicFunctions',
+ definePostInstallLogicFunction: 'logicFunctions',
+ definePreInstallLogicFunction: 'logicFunctions',
+ defineUninstallLogicFunction: 'logicFunctions',
+ defineHealthCheck: 'logicFunctions',
+ defineObject: 'objects',
+ definePermissionFlag: 'permissionFlags',
+ defineRole: 'roles',
+ defineSkill: 'skills',
+ defineAgent: 'agents',
+ defineConnectionProvider: 'connectionProviders',
+ defineFrontComponent: 'frontComponents',
+ defineSettingsFrontComponent: 'frontComponents',
+ defineView: 'views',
+ defineViewField: 'viewFields',
+ defineNavigationMenuItem: 'navigationMenuItems',
+ definePageLayout: 'pageLayouts',
+ definePageLayoutTab: 'pageLayoutTabs',
+ definePageLayoutWidget: 'pageLayoutWidgets',
+ defineCommandMenuItem: 'commandMenuItems',
+ defineTimelineActivityType: 'timelineActivityTypes',
+ defineSettingsMenuItem: 'settingsMenuItems',
+} as const;
+
+export type TargetFunction = keyof typeof DEFINE_ENTITY_KEYS;
+export type ManifestEntityKey = (typeof DEFINE_ENTITY_KEYS)[TargetFunction];
+
+const isTargetFunction = (name: string): name is TargetFunction =>
+ Object.hasOwn(DEFINE_ENTITY_KEYS, name);
+
+export const extractDefineEntity = (
+ fileContent: string,
+): TargetFunction | undefined => {
+ const sourceFile = ts.createSourceFile(
+ 'temp.ts',
+ fileContent,
+ ts.ScriptTarget.Latest,
+ true,
+ );
+
+ for (const node of sourceFile.statements) {
+ if (!ts.isExportAssignment(node)) {
+ continue;
+ }
+
+ if (node.isExportEquals) {
+ return undefined;
+ }
+
+ const expression = node.expression;
+
+ if (
+ ts.isCallExpression(expression) &&
+ ts.isIdentifier(expression.expression) &&
+ isTargetFunction(expression.expression.text)
+ ) {
+ return expression.expression.text;
+ }
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-cli/src/app/source/extract-manifest-from-file.ts b/packages/twenty-cli/src/app/source/extract-manifest-from-file.ts
new file mode 100644
index 00000000000..5a9067e27c5
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/extract-manifest-from-file.ts
@@ -0,0 +1,193 @@
+import { createHash } from 'node:crypto';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import vm from 'node:vm';
+
+import { isArray, isBoolean, isString } from '@sniptt/guards';
+import * as esbuild from 'esbuild';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { conditionalAvailabilityTransformPlugin } from '@/app/source/conditional-availability-transform-plugin';
+import { type SourceValidationResult } from '@/app/source/types/source-validation-result.type';
+import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';
+import { pathExists } from '@/app/fs-utils';
+import { CliError } from '@/output/cli-error';
+
+type CompiledModuleWrapper = (
+ exports: Record<string, unknown>,
+ require: NodeRequire,
+ module: { exports: Record<string, unknown> },
+ filename: string,
+ dirname: string,
+) => void;
+
+type CachedCompiledModule = {
+ outputHash: string;
+ wrapper: CompiledModuleWrapper;
+};
+
+const compiledModuleCacheByFilePath = new Map<string, CachedCompiledModule>();
+
+const getCompiledWrapper = (
+ code: string,
+ filePath: string,
+): CompiledModuleWrapper => {
+ const outputHash = createHash('sha1').update(code).digest('hex');
+
+ const cachedModule = compiledModuleCacheByFilePath.get(filePath);
+
+ if (isDefined(cachedModule) && cachedModule.outputHash === outputHash) {
+ return cachedModule.wrapper;
+ }
+
+ const compiledWrapper = vm.compileFunction(
+ code,
+ ['exports', 'require', 'module', '__filename', '__dirname'],
+ { filename: filePath },
+ ) as unknown as CompiledModuleWrapper;
+
+ compiledModuleCacheByFilePath.set(filePath, {
+ outputHash,
+ wrapper: compiledWrapper,
+ });
+
+ return compiledWrapper;
+};
+
+const MANIFEST_MOCK_MODULES = [
+ 'twenty-ui',
+ 'twenty-client-sdk/core',
+ 'twenty-client-sdk/metadata',
+];
+
+const escapeRegExp = (value: string): string =>
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+const manifestMockPlugin: esbuild.Plugin = {
+ name: 'manifest-mock',
+ setup: (build) => {
+ const escapedModules = MANIFEST_MOCK_MODULES.map(escapeRegExp);
+ const filter = new RegExp(`^(${escapedModules.join('|')})(/.*)?$`);
+
+ build.onResolve({ filter }, ({ path: modulePath }) => {
+ if (modulePath.endsWith('.css')) {
+ return null;
+ }
+
+ return {
+ path: modulePath,
+ namespace: 'manifest-mock',
+ };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'manifest-mock' }, () => ({
+ contents: 'module.exports = new Proxy({}, { get: () => () => {} });',
+ loader: 'js',
+ }));
+ },
+};
+
+export const extractManifestFromFile = async <
+ TConfig = Record<string, unknown>,
+>({
+ filePath,
+ appPath,
+}: {
+ filePath: string;
+ appPath: string;
+}): Promise<SourceValidationResult<TConfig>> => {
+ const module = await loadModule({ filePath, appPath });
+
+ return extractDefaultConfigFromModuleOrThrow(
+ module,
+ filePath,
+ ) as SourceValidationResult<TConfig>;
+};
+
+const loadModule = async ({
+ filePath,
+ appPath,
+}: {
+ filePath: string;
+ appPath: string;
+}): Promise<Record<string, unknown>> => {
+ const tsconfigPath = path.join(appPath, 'tsconfig.json');
+ const hasTsconfig = await pathExists(tsconfigPath);
+
+ const appRequire = createRequire(path.join(appPath, 'package.json'));
+ let reactPath: string | undefined;
+ let reactDomPath: string | undefined;
+
+ try {
+ reactPath = path.dirname(appRequire.resolve('react/package.json'));
+ reactDomPath = path.dirname(appRequire.resolve('react-dom/package.json'));
+ } catch {}
+
+ const result = await esbuild.build({
+ entryPoints: [filePath],
+ bundle: true,
+ write: false,
+ format: 'cjs',
+ platform: 'node',
+ target: 'node18',
+ jsx: 'automatic',
+ tsconfig: hasTsconfig ? tsconfigPath : undefined,
+ loader: { '.css': 'empty' },
+ alias: {
+ ...(reactPath && { react: reactPath }),
+ ...(reactDomPath && { 'react-dom': reactDomPath }),
+ },
+ plugins: [
+ ...getWatchInputPlugins(),
+ conditionalAvailabilityTransformPlugin,
+ manifestMockPlugin,
+ ],
+ logLevel: 'silent',
+ });
+
+ const code = result.outputFiles[0].text;
+
+ const compiledWrapper = getCompiledWrapper(code, filePath);
+
+ const moduleShim: { exports: Record<string, unknown> } = { exports: {} };
+
+ compiledWrapper(
+ moduleShim.exports,
+ appRequire,
+ moduleShim,
+ filePath,
+ path.dirname(filePath),
+ );
+
+ return moduleShim.exports;
+};
+
+const extractDefaultConfigFromModuleOrThrow = (
+ module: Record<string, unknown>,
+ filePath: string,
+): SourceValidationResult => {
+ const result = module.default;
+
+ if (
+ isPlainObject(result) &&
+ isBoolean(result.success) &&
+ isPlainObject(result.config) &&
+ isArray(result.errors) &&
+ result.errors.every(isString) &&
+ (!isDefined(result.warnings) ||
+ (isArray(result.warnings) && result.warnings.every(isString)))
+ ) {
+ return {
+ success: result.success,
+ config: result.config,
+ errors: result.errors,
+ ...(isDefined(result.warnings) ? { warnings: result.warnings } : {}),
+ };
+ }
+
+ throw new CliError({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ message: `The definition in ${filePath} must export a twenty-sdk ValidationResult with success, config and errors.`,
+ hint: 'Use the SDK define functions, rename local helpers with the same names, or install a compatible twenty-sdk version.',
+ });
+};
diff --git a/packages/twenty-cli/src/app/source/list-application-source-files.ts b/packages/twenty-cli/src/app/source/list-application-source-files.ts
new file mode 100644
index 00000000000..873887f50ef
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/list-application-source-files.ts
@@ -0,0 +1,18 @@
+import { glob } from 'tinyglobby';
+
+import {
+ APPLICATION_SOURCE_GLOBS,
+ APPLICATION_SOURCE_IGNORED_GLOBS,
+} from '@/app/source/application-source-globs';
+
+export const listApplicationSourceFiles = async (
+ appPath: string,
+): Promise<string[]> =>
+ (
+ await glob(APPLICATION_SOURCE_GLOBS, {
+ cwd: appPath,
+ absolute: true,
+ ignore: APPLICATION_SOURCE_IGNORED_GLOBS,
+ onlyFiles: true,
+ })
+ ).sort();
diff --git a/packages/twenty-cli/src/app/source/read-application-identity.ts b/packages/twenty-cli/src/app/source/read-application-identity.ts
new file mode 100644
index 00000000000..613a203caf3
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/read-application-identity.ts
@@ -0,0 +1,63 @@
+import { readFile, stat } from 'node:fs/promises';
+import { isAbsolute, relative } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { extractDefineEntity } from '@/app/source/extract-define-entity';
+import { extractManifestFromFile } from '@/app/source/extract-manifest-from-file';
+import { listApplicationSourceFiles } from '@/app/source/list-application-source-files';
+import { type AppSourceIdentity } from '@/app/source/types/app-source-identity.type';
+
+export const readApplicationIdentity = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+}): Promise<AppSourceIdentity> => {
+ signal.throwIfAborted();
+
+ if (!isAbsolute(appPath) || !(await stat(appPath)).isDirectory()) {
+ throw new Error('The app path must be an absolute directory path.');
+ }
+
+ const filePaths = await listApplicationSourceFiles(appPath);
+ let application: AppSourceIdentity['application'] = null;
+
+ for (const filePath of filePaths) {
+ signal.throwIfAborted();
+
+ if (
+ extractDefineEntity(await readFile(filePath, 'utf8')) !==
+ 'defineApplication'
+ ) {
+ continue;
+ }
+
+ if (isDefined(application)) {
+ throw new Error('The project declares more than one application.');
+ }
+
+ const { config } = await extractManifestFromFile({ appPath, filePath });
+
+ if (
+ !isString(config.universalIdentifier) ||
+ !isValidUniversalIdentifier(config.universalIdentifier)
+ ) {
+ throw new Error(
+ `Could not read the application identifier in ${relative(appPath, filePath)}.`,
+ );
+ }
+
+ application = {
+ universalIdentifier: config.universalIdentifier,
+ displayName: isString(config.displayName) ? config.displayName : null,
+ };
+ }
+
+ signal.throwIfAborted();
+
+ return { application };
+};
diff --git a/packages/twenty-cli/src/app/source/scan-project-source-files.ts b/packages/twenty-cli/src/app/source/scan-project-source-files.ts
new file mode 100644
index 00000000000..dff4b2f1c04
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/scan-project-source-files.ts
@@ -0,0 +1,112 @@
+import { readFile } from 'node:fs/promises';
+import { relative } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ DEFINE_ENTITY_KEYS,
+ extractDefineEntity,
+ type ManifestEntityKey,
+ type TargetFunction,
+} from '@/app/source/extract-define-entity';
+import { extractManifestFromFile } from '@/app/source/extract-manifest-from-file';
+import { listApplicationSourceFiles } from '@/app/source/list-application-source-files';
+import { CliError } from '@/output/cli-error';
+
+export type ScannedSourceFile = {
+ relativePath: string;
+ entityKey: ManifestEntityKey | null;
+ targetFunctionName: TargetFunction | null;
+ universalIdentifier: string | null;
+ isReadable: boolean;
+ config?: unknown;
+};
+
+export const scanProjectSourceFiles = async ({
+ appPath,
+ includeConfig = false,
+ signal,
+}: {
+ appPath: string;
+ includeConfig?: boolean;
+ signal: AbortSignal;
+}): Promise<ScannedSourceFile[]> => {
+ signal.throwIfAborted();
+
+ const filePaths = await listApplicationSourceFiles(appPath);
+
+ const scannedFiles: ScannedSourceFile[] = [];
+
+ for (const filePath of filePaths) {
+ signal.throwIfAborted();
+ const relativePath = relative(appPath, filePath);
+
+ let fileContent: string;
+
+ try {
+ fileContent = await readFile(filePath, 'utf-8');
+ } catch {
+ scannedFiles.push({
+ relativePath,
+ entityKey: null,
+ targetFunctionName: null,
+ universalIdentifier: null,
+ isReadable: false,
+ });
+ continue;
+ }
+
+ const targetFunctionName = extractDefineEntity(fileContent);
+
+ if (!isDefined(targetFunctionName)) {
+ scannedFiles.push({
+ relativePath,
+ entityKey: null,
+ targetFunctionName: null,
+ universalIdentifier: null,
+ isReadable: true,
+ });
+ continue;
+ }
+
+ const entityKey = DEFINE_ENTITY_KEYS[targetFunctionName];
+
+ let config: Record<string, unknown> = {};
+ let isReadable = true;
+
+ try {
+ const extract = await extractManifestFromFile({
+ appPath,
+ filePath,
+ });
+
+ config = extract.config;
+ } catch (error) {
+ if (
+ error instanceof CliError &&
+ error.code === 'SDK_SOURCE_UNSUPPORTED'
+ ) {
+ throw error;
+ }
+
+ config = {};
+ isReadable = false;
+ }
+
+ scannedFiles.push({
+ relativePath,
+ entityKey,
+ targetFunctionName,
+ universalIdentifier: isString(config.universalIdentifier)
+ ? config.universalIdentifier
+ : null,
+ isReadable,
+ ...(includeConfig ? { config } : {}),
+ });
+ }
+
+ signal.throwIfAborted();
+
+ return scannedFiles;
+};
diff --git a/packages/twenty-cli/src/app/source/to-expr-eval.ts b/packages/twenty-cli/src/app/source/to-expr-eval.ts
new file mode 100644
index 00000000000..18c09fd7661
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/to-expr-eval.ts
@@ -0,0 +1,16 @@
+const ARRAY_LENGTH_REPLACEMENTS: [RegExp, string][] = [
+ [/\bfavoriteRecordIds\.length\b/g, 'arrayLength(favoriteRecordIds)'],
+ [/\bselectedRecords\.length\b/g, 'arrayLength(selectedRecords)'],
+];
+
+export const toExprEval = (raw: string): string =>
+ ARRAY_LENGTH_REPLACEMENTS.reduce(
+ (acc, [pattern, replacement]) => acc.replace(pattern, replacement),
+ raw
+ .replace(/!==/g, '!=')
+ .replace(/===/g, '==')
+ .replace(/&&/g, 'and')
+ .replace(/\|\|/g, 'or')
+ .replace(/!(?!=)/g, 'not ')
+ .replace(/,(\s*\))/g, '$1'),
+ );
diff --git a/packages/twenty-cli/src/app/source/transform-conditional-availability-expressions.ts b/packages/twenty-cli/src/app/source/transform-conditional-availability-expressions.ts
new file mode 100644
index 00000000000..75ea129c98c
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/transform-conditional-availability-expressions.ts
@@ -0,0 +1,13 @@
+import { toExprEval } from '@/app/source/to-expr-eval';
+
+const CONDITIONAL_AVAILABILITY_EXPRESSION_PATTERN =
+ /(conditionalAvailabilityExpression\s*:\s*)(?!['"`])((?:[^,}()]|\([^()]*\))+)/g;
+
+export const transformConditionalAvailabilityExpressionsForEsBuildPlugin = (
+ source: string,
+): string =>
+ source.replace(
+ CONDITIONAL_AVAILABILITY_EXPRESSION_PATTERN,
+ (_, prefix: string, rawExpression: string) =>
+ prefix + JSON.stringify(toExprEval(rawExpression.trim())),
+ );
diff --git a/packages/twenty-cli/src/app/source/types/app-source-identity.type.ts b/packages/twenty-cli/src/app/source/types/app-source-identity.type.ts
new file mode 100644
index 00000000000..f63bdae83e3
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/types/app-source-identity.type.ts
@@ -0,0 +1,6 @@
+export type AppSourceIdentity = {
+ application: {
+ universalIdentifier: string;
+ displayName: string | null;
+ } | null;
+};
diff --git a/packages/twenty-cli/src/app/source/types/source-validation-result.type.ts b/packages/twenty-cli/src/app/source/types/source-validation-result.type.ts
new file mode 100644
index 00000000000..aa7b697df65
--- /dev/null
+++ b/packages/twenty-cli/src/app/source/types/source-validation-result.type.ts
@@ -0,0 +1,6 @@
+export type SourceValidationResult<TConfig = Record<string, unknown>> = {
+ success: boolean;
+ config: TConfig;
+ errors: string[];
+ warnings?: string[];
+};
diff --git a/packages/twenty-cli/src/app/to-worker-output-diagnostics.ts b/packages/twenty-cli/src/app/to-worker-output-diagnostics.ts
new file mode 100644
index 00000000000..ddb57a1e24d
--- /dev/null
+++ b/packages/twenty-cli/src/app/to-worker-output-diagnostics.ts
@@ -0,0 +1,20 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type AppWorkerOutput } from '@/app/types/app-worker-output.type';
+import { type ToolingDiagnostic } from '@/app/types/tooling-result.type';
+
+export const toWorkerOutputDiagnostics = (
+ output: AppWorkerOutput,
+): ToolingDiagnostic[] =>
+ (
+ [
+ ['stdout', output.stdout],
+ ['stderr', output.stderr],
+ ] as const
+ )
+ .filter(([, text]) => isNonEmptyString(text.trim()))
+ .map(([stream, text]) => ({
+ severity: 'warning',
+ code: 'PROJECT_OUTPUT',
+ message: `The app or twenty-sdk wrote to ${stream}:\n${text.trimEnd()}${output.isTruncated ? '\n(output truncated)' : ''}`,
+ }));
diff --git a/packages/twenty-cli/src/app/translations/__tests__/collect-front-component-strings.spec.ts b/packages/twenty-cli/src/app/translations/__tests__/collect-front-component-strings.spec.ts
new file mode 100644
index 00000000000..146d3b02020
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/__tests__/collect-front-component-strings.spec.ts
@@ -0,0 +1,160 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { collectFrontComponentStrings } from '@/app/translations/collect-front-component-strings';
+
+const directories: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true })),
+ );
+});
+
+const writeFrontComponent = async (source: string): Promise<string> => {
+ const dir = await mkdtemp(join(tmpdir(), 'twenty-fc-translations-'));
+ directories.push(dir);
+ const filePath = join(dir, 'my.front-component.tsx');
+
+ await writeFile(filePath, source);
+
+ return filePath;
+};
+
+describe('collectFrontComponentStrings', () => {
+ it('returns nothing when there are no source files', async () => {
+ expect(await collectFrontComponentStrings([])).toEqual([]);
+ });
+
+ it('extracts t(), msg() and <Trans> static strings with context', async () => {
+ const filePath = await writeFrontComponent(`
+ import { t, msg, Trans, useTranslate } from 'twenty-sdk/front-component';
+
+ const STATUS = msg('Draft');
+
+ const Component = () => {
+ const { t: translate } = useTranslate();
+
+ const label = t('No content yet');
+ const verb = t({ message: 'Open', context: 'door' });
+
+ return (
+ <div title={label}>
+ <Trans>Welcome back</Trans>
+ <Trans context="card">Untitled</Trans>
+ <Trans message="Hi {name}" values={{ name: 'Ada' }} />
+ <span>{translate(STATUS)}</span>
+ </div>
+ );
+ };
+
+ export default defineFrontComponent({ component: Component });
+ `);
+
+ const result = await collectFrontComponentStrings([filePath]);
+
+ expect(result).toEqual(
+ expect.arrayContaining([
+ { message: 'Draft' },
+ { message: 'No content yet' },
+ { message: 'Open', context: 'door' },
+ { message: 'Welcome back' },
+ { message: 'Untitled', context: 'card' },
+ { message: 'Hi {name}' },
+ ]),
+ );
+ expect(result).toHaveLength(6);
+ });
+
+ it('collapses whitespace in multi-line <Trans> static text', async () => {
+ const filePath = await writeFrontComponent(`
+ import { Trans } from 'twenty-sdk/front-component';
+
+ const Component = () => (
+ <p>
+ <Trans>
+ Welcome
+ back
+ </Trans>
+ </p>
+ );
+
+ export default defineFrontComponent({ component: Component });
+ `);
+
+ expect(await collectFrontComponentStrings([filePath])).toEqual([
+ { message: 'Welcome back' },
+ ]);
+ });
+
+ it('skips dynamic arguments and interpolated children that cannot be statically extracted', async () => {
+ const filePath = await writeFrontComponent(`
+ import { t, Trans } from 'twenty-sdk/front-component';
+
+ const Component = ({ name }: { name: string }) => {
+ const dynamic = t(name);
+
+ return (
+ <div title={dynamic}>
+ <Trans>Hello {name}</Trans>
+ </div>
+ );
+ };
+
+ export default defineFrontComponent({ component: Component });
+ `);
+
+ expect(await collectFrontComponentStrings([filePath])).toEqual([]);
+ });
+
+ it('dedupes identical message/context pairs across files', async () => {
+ const first = await writeFrontComponent(`
+ import { t } from 'twenty-sdk/front-component';
+ export const a = () => t('Save');
+ `);
+ const second = await writeFrontComponent(`
+ import { t } from 'twenty-sdk/front-component';
+ export const b = () => t('Save');
+ `);
+
+ expect(await collectFrontComponentStrings([first, second])).toEqual([
+ { message: 'Save' },
+ ]);
+ });
+ it('visits nested calls and JSX children even when their parent cannot be extracted', async () => {
+ const filePath = await writeFrontComponent(`
+ t(wrap(msg('Nested call')));
+ <Trans>{msg('Nested expression')}</Trans>;
+ <Trans><Trans>Nested element</Trans></Trans>;
+ <div><Trans message={'Static attribute'} context={'card'} /></div>;
+ `);
+ expect(await collectFrontComponentStrings([filePath])).toEqual([
+ { message: 'Nested call' },
+ { message: 'Nested expression' },
+ { message: 'Nested element' },
+ { message: 'Static attribute', context: 'card' },
+ ]);
+ });
+
+ it('uses identifier keys and the first matching property in message descriptors', async () => {
+ const filePath = await writeFrontComponent(String.raw`
+ t({ 'message': 'Quoted' });
+ t({ ['message']: 'Computed' });
+ t({ message, message: 'Later property' });
+ t({ get message() { return 'Getter'; }, message: 'Later property' });
+ t({ message: 'First property', message: 'Later property' });
+ t({ \u006dessage: 'Escaped name' });
+ \u0074('Escaped callee');
+ `);
+ expect(await collectFrontComponentStrings([filePath])).toEqual([
+ { message: 'First property' },
+ { message: 'Escaped name' },
+ { message: 'Escaped callee' },
+ ]);
+ });
+});
diff --git a/packages/twenty-cli/src/app/translations/__tests__/compile-application-translations.spec.ts b/packages/twenty-cli/src/app/translations/__tests__/compile-application-translations.spec.ts
new file mode 100644
index 00000000000..952cf4ddd7d
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/__tests__/compile-application-translations.spec.ts
@@ -0,0 +1,175 @@
+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { generateMessageId } from 'twenty-shared/i18n';
+import { compileApplicationTranslations } from '@/app/translations/compile-application-translations';
+
+describe('compileApplicationTranslations', () => {
+ it('compiles catalogs keyed by message id, skipping source locale and empty values', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-translations-'));
+ const localesDir = join(appPath, 'locales');
+
+ await mkdir(localesDir, { recursive: true });
+ await writeFile(
+ join(localesDir, 'fr-FR.json'),
+ JSON.stringify({ Company: 'Entreprise', Untranslated: '' }),
+ );
+ await writeFile(
+ join(localesDir, 'en.json'),
+ JSON.stringify({ Company: 'Company' }),
+ );
+
+ const result = await compileApplicationTranslations({ appPath });
+
+ expect(result).toEqual({
+ 'fr-FR': { [generateMessageId('Company')]: 'Entreprise' },
+ });
+ });
+
+ it('hashes a context-qualified key with its context so it matches the server lookup', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-context-'),
+ );
+ const localesDir = join(appPath, 'locales');
+
+ await mkdir(localesDir, { recursive: true });
+ await writeFile(
+ join(localesDir, 'fr-FR.json'),
+ JSON.stringify({
+ door: { Open: 'Ouvrir' },
+ }),
+ );
+
+ const result = await compileApplicationTranslations({ appPath });
+
+ expect(result).toEqual({
+ 'fr-FR': { [generateMessageId('Open', 'door')]: 'Ouvrir' },
+ });
+ });
+
+ it('declares nothing when there is no locales directory, so the sync leaves stored translations alone', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-translations-empty-'));
+
+ expect(await compileApplicationTranslations({ appPath })).toBeUndefined();
+ });
+
+ it('declares zero locales when the locales directory exists but holds none', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-no-locale-'),
+ );
+
+ await mkdir(join(appPath, 'locales'), { recursive: true });
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({});
+ });
+
+ it('declares zero locales when only the source locale is present', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-source-only-'),
+ );
+ const localesDir = join(appPath, 'locales');
+
+ await mkdir(localesDir, { recursive: true });
+ await writeFile(
+ join(localesDir, 'en.json'),
+ JSON.stringify({ Company: 'Company' }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({});
+ });
+
+ it('merges compiled catalogs and lets an authored entry win on the same id', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-translations-merge-'));
+ const localesDir = join(appPath, 'locales');
+ await mkdir(join(localesDir, 'compiled'), { recursive: true });
+ await writeFile(
+ join(localesDir, 'fr-FR.json'),
+ JSON.stringify({ Company: 'Entreprise' }),
+ );
+ await writeFile(
+ join(localesDir, 'compiled', 'fr-FR.json'),
+ JSON.stringify({
+ [generateMessageId('Company')]: 'Société',
+ zzzzzz: 'orphan',
+ }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({
+ 'fr-FR': {
+ [generateMessageId('Company')]: 'Entreprise',
+ zzzzzz: 'orphan',
+ },
+ });
+ });
+
+ it('declares a locale that only has a compiled catalog', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-compiled-only-'),
+ );
+ await mkdir(join(appPath, 'locales', 'compiled'), { recursive: true });
+ await writeFile(
+ join(appPath, 'locales', 'compiled', 'de-DE.json'),
+ JSON.stringify({ zzzzzz: 'Waise' }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({
+ 'de-DE': { zzzzzz: 'Waise' },
+ });
+ });
+
+ it('skips empty compiled entries and compiled files of unsupported locales', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-compiled-skip-'),
+ );
+ await mkdir(join(appPath, 'locales', 'compiled'), { recursive: true });
+ await writeFile(
+ join(appPath, 'locales', 'compiled', 'fr-FR.json'),
+ JSON.stringify({ aaaaaa: '', bbbbbb: 'kept' }),
+ );
+ await writeFile(
+ join(appPath, 'locales', 'compiled', 'klingon.json'),
+ JSON.stringify({ cccccc: 'nuqneH' }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({
+ 'fr-FR': { bbbbbb: 'kept' },
+ });
+ });
+
+ it('skips a locale file whose JSON is not an object', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-not-object-'),
+ );
+ const localesDir = join(appPath, 'locales');
+ await mkdir(localesDir, { recursive: true });
+ await writeFile(join(localesDir, 'fr-FR.json'), JSON.stringify(''));
+ await writeFile(join(localesDir, 'de-DE.json'), JSON.stringify(['x']));
+ await writeFile(
+ join(localesDir, 'it-IT.json'),
+ JSON.stringify({ Company: 'Azienda' }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({
+ 'it-IT': { [generateMessageId('Company')]: 'Azienda' },
+ });
+ });
+
+ it('skips a locale file that cannot be parsed', async () => {
+ const appPath = await mkdtemp(
+ join(tmpdir(), 'twenty-translations-unparsable-'),
+ );
+ const localesDir = join(appPath, 'locales');
+ await mkdir(join(localesDir, 'compiled'), { recursive: true });
+ await writeFile(join(localesDir, 'fr-FR.json'), '');
+ await writeFile(join(localesDir, 'compiled', 'de-DE.json'), '{');
+ await writeFile(
+ join(localesDir, 'it-IT.json'),
+ JSON.stringify({ Company: 'Azienda' }),
+ );
+
+ expect(await compileApplicationTranslations({ appPath })).toEqual({
+ 'it-IT': { [generateMessageId('Company')]: 'Azienda' },
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/app/translations/__tests__/compile-catalog-to-message-ids.spec.ts b/packages/twenty-cli/src/app/translations/__tests__/compile-catalog-to-message-ids.spec.ts
new file mode 100644
index 00000000000..124faa3d47c
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/__tests__/compile-catalog-to-message-ids.spec.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { generateMessageId } from 'twenty-shared/i18n';
+
+import { compileCatalogToMessageIds } from '@/app/translations/compile-catalog-to-message-ids';
+
+describe('compileCatalogToMessageIds', () => {
+ it('keys translations by message id, honoring context groups', () => {
+ const compiled = compileCatalogToMessageIds({
+ catalog: {
+ Export: 'Exporter',
+ 'view.name': { Export: 'Export de vue' },
+ },
+ });
+
+ expect(compiled).toEqual({
+ [generateMessageId('Export')]: 'Exporter',
+ [generateMessageId('Export', 'view.name')]: 'Export de vue',
+ });
+ });
+
+ it('skips empty and non-string translations', () => {
+ const compiled = compileCatalogToMessageIds({
+ catalog: {
+ Export: '',
+ Import: 42,
+ Delete: 'Supprimer',
+ 'view.name': { Untranslated: '' },
+ },
+ });
+
+ expect(compiled).toEqual({ [generateMessageId('Delete')]: 'Supprimer' });
+ });
+
+ it('reports a collision and keeps the later entry', () => {
+ const onCollision = vi.fn();
+
+ // An empty-string context group hashes like no context at all, so two
+ // distinct authored entries can claim one message id.
+ const compiled = compileCatalogToMessageIds({
+ catalog: {
+ Export: 'first',
+ '': { Export: 'second' },
+ },
+ onCollision,
+ });
+
+ expect(onCollision).toHaveBeenCalledWith({
+ messageId: generateMessageId('Export'),
+ keptKey: ' Export',
+ droppedKey: 'Export',
+ });
+ expect(compiled).toEqual({ [generateMessageId('Export')]: 'second' });
+ });
+});
diff --git a/packages/twenty-cli/src/app/translations/collect-front-component-strings.ts b/packages/twenty-cli/src/app/translations/collect-front-component-strings.ts
new file mode 100644
index 00000000000..a767e1bd894
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/collect-front-component-strings.ts
@@ -0,0 +1,241 @@
+import { readFile } from 'node:fs/promises';
+
+import * as ts from 'typescript';
+
+import {
+ getTranslationCatalogKey,
+ normalizeMessageWhitespace,
+ type MessageDescriptor,
+} from '@/app/translations/message';
+
+const TRANSLATION_FUNCTION_NAMES = new Set(['t', 'msg']);
+const TRANS_COMPONENT_NAME = 'Trans';
+
+const getStringLiteralValue = (
+ node: ts.Node | undefined,
+): string | undefined => {
+ if (node === undefined) {
+ return undefined;
+ }
+
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
+ return node.text;
+ }
+
+ return undefined;
+};
+
+// Only static string literals are extractable; dynamic arguments are skipped.
+const extractFromCallArgument = (
+ argument: ts.Node | undefined,
+): MessageDescriptor | undefined => {
+ if (argument === undefined) {
+ return undefined;
+ }
+
+ const literalMessage = getStringLiteralValue(argument);
+
+ if (literalMessage !== undefined) {
+ return { message: literalMessage };
+ }
+
+ if (!ts.isObjectLiteralExpression(argument)) {
+ return undefined;
+ }
+
+ const messageProperty = argument.properties.find(
+ (property) =>
+ property.name !== undefined &&
+ ts.isIdentifier(property.name) &&
+ property.name.text === 'message',
+ );
+
+ if (
+ messageProperty === undefined ||
+ !ts.isPropertyAssignment(messageProperty)
+ ) {
+ return undefined;
+ }
+
+ const message = getStringLiteralValue(messageProperty.initializer);
+
+ if (message === undefined) {
+ return undefined;
+ }
+
+ const contextProperty = argument.properties.find(
+ (property) =>
+ property.name !== undefined &&
+ ts.isIdentifier(property.name) &&
+ property.name.text === 'context',
+ );
+ const context =
+ contextProperty !== undefined && ts.isPropertyAssignment(contextProperty)
+ ? getStringLiteralValue(contextProperty.initializer)
+ : undefined;
+
+ return context !== undefined ? { message, context } : { message };
+};
+
+const getJsxAttributeStringValue = (
+ element: ts.JsxOpeningElement | ts.JsxSelfClosingElement,
+ name: string,
+): string | undefined => {
+ const attribute = element.attributes.properties.find(
+ (property) =>
+ ts.isJsxAttribute(property) && property.name.getText() === name,
+ );
+
+ if (attribute === undefined || !ts.isJsxAttribute(attribute)) {
+ return undefined;
+ }
+
+ const initializer = attribute.initializer;
+
+ if (initializer === undefined) {
+ return undefined;
+ }
+
+ if (ts.isStringLiteral(initializer)) {
+ return initializer.text;
+ }
+
+ if (ts.isJsxExpression(initializer)) {
+ return getStringLiteralValue(initializer.expression);
+ }
+
+ return undefined;
+};
+
+const getTransChildrenText = (element: ts.JsxElement): string | undefined => {
+ const children = element.children;
+
+ const hasDynamicChild = children.some(
+ (child) =>
+ ts.isJsxExpression(child) ||
+ ts.isJsxElement(child) ||
+ ts.isJsxSelfClosingElement(child),
+ );
+
+ if (hasDynamicChild) {
+ return undefined;
+ }
+
+ const text = normalizeMessageWhitespace(
+ children
+ .filter((child) => ts.isJsxText(child))
+ .map((child) => child.getText())
+ .join(''),
+ );
+
+ return text.length > 0 ? text : undefined;
+};
+
+const dedupeByCatalogKey = (
+ descriptors: MessageDescriptor[],
+): MessageDescriptor[] => {
+ const descriptorByKey = new Map<string, MessageDescriptor>();
+
+ for (const descriptor of descriptors) {
+ descriptorByKey.set(
+ getTranslationCatalogKey(descriptor.message, descriptor.context),
+ descriptor,
+ );
+ }
+
+ return [...descriptorByKey.values()];
+};
+
+export const collectFrontComponentStrings = async (
+ sourceFilePaths: string[],
+): Promise<MessageDescriptor[]> => {
+ if (sourceFilePaths.length === 0) {
+ return [];
+ }
+
+ const descriptors: MessageDescriptor[] = [];
+
+ for (let index = 0; index < sourceFilePaths.length; index++) {
+ let content: string;
+
+ try {
+ content = await readFile(sourceFilePaths[index], 'utf8');
+ } catch {
+ continue;
+ }
+
+ const sourceFile = ts.createSourceFile(
+ `front-component-${index}.tsx`,
+ content,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+
+ const collectFromNode = (node: ts.Node): void => {
+ if (ts.isCallExpression(node)) {
+ const expression = node.expression;
+
+ if (
+ ts.isIdentifier(expression) &&
+ TRANSLATION_FUNCTION_NAMES.has(expression.text)
+ ) {
+ const descriptor = extractFromCallArgument(node.arguments[0]);
+
+ if (descriptor !== undefined) {
+ descriptors.push(descriptor);
+ }
+ }
+
+ return;
+ }
+
+ if (ts.isJsxSelfClosingElement(node)) {
+ if (node.tagName.getText() !== TRANS_COMPONENT_NAME) {
+ return;
+ }
+
+ const message = getJsxAttributeStringValue(node, 'message');
+
+ if (message !== undefined && message.length > 0) {
+ const context = getJsxAttributeStringValue(node, 'context');
+
+ descriptors.push(
+ context !== undefined ? { message, context } : { message },
+ );
+ }
+
+ return;
+ }
+
+ if (ts.isJsxElement(node)) {
+ const openingElement = node.openingElement;
+
+ if (openingElement.tagName.getText() !== TRANS_COMPONENT_NAME) {
+ return;
+ }
+
+ const message =
+ getJsxAttributeStringValue(openingElement, 'message') ??
+ getTransChildrenText(node);
+
+ if (message !== undefined && message.length > 0) {
+ const context = getJsxAttributeStringValue(openingElement, 'context');
+
+ descriptors.push(
+ context !== undefined ? { message, context } : { message },
+ );
+ }
+ }
+ };
+
+ const visit = (node: ts.Node): void => {
+ collectFromNode(node);
+ ts.forEachChild(node, visit);
+ };
+
+ ts.forEachChild(sourceFile, visit);
+ }
+
+ return dedupeByCatalogKey(descriptors);
+};
diff --git a/packages/twenty-cli/src/app/translations/collect-translatable-strings.ts b/packages/twenty-cli/src/app/translations/collect-translatable-strings.ts
new file mode 100644
index 00000000000..e25d8d75c7e
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/collect-translatable-strings.ts
@@ -0,0 +1,100 @@
+import { type Manifest } from 'twenty-shared/application';
+import {
+ getMetadataLabelContext,
+ TRANSLATABLE_PROPERTIES_BY_METADATA_NAME,
+ type TranslatableMetadataName,
+} from 'twenty-shared/i18n';
+
+import { type MessageDescriptor } from '@/app/translations/message';
+
+// Which manifest collection carries which metadata entity. The properties to
+// extract are not listed here on purpose: they come from the shared registry,
+// so extraction matches what the server resolves at runtime.
+// Metadata names with no manifest collection (viewFieldGroup) are simply absent.
+const MANIFEST_KEY_BY_METADATA_NAME = {
+ objectMetadata: 'objects',
+ fieldMetadata: 'fields',
+ view: 'views',
+ pageLayout: 'pageLayouts',
+ pageLayoutTab: 'pageLayoutTabs',
+ pageLayoutWidget: 'pageLayoutWidgets',
+ commandMenuItem: 'commandMenuItems',
+ navigationMenuItem: 'navigationMenuItems',
+ timelineActivityType: 'timelineActivityTypes',
+ settingsMenuItem: 'settingsMenuItems',
+} as const satisfies Partial<Record<TranslatableMetadataName, keyof Manifest>>;
+
+export const collectTranslatableStrings = (
+ manifest: Manifest,
+): MessageDescriptor[] => {
+ // The same string can label several roles ('Invoice' as an object name and a
+ // field label), and each role is its own catalog entry, so descriptors are
+ // deduplicated per (context, message) rather than per message.
+ const descriptorByKey = new Map<string, MessageDescriptor>();
+
+ const addEntityStrings = (
+ entity: unknown,
+ metadataName: TranslatableMetadataName,
+ ) => {
+ if (entity === null || typeof entity !== 'object') {
+ return;
+ }
+
+ for (const property of TRANSLATABLE_PROPERTIES_BY_METADATA_NAME[
+ metadataName
+ ]) {
+ const value = (entity as Record<string, unknown>)[property];
+
+ if (typeof value !== 'string' || value.length === 0) {
+ continue;
+ }
+
+ const context = getMetadataLabelContext(metadataName, property);
+
+ descriptorByKey.set(JSON.stringify([context, value]), {
+ message: value,
+ context,
+ });
+ }
+ };
+
+ for (const [metadataName, manifestKey] of Object.entries(
+ MANIFEST_KEY_BY_METADATA_NAME,
+ ) as [TranslatableMetadataName, keyof Manifest][]) {
+ const entities = manifest[manifestKey];
+
+ if (!Array.isArray(entities)) {
+ continue;
+ }
+
+ for (const entity of entities) {
+ addEntityStrings(entity, metadataName);
+ }
+ }
+
+ for (const objectManifest of manifest.objects ?? []) {
+ for (const field of objectManifest.fields ?? []) {
+ addEntityStrings(field, 'fieldMetadata');
+ }
+ }
+
+ // Tab and widget titles live nested under pageLayouts[].tabs[], not in the
+ // flat pageLayoutTabs array, so walk the tree to reach them.
+ for (const pageLayout of manifest.pageLayouts ?? []) {
+ for (const tab of pageLayout.tabs ?? []) {
+ addEntityStrings(tab, 'pageLayoutTab');
+
+ for (const widget of tab.widgets ?? []) {
+ addEntityStrings(widget, 'pageLayoutWidget');
+ }
+ }
+ }
+
+ for (const pageLayoutTab of manifest.pageLayoutTabs ?? []) {
+ for (const widget of pageLayoutTab.widgets ?? []) {
+ addEntityStrings(widget, 'pageLayoutWidget');
+ }
+ }
+
+ return [...descriptorByKey.values()];
+};
diff --git a/packages/twenty-cli/src/app/translations/compile-application-translations.ts b/packages/twenty-cli/src/app/translations/compile-application-translations.ts
new file mode 100644
index 00000000000..5f92d5282d8
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/compile-application-translations.ts
@@ -0,0 +1,166 @@
+import { readdir } from 'node:fs/promises';
+import path from 'path';
+
+import { compileCatalogToMessageIds } from '@/app/translations/compile-catalog-to-message-ids';
+import { pathExists, readJson } from '@/app/fs-utils';
+import {
+ COMPILED_LOCALES_DIR,
+ LOCALES_DIR,
+} from '@/app/translations/constants';
+import { isSupportedLocale } from '@/app/translations/is-supported-locale';
+import { type TranslationsManifest } from 'twenty-shared/application';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+import { isDefined } from 'twenty-shared/utils';
+
+const readLocaleCatalogFile = async ({
+ filePath,
+ onWarning,
+}: {
+ filePath: string;
+ onWarning: (message: string) => void;
+}): Promise<Record<string, unknown> | null> => {
+ let parsed: unknown;
+
+ try {
+ parsed = await readJson<unknown>(filePath);
+ } catch {
+ onWarning(
+ `Skipping translation file "${path.basename(filePath)}": it is not valid JSON.`,
+ );
+
+ return null;
+ }
+
+ if (
+ !isDefined(parsed) ||
+ typeof parsed !== 'object' ||
+ Array.isArray(parsed)
+ ) {
+ onWarning(
+ `Skipping translation file "${path.basename(filePath)}": expected a JSON object.`,
+ );
+
+ return null;
+ }
+
+ return parsed as Record<string, unknown>;
+};
+
+const readCompiledCatalogs = async ({
+ appPath,
+ onWarning,
+}: {
+ appPath: string;
+ onWarning: (message: string) => void;
+}): Promise<Record<string, Record<string, string>>> => {
+ const compiledDir = path.join(appPath, COMPILED_LOCALES_DIR);
+
+ if (!(await pathExists(compiledDir))) {
+ return {};
+ }
+
+ const catalogs: Record<string, Record<string, string>> = {};
+
+ for (const compiledFile of (await readdir(compiledDir)).filter((entry) =>
+ entry.endsWith('.json'),
+ )) {
+ const locale = path.basename(compiledFile, '.json');
+
+ if (locale === SOURCE_LOCALE) {
+ continue;
+ }
+
+ if (!isSupportedLocale(locale)) {
+ onWarning(
+ `Skipping compiled translation file "${compiledFile}": "${locale}" is not a supported locale.`,
+ );
+ continue;
+ }
+
+ const compiledCatalog = await readLocaleCatalogFile({
+ filePath: path.join(compiledDir, compiledFile),
+ onWarning,
+ });
+
+ if (compiledCatalog === null) {
+ continue;
+ }
+
+ const messages = Object.fromEntries(
+ Object.entries(compiledCatalog).filter(
+ (entry): entry is [string, string] =>
+ typeof entry[1] === 'string' && entry[1].length > 0,
+ ),
+ );
+
+ if (Object.keys(messages).length > 0) {
+ catalogs[locale] = messages;
+ }
+ }
+
+ return catalogs;
+};
+
+export const compileApplicationTranslations = async ({
+ appPath,
+ onWarning = (message) => console.warn(message),
+}: {
+ appPath: string;
+ onWarning?: (message: string) => void;
+}): Promise<TranslationsManifest | undefined> => {
+ const localesDir = path.join(appPath, LOCALES_DIR);
+
+ if (!(await pathExists(localesDir))) {
+ return undefined;
+ }
+
+ const localeFiles = (await readdir(localesDir)).filter((entry) =>
+ entry.endsWith('.json'),
+ );
+
+ const translations: Record<string, Record<string, string>> = {};
+
+ for (const localeFile of localeFiles) {
+ const locale = path.basename(localeFile, '.json');
+
+ if (locale === SOURCE_LOCALE) {
+ continue;
+ }
+
+ if (!isSupportedLocale(locale)) {
+ onWarning(
+ `Skipping translation file "${localeFile}": "${locale}" is not a supported locale.`,
+ );
+ continue;
+ }
+
+ const sourceToTranslation = await readLocaleCatalogFile({
+ filePath: path.join(localesDir, localeFile),
+ onWarning,
+ });
+
+ if (sourceToTranslation === null) {
+ continue;
+ }
+
+ const compiled = compileCatalogToMessageIds({
+ catalog: sourceToTranslation,
+ onCollision: ({ messageId, keptKey, droppedKey }) =>
+ onWarning(
+ `Message id collision in "${localeFile}": "${keptKey}" and "${droppedKey}" share id "${messageId}". Keeping "${keptKey}".`,
+ ),
+ });
+
+ if (Object.keys(compiled).length > 0) {
+ translations[locale] = compiled;
+ }
+ }
+
+ for (const [locale, messages] of Object.entries(
+ await readCompiledCatalogs({ appPath, onWarning }),
+ )) {
+ translations[locale] = { ...messages, ...(translations[locale] ?? {}) };
+ }
+
+ return translations as TranslationsManifest;
+};
diff --git a/packages/twenty-cli/src/app/translations/compile-catalog-to-message-ids.ts b/packages/twenty-cli/src/app/translations/compile-catalog-to-message-ids.ts
new file mode 100644
index 00000000000..c51692ab4e3
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/compile-catalog-to-message-ids.ts
@@ -0,0 +1,44 @@
+import { generateMessageId } from 'twenty-shared/i18n';
+import { isDefined } from 'twenty-shared/utils';
+
+import { flattenLocaleCatalog } from '@/app/translations/locale-catalog-format';
+
+// Authoring files are keyed readable (context groups + plain messages) for
+// translators; runtime lookups are by message id, so every consumer compiles
+// through here.
+export const compileCatalogToMessageIds = ({
+ catalog,
+ onCollision,
+}: {
+ // Parsed straight from on-disk JSON, so values are only claimed strings.
+ catalog: Record<string, unknown>;
+ onCollision?: (args: {
+ messageId: string;
+ keptKey: string;
+ droppedKey: string;
+ }) => void;
+}): Record<string, string> => {
+ const compiled: Record<string, string> = {};
+ const keyByMessageId = new Map<string, string>();
+
+ for (const { message, context, translation } of flattenLocaleCatalog(
+ catalog,
+ )) {
+ if (translation.length === 0) {
+ continue;
+ }
+
+ const key = isDefined(context) ? `${context} ${message}` : message;
+ const messageId = generateMessageId(message, context);
+ const collidingKey = keyByMessageId.get(messageId);
+
+ if (isDefined(collidingKey) && collidingKey !== key) {
+ onCollision?.({ messageId, keptKey: key, droppedKey: collidingKey });
+ }
+
+ keyByMessageId.set(messageId, key);
+ compiled[messageId] = translation;
+ }
+
+ return compiled;
+};
diff --git a/packages/twenty-cli/src/app/translations/constants.ts b/packages/twenty-cli/src/app/translations/constants.ts
new file mode 100644
index 00000000000..b2c3031b9fc
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/constants.ts
@@ -0,0 +1,5 @@
+import { posix } from 'node:path';
+
+export const LOCALES_DIR = 'locales';
+
+export const COMPILED_LOCALES_DIR = posix.join(LOCALES_DIR, 'compiled');
diff --git a/packages/twenty-cli/src/app/translations/is-locale-catalog.ts b/packages/twenty-cli/src/app/translations/is-locale-catalog.ts
new file mode 100644
index 00000000000..840e638c6ba
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/is-locale-catalog.ts
@@ -0,0 +1,9 @@
+import { isDefined } from 'twenty-shared/utils';
+
+export const isLocaleCatalog = (
+ value: unknown,
+): value is Record<string, string> =>
+ isDefined(value) &&
+ typeof value === 'object' &&
+ !Array.isArray(value) &&
+ Object.values(value).every((translation) => typeof translation === 'string');
diff --git a/packages/twenty-cli/src/app/translations/is-supported-locale.ts b/packages/twenty-cli/src/app/translations/is-supported-locale.ts
new file mode 100644
index 00000000000..b9e2840a5c0
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/is-supported-locale.ts
@@ -0,0 +1,4 @@
+import { APP_LOCALES, type AppLocale } from 'twenty-shared/translations';
+
+export const isSupportedLocale = (locale: string): locale is AppLocale =>
+ Object.prototype.hasOwnProperty.call(APP_LOCALES, locale);
diff --git a/packages/twenty-cli/src/app/translations/load-front-component-translation-catalogs.ts b/packages/twenty-cli/src/app/translations/load-front-component-translation-catalogs.ts
new file mode 100644
index 00000000000..46fb15999ce
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/load-front-component-translation-catalogs.ts
@@ -0,0 +1,48 @@
+import { readdir } from 'node:fs/promises';
+import path from 'path';
+
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+
+import { type TranslationCatalogsByLocale } from '@/app/translations/types/translation-catalogs-by-locale.type';
+import { pathExists, readJson } from '@/app/fs-utils';
+import { compileCatalogToMessageIds } from '@/app/translations/compile-catalog-to-message-ids';
+import { LOCALES_DIR } from '@/app/translations/constants';
+
+import { isSupportedLocale } from '@/app/translations/is-supported-locale';
+
+export const loadFrontComponentTranslationCatalogs = async (
+ appPath: string,
+): Promise<TranslationCatalogsByLocale> => {
+ const localesDir = path.join(appPath, LOCALES_DIR);
+
+ if (!(await pathExists(localesDir))) {
+ return {};
+ }
+
+ const localeFiles = (await readdir(localesDir)).filter((entry) =>
+ entry.endsWith('.json'),
+ );
+
+ const catalogs: TranslationCatalogsByLocale = {};
+
+ for (const localeFile of localeFiles) {
+ const locale = path.basename(localeFile, '.json');
+
+ if (locale === SOURCE_LOCALE || !isSupportedLocale(locale)) {
+ continue;
+ }
+
+ const catalog =
+ (await readJson<Record<string, unknown>>(
+ path.join(localesDir, localeFile),
+ )) ?? {};
+
+ const compiled = compileCatalogToMessageIds({ catalog });
+
+ if (Object.keys(compiled).length > 0) {
+ catalogs[locale] = compiled;
+ }
+ }
+
+ return catalogs;
+};
diff --git a/packages/twenty-cli/src/app/translations/locale-catalog-format.ts b/packages/twenty-cli/src/app/translations/locale-catalog-format.ts
new file mode 100644
index 00000000000..6069e7a69dc
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/locale-catalog-format.ts
@@ -0,0 +1,76 @@
+import { isDefined } from 'twenty-shared/utils';
+
+// A locale file is authored by hand, so its shape is optimized for reading:
+// context-free messages sit at the top level, and contextual messages are
+// grouped under their context so a translator sees the role ('Invoice' under
+// objectMetadata.labelSingular is an object name, not a field label).
+//
+// {
+// "Saved {count} cards": "{count} cartes enregistrées",
+// "objectMetadata.labelSingular": { "Invoice": "Facture" }
+// }
+//
+// A string value is a translation, an object value is a context group -- which
+// is also how the two are told apart when reading.
+export type LocaleCatalogEntry = {
+ message: string;
+ context?: string;
+ translation: string;
+};
+
+export const flattenLocaleCatalog = (
+ raw: Record<string, unknown>,
+): LocaleCatalogEntry[] => {
+ const entries: LocaleCatalogEntry[] = [];
+
+ for (const [key, value] of Object.entries(raw)) {
+ if (typeof value === 'string') {
+ entries.push({ message: key, translation: value });
+ continue;
+ }
+
+ if (isDefined(value) && typeof value === 'object') {
+ for (const [message, translation] of Object.entries(value)) {
+ if (typeof translation === 'string') {
+ entries.push({ message, context: key, translation });
+ }
+ }
+ }
+ }
+
+ return entries;
+};
+
+export const buildLocaleCatalog = (
+ entries: LocaleCatalogEntry[],
+): Record<string, string | Record<string, string>> => {
+ const catalog: Record<string, string | Record<string, string>> =
+ Object.create(null);
+ const sorted = [...entries].sort(
+ (a, b) =>
+ (a.context ?? '').localeCompare(b.context ?? '') ||
+ a.message.localeCompare(b.message),
+ );
+
+ for (const { message, context, translation } of sorted) {
+ if (!isDefined(context)) {
+ catalog[message] = translation;
+ continue;
+ }
+
+ const group = catalog[context];
+
+ if (typeof group === 'object' && isDefined(group)) {
+ Object.defineProperty(group, message, {
+ value: translation,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ } else {
+ catalog[context] = { [message]: translation };
+ }
+ }
+
+ return catalog;
+};
diff --git a/packages/twenty-cli/src/app/translations/message/context-separator.constant.ts b/packages/twenty-cli/src/app/translations/message/context-separator.constant.ts
new file mode 100644
index 00000000000..bfad59ad98d
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/message/context-separator.constant.ts
@@ -0,0 +1,2 @@
+// A control char, so context-less keys stay equal to the raw source message.
+export const CONTEXT_SEPARATOR = String.fromCharCode(0x04);
diff --git a/packages/twenty-cli/src/app/translations/message/get-translation-catalog-key.ts b/packages/twenty-cli/src/app/translations/message/get-translation-catalog-key.ts
new file mode 100644
index 00000000000..ca6db005ff0
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/message/get-translation-catalog-key.ts
@@ -0,0 +1,9 @@
+import { CONTEXT_SEPARATOR } from './context-separator.constant';
+
+export const getTranslationCatalogKey = (
+ message: string,
+ context?: string,
+): string =>
+ context !== undefined && context.length > 0
+ ? `${context}${CONTEXT_SEPARATOR}${message}`
+ : message;
diff --git a/packages/twenty-cli/src/app/translations/message/index.ts b/packages/twenty-cli/src/app/translations/message/index.ts
new file mode 100644
index 00000000000..87dd2d54573
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/message/index.ts
@@ -0,0 +1,3 @@
+export { getTranslationCatalogKey } from './get-translation-catalog-key';
+export { normalizeMessageWhitespace } from './normalize-message-whitespace';
+export { type MessageDescriptor } from './message-descriptor.type';
diff --git a/packages/twenty-cli/src/app/translations/message/message-descriptor.type.ts b/packages/twenty-cli/src/app/translations/message/message-descriptor.type.ts
new file mode 100644
index 00000000000..b0767ed2728
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/message/message-descriptor.type.ts
@@ -0,0 +1,4 @@
+export type MessageDescriptor = {
+ message: string;
+ context?: string;
+};
diff --git a/packages/twenty-cli/src/app/translations/message/normalize-message-whitespace.ts b/packages/twenty-cli/src/app/translations/message/normalize-message-whitespace.ts
new file mode 100644
index 00000000000..77b861b502f
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/message/normalize-message-whitespace.ts
@@ -0,0 +1,3 @@
+// Must match how JSX collapses <Trans> whitespace, so build and runtime agree.
+export const normalizeMessageWhitespace = (text: string): string =>
+ text.replace(/\s+/g, ' ').trim();
diff --git a/packages/twenty-cli/src/app/translations/types/translation-catalogs-by-locale.type.ts b/packages/twenty-cli/src/app/translations/types/translation-catalogs-by-locale.type.ts
new file mode 100644
index 00000000000..89213b8d30c
--- /dev/null
+++ b/packages/twenty-cli/src/app/translations/types/translation-catalogs-by-locale.type.ts
@@ -0,0 +1,5 @@
+import { type AppLocale } from 'twenty-shared/translations';
+
+export type TranslationCatalogsByLocale = Partial<
+ Record<AppLocale, Record<string, string>>
+>;
diff --git a/packages/twenty-cli/src/app/typecheck/README.md b/packages/twenty-cli/src/app/typecheck/README.md
new file mode 100644
index 00000000000..7db11d84667
--- /dev/null
+++ b/packages/twenty-cli/src/app/typecheck/README.md
@@ -0,0 +1,67 @@
+# Application typechecking
+
+The CLI typechecks applications using their own TypeScript installation.
+See the [app tooling overview](../README.md) for package ownership.
+
+The internal `typecheckSource` worker request checks the app's source and compiler
+configuration. `bundleSnapshot` runs this typecheck after bundling. A failed check
+discards that build's snapshot. Public build, typecheck, plan, apply and uninstall
+commands use this pipeline.
+
+## Compiler ownership
+
+The globally installed CLI resolves `typescript` from the app's `node_modules`
+or a workspace ancestor. It never falls back to its own parser dependency,
+`NODE_PATH` or Node's global package folders. Apps keep TypeScript in their
+development dependencies; neither apps nor the SDK depend on the CLI.
+
+Missing TypeScript returns `TYPESCRIPT_NOT_INSTALLED`. An incomplete installation,
+missing compiler API or unsupported Plug'n'Play installation returns
+`TOOLING_UNSUPPORTED`. The resolved compiler entry must belong to the app's
+TypeScript installation so checks use the project's compiler version.
+
+TypeScript is loaded only in the child worker. Its public JavaScript compiler API
+is required. The CLI uses the installed compiler's diagnostic categories and
+message formatter, so diagnostics follow the project's compiler version. The CLI
+parser used for source loading remains independent.
+
+## Compiler contract
+
+- Read the app's `tsconfig.json`, preserve its project references and force
+ `noEmit: true`. Do not write JavaScript, declarations or build information.
+- Configuration read/parse errors fail the check, including missing configs,
+ invalid options and missing extended configs. Source diagnostics use TS codes,
+ project-relative paths and one-based line and column numbers.
+- Unbuilt project references fail with TS6305, including diagnostics without a
+ source location. Build the referenced projects separately; this check does not
+ build them or silently ignore their errors.
+- Build warnings remain alongside typecheck diagnostics. Failure never holds a
+ snapshot for upload, and cleanup preserves unrelated snapshots.
+- Check cancellation before and after the synchronous compiler work. A busy
+ compiler cannot process IPC cancellation mid-call; the worker grace
+ period and forced termination remain the fallback.
+
+Different compiler versions can produce different diagnostics. Align compiler
+versions when comparing CLI results with another tool. See the
+[build requirements](../../../docs/commands.md#build-and-check-an-app) for
+configuration and project-reference troubleshooting.
+
+## Verification
+
+From `packages/twenty-cli`, after building the shared and SDK dependencies:
+
+```sh
+node ../../node_modules/vitest/vitest.mjs run --config vitest.config.ts src/app/typecheck src/app/snapshots --maxWorkers=1
+```
+
+The typecheck suite compares the SDK reference, the CLI implementation
+and the production worker with the same compiler. It also tests absent and hoisted
+compilers, global-path fallback, incomplete installations and actual TypeScript
+5.9.3 versus 5.7.3 behavior. The 5.7.3 compiler comes from the SDK's
+ts-morph dependency for this test only.
+
+Snapshot parity runs both real typecheck phases, with no compiler bypass.
+The app fixture supplies only the SDK's authoring/runtime exports. The apply
+contract exercises CLI snapshots against a local HTTP fixture.
+For the fresh CLI template, parity compares successful builds with the test
+setup included and Vitest configuration files excluded.
diff --git a/packages/twenty-cli/src/app/typecheck/__tests__/typecheck-application.spec.ts b/packages/twenty-cli/src/app/typecheck/__tests__/typecheck-application.spec.ts
new file mode 100644
index 00000000000..386f61c83d0
--- /dev/null
+++ b/packages/twenty-cli/src/app/typecheck/__tests__/typecheck-application.spec.ts
@@ -0,0 +1,390 @@
+import { existsSync } from 'node:fs';
+import {
+ mkdir,
+ mkdtemp,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { build, stop } from 'esbuild';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { parseNullData, parseToolingResult } from '@/app/parse-tooling-result';
+import { runAppWorker } from '@/app/run-app-worker';
+import { typecheckApplication } from '@/app/typecheck/typecheck-application';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+const require = createRequire(import.meta.url);
+const compilerDirectory = dirname(require.resolve('typescript/package.json'));
+
+describe('CLI typecheck matches the SDK with the same compiler', () => {
+ let appPath: string;
+ let referenceDirectory: string;
+ let sdk: { typecheckApplication: typeof typecheckApplication };
+
+ const checkWithWorker = async () => {
+ const response = await runAppWorker({
+ request: { type: 'typecheckSource', appPath },
+ signal: new AbortController().signal,
+ });
+ expect(response.isSnapshotHeld).toBe(false);
+ return parseToolingResult({
+ value: response.result,
+ parseData: parseNullData,
+ });
+ };
+
+ const checkWithParity = async () => {
+ const expected = await sdk.typecheckApplication({ appPath });
+ const direct = await typecheckApplication({ appPath });
+ const worker = await checkWithWorker();
+ expect(direct).toEqual(expected);
+ expect(worker).toEqual(expected);
+ return worker;
+ };
+
+ beforeAll(async () => {
+ referenceDirectory = await mkdtemp(
+ join(tmpdir(), 'twenty-typecheck-reference-'),
+ );
+ await mkdir(join(referenceDirectory, 'node_modules'));
+ for (const name of ['typescript', 'twenty-shared']) {
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules', name),
+ join(referenceDirectory, 'node_modules', name),
+ );
+ }
+ const sdkSource = join(REPOSITORY_ROOT, 'packages/twenty-sdk/src');
+ const entry = join(referenceDirectory, 'sdk-reference.cjs');
+ await build({
+ entryPoints: [
+ join(sdkSource, 'application-build/typecheck-application.ts'),
+ ],
+ outfile: entry,
+ alias: { '@': sdkSource },
+ bundle: true,
+ packages: 'external',
+ platform: 'node',
+ format: 'cjs',
+ target: 'node24',
+ });
+ sdk = require(entry) as typeof sdk;
+ await buildTestAppWorker(join(referenceDirectory, 'cli'));
+ launch.modulePath = join(referenceDirectory, 'cli/app-worker.cjs');
+ }, 60000);
+
+ afterAll(async () => {
+ await stop();
+ await rm(referenceDirectory, { recursive: true, force: true });
+ });
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-typecheck-'));
+ await mkdir(join(appPath, 'node_modules'));
+ await symlink(compilerDirectory, join(appPath, 'node_modules/typescript'));
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { strict: true, types: [], declaration: true },
+ files: ['example.ts'],
+ }),
+ );
+ await writeFile(join(appPath, 'example.ts'), 'export const value = 1;');
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('checks valid code without emitting files or requiring an SDK', async () => {
+ expect(await checkWithParity()).toEqual({
+ success: true,
+ data: null,
+ diagnostics: [],
+ });
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'example.ts',
+ 'node_modules',
+ 'tsconfig.json',
+ ]);
+ }, 15000);
+
+ it('reports compiler errors with project-relative, one-based locations', async () => {
+ await writeFile(
+ join(appPath, 'example.ts'),
+ 'export const broken: number = "bad";',
+ );
+ expect(await checkWithParity()).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: [
+ {
+ severity: 'error',
+ code: 'TS2322',
+ file: 'example.ts',
+ line: 1,
+ column: 14,
+ },
+ ],
+ });
+ }, 15000);
+
+ it('fails when tsconfig.json is missing', async () => {
+ await rm(join(appPath, 'tsconfig.json'));
+ expect(await checkWithParity()).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: [{ severity: 'error', code: 'TS5083' }],
+ });
+ });
+
+ it.each([
+ [
+ 'invalid option value',
+ { compilerOptions: { target: 'invalid-target' } },
+ 'TS6046',
+ ],
+ ['unknown option', { compilerOptions: { invalidOption: true } }, 'TS5023'],
+ ['missing extended config', { extends: './missing.json' }, 'TS5083'],
+ ['no matching files', { include: ['missing/**/*.ts'] }, 'TS18003'],
+ ])('fails on %s', async (_name, config, code) => {
+ await writeFile(join(appPath, 'tsconfig.json'), JSON.stringify(config));
+ expect(await checkWithParity()).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({ severity: 'error', code }),
+ ]),
+ });
+ });
+
+ it('reports invalid JSON configuration', async () => {
+ await writeFile(join(appPath, 'tsconfig.json'), '{ "compilerOptions": ');
+ expect(await checkWithParity()).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: [expect.objectContaining({ severity: 'error' })],
+ });
+ });
+
+ it('fails on unbuilt project references even without a source location', async () => {
+ await mkdir(join(appPath, 'referenced'));
+ await writeFile(
+ join(appPath, 'referenced/source.ts'),
+ 'export const value = 1;',
+ );
+ await writeFile(
+ join(appPath, 'referenced/tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { composite: true, outDir: 'dist', types: [] },
+ files: ['source.ts'],
+ }),
+ );
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { types: [] },
+ files: ['referenced/source.ts'],
+ references: [{ path: './referenced' }],
+ }),
+ );
+ const result = await checkWithParity();
+ expect(result).toMatchObject({
+ success: false,
+ error: { code: 'TYPECHECK_FAILED' },
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({ severity: 'error', code: 'TS6305' }),
+ ]),
+ });
+ expect(
+ result.diagnostics.find((diagnostic) => diagnostic.code === 'TS6305')
+ ?.file,
+ ).toBeUndefined();
+ expect((await readdir(join(appPath, 'referenced'))).sort()).toEqual([
+ 'source.ts',
+ 'tsconfig.json',
+ ]);
+ }, 15000);
+
+ it('fails clearly when the app compiler is missing, despite the CLI compiler being installed', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ expect(await checkWithWorker()).toMatchObject({
+ success: false,
+ error: {
+ code: 'TYPESCRIPT_NOT_INSTALLED',
+ message: expect.stringContaining(
+ "Install typescript in the app's devDependencies",
+ ),
+ },
+ });
+ });
+
+ it('does not borrow a compiler from NODE_PATH', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ vi.stubEnv('NODE_PATH', dirname(compilerDirectory));
+ expect(await checkWithWorker()).toMatchObject({
+ success: false,
+ error: { code: 'TYPESCRIPT_NOT_INSTALLED' },
+ });
+ });
+
+ it("explains unsupported Plug'n'Play resolution", async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ await writeFile(join(appPath, '.pnp.cjs'), 'module.exports = {};');
+ expect(await checkWithWorker()).toMatchObject({
+ success: false,
+ error: {
+ code: 'TOOLING_UNSUPPORTED',
+ message: expect.stringContaining('nodeLinker: node-modules'),
+ },
+ });
+ });
+
+ it('reports an incomplete compiler installation', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ await mkdir(join(appPath, 'node_modules/typescript'));
+ await writeFile(
+ join(appPath, 'node_modules/typescript/package.json'),
+ JSON.stringify({
+ name: 'typescript',
+ version: '0.0.0',
+ main: 'index.cjs',
+ }),
+ );
+ await writeFile(
+ join(appPath, 'node_modules/typescript/index.cjs'),
+ 'module.exports = {};',
+ );
+ expect(await checkWithWorker()).toMatchObject({
+ success: false,
+ error: {
+ code: 'TOOLING_UNSUPPORTED',
+ details: { compilerVersion: '0.0.0' },
+ },
+ });
+ });
+
+ it('resolves a workspace-hoisted compiler', async () => {
+ const workspacePath = appPath;
+ appPath = join(workspacePath, 'packages/app');
+ try {
+ await mkdir(appPath, { recursive: true });
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { types: [] },
+ files: ['example.ts'],
+ }),
+ );
+ await writeFile(join(appPath, 'example.ts'), 'export const value = 1;');
+ expect(await checkWithParity()).toMatchObject({ success: true });
+ } finally {
+ appPath = workspacePath;
+ }
+ }, 15000);
+
+ it('uses the actual app compiler version instead of the CLI compiler', async () => {
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { module: 'node20', types: [] },
+ files: ['example.ts'],
+ }),
+ );
+ expect(await checkWithWorker()).toMatchObject({ success: true });
+ await rm(join(appPath, 'node_modules/typescript'));
+ await mkdir(join(appPath, 'node_modules/typescript'));
+ const sdkRequire = createRequire(
+ join(REPOSITORY_ROOT, 'packages/twenty-sdk/package.json'),
+ );
+ const legacyCompilerPath = sdkRequire.resolve('@ts-morph/common');
+ await writeFile(
+ join(appPath, 'node_modules/typescript/package.json'),
+ JSON.stringify({ name: 'typescript', main: 'index.cjs' }),
+ );
+ await writeFile(
+ join(appPath, 'node_modules/typescript/index.cjs'),
+ `module.exports = require(${JSON.stringify(legacyCompilerPath)}).ts;`,
+ );
+ expect(await checkWithWorker()).toMatchObject({
+ success: false,
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ code: 'TS6046',
+ message: expect.stringContaining('--module'),
+ }),
+ ]),
+ });
+ }, 15000);
+
+ it('returns structured cancellation before loading the app compiler', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ expect(
+ await typecheckApplication({ appPath, signal: AbortSignal.abort() }),
+ ).toMatchObject({ success: false, error: { code: 'CANCELLED' } });
+ });
+
+ it('terminates a compiler that cannot process cancellation', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ await mkdir(join(appPath, 'node_modules/typescript'));
+ await writeFile(
+ join(appPath, 'node_modules/typescript/package.json'),
+ JSON.stringify({ name: 'typescript', main: 'index.cjs' }),
+ );
+ const marker = join(appPath, 'compiler-started');
+ await writeFile(
+ join(appPath, 'node_modules/typescript/index.cjs'),
+ `const compiler = require(${JSON.stringify(require.resolve('typescript'))});
+ module.exports = { ...compiler, getPreEmitDiagnostics() {
+ require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'started');
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
+ } };`,
+ );
+ const controller = new AbortController();
+ const work = runAppWorker({
+ request: { type: 'typecheckSource', appPath },
+ signal: controller.signal,
+ });
+ const cancelled = expect(work).rejects.toMatchObject({ code: 'CANCELLED' });
+ try {
+ await vi.waitFor(() => expect(existsSync(marker)).toBe(true), {
+ timeout: 5000,
+ });
+ } finally {
+ controller.abort();
+ await cancelled;
+ }
+ expect(existsSync(join(appPath, '.twenty'))).toBe(false);
+ }, 15000);
+
+ it('rejects relative application paths', async () => {
+ expect(
+ await typecheckApplication({ appPath: 'relative-app' }),
+ ).toMatchObject({ success: false, error: { code: 'INVALID_APP_PATH' } });
+ });
+});
diff --git a/packages/twenty-cli/src/app/typecheck/is-typescript-compiler-api.ts b/packages/twenty-cli/src/app/typecheck/is-typescript-compiler-api.ts
new file mode 100644
index 00000000000..cf709a607ed
--- /dev/null
+++ b/packages/twenty-cli/src/app/typecheck/is-typescript-compiler-api.ts
@@ -0,0 +1,17 @@
+import { isFunction, isNumber } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+import type ts from 'typescript';
+
+export const isTypeScriptCompilerApi = (value: unknown): value is typeof ts =>
+ isPlainObject(value) &&
+ [
+ 'readConfigFile',
+ 'parseJsonConfigFileContent',
+ 'createProgram',
+ 'getPreEmitDiagnostics',
+ 'flattenDiagnosticMessageText',
+ ].every((name) => isFunction(value[name])) &&
+ isPlainObject(value.sys) &&
+ isFunction(value.sys.readFile) &&
+ isPlainObject(value.DiagnosticCategory) &&
+ isNumber(value.DiagnosticCategory.Warning);
diff --git a/packages/twenty-cli/src/app/typecheck/resolve-project-typescript.ts b/packages/twenty-cli/src/app/typecheck/resolve-project-typescript.ts
new file mode 100644
index 00000000000..14c14571372
--- /dev/null
+++ b/packages/twenty-cli/src/app/typecheck/resolve-project-typescript.ts
@@ -0,0 +1,77 @@
+import { realpath } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+
+import type ts from 'typescript';
+
+import { hasYarnPlugAndPlay } from '@/app/project/has-yarn-plug-and-play';
+import { isTypeScriptCompilerApi } from '@/app/typecheck/is-typescript-compiler-api';
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+import { pathExists } from '@/app/fs-utils';
+import { readJsonObject } from '@/app/read-json-object';
+import { CliError } from '@/output/cli-error';
+import { isInsideDirectory } from '@/utils/is-inside-directory';
+
+export const resolveProjectTypeScript = async (
+ appPath: string,
+): Promise<typeof ts> => {
+ const requireFromApp = createRequire(join(appPath, 'package.json'));
+ const ancestors = listAncestorDirectories(appPath);
+
+ for (const directory of ancestors) {
+ const installedPath = join(directory, 'node_modules/typescript');
+
+ if (!(await pathExists(installedPath))) {
+ continue;
+ }
+
+ const compilerPath = await realpath(installedPath);
+ const packageJson = await readJsonObject(
+ join(compilerPath, 'package.json'),
+ );
+ const unsupported = () =>
+ new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message: `The TypeScript installation at ${compilerPath} does not provide the compiler API this CLI needs. Reinstall a compatible typescript version in this app.`,
+ details: {
+ appPath,
+ compilerPath,
+ compilerVersion: packageJson?.version,
+ },
+ });
+
+ if (packageJson?.name !== 'typescript') {
+ throw unsupported();
+ }
+
+ let entryPath: string;
+
+ try {
+ entryPath = requireFromApp.resolve(compilerPath);
+ } catch {
+ throw unsupported();
+ }
+
+ if (!isInsideDirectory({ filePath: entryPath, directory: compilerPath })) {
+ throw unsupported();
+ }
+
+ const compiler: unknown = requireFromApp(entryPath);
+
+ if (!isTypeScriptCompilerApi(compiler)) {
+ throw unsupported();
+ }
+
+ return compiler;
+ }
+
+ const hasPlugAndPlay = await hasYarnPlugAndPlay(appPath);
+
+ throw new CliError({
+ code: hasPlugAndPlay ? 'TOOLING_UNSUPPORTED' : 'TYPESCRIPT_NOT_INSTALLED',
+ message: hasPlugAndPlay
+ ? "This app uses Yarn Plug'n'Play, which the twenty CLI cannot load TypeScript from. Set nodeLinker: node-modules in .yarnrc.yml and reinstall the app's dependencies."
+ : "TypeScript is not installed for this app. Install typescript in the app's devDependencies, then try again.",
+ details: { appPath },
+ });
+};
diff --git a/packages/twenty-cli/src/app/typecheck/typecheck-application.ts b/packages/twenty-cli/src/app/typecheck/typecheck-application.ts
new file mode 100644
index 00000000000..c48705190af
--- /dev/null
+++ b/packages/twenty-cli/src/app/typecheck/typecheck-application.ts
@@ -0,0 +1,162 @@
+import { join, relative } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+import type ts from 'typescript';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import {
+ type ToolingDiagnostic,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import { validateAppPath } from '@/app/snapshots/validate-app-path';
+import { resolveProjectTypeScript } from '@/app/typecheck/resolve-project-typescript';
+import {
+ recordWatchFile,
+ recordWatchProbe,
+} from '@/app/dev/collect-watch-inputs';
+import { CliError } from '@/output/cli-error';
+
+const toDiagnostic = ({
+ diagnostic,
+ appPath,
+ typescript,
+}: {
+ diagnostic: ts.Diagnostic;
+ appPath: string;
+ typescript: typeof ts;
+}): ToolingDiagnostic => {
+ const position =
+ isDefined(diagnostic.file) && isDefined(diagnostic.start)
+ ? diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
+ : undefined;
+
+ return {
+ severity:
+ diagnostic.category === typescript.DiagnosticCategory.Warning
+ ? 'warning'
+ : 'error',
+ code: `TS${diagnostic.code}`,
+ message: typescript.flattenDiagnosticMessageText(
+ diagnostic.messageText,
+ '\n',
+ ),
+ ...(isDefined(diagnostic.file)
+ ? { file: relative(appPath, diagnostic.file.fileName) }
+ : {}),
+ ...(isDefined(position)
+ ? { line: position.line + 1, column: position.character + 1 }
+ : {}),
+ };
+};
+
+const collectCompilerDiagnostics = ({
+ appPath,
+ typescript,
+}: {
+ appPath: string;
+ typescript: typeof ts;
+}): readonly ts.Diagnostic[] => {
+ const configPath = join(appPath, 'tsconfig.json');
+ const readFile: typeof typescript.sys.readFile = (path, encoding) => {
+ recordWatchFile(path);
+
+ return typescript.sys.readFile(path, encoding);
+ };
+ const config = typescript.readConfigFile(configPath, readFile);
+
+ if (isDefined(config.error)) {
+ return [config.error];
+ }
+
+ const parsed = typescript.parseJsonConfigFileContent(
+ config.config,
+ { ...typescript.sys, readFile },
+ appPath,
+ { noEmit: true },
+ configPath,
+ );
+
+ if (parsed.errors.length > 0) {
+ return parsed.errors;
+ }
+
+ const host = typescript.createCompilerHost(parsed.options);
+ const hostReadFile = host.readFile;
+
+ host.readFile = (path) => {
+ recordWatchFile(path);
+
+ return hostReadFile(path);
+ };
+ const hostFileExists = host.fileExists;
+
+ host.fileExists = (path) => {
+ const exists = hostFileExists(path);
+
+ if (!exists) {
+ recordWatchProbe(path);
+ }
+
+ return exists;
+ };
+ const program = typescript.createProgram({
+ host,
+ rootNames: parsed.fileNames,
+ options: parsed.options,
+ projectReferences: parsed.projectReferences,
+ });
+
+ return typescript.getPreEmitDiagnostics(program);
+};
+
+export const typecheckApplication = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal?: AbortSignal;
+}): Promise<ToolingResult<null>> => {
+ const validation = await validateAppPath(appPath);
+
+ if (!validation.success) {
+ return validation;
+ }
+
+ try {
+ signal?.throwIfAborted();
+ const typescript = await resolveProjectTypeScript(appPath);
+ signal?.throwIfAborted();
+ const compilerDiagnostics = collectCompilerDiagnostics({
+ appPath,
+ typescript,
+ });
+
+ signal?.throwIfAborted();
+
+ const diagnostics = compilerDiagnostics.map((diagnostic) =>
+ toDiagnostic({ diagnostic, appPath, typescript }),
+ );
+
+ return diagnostics.some((diagnostic) => diagnostic.severity === 'error')
+ ? {
+ success: false,
+ error: { code: 'TYPECHECK_FAILED', message: 'Typecheck failed.' },
+ diagnostics,
+ }
+ : { success: true, data: null, diagnostics };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code: signal?.aborted
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'TYPECHECK_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ },
+ diagnostics: [],
+ };
+ }
+};
diff --git a/packages/twenty-cli/src/app/types/app-export.type.ts b/packages/twenty-cli/src/app/types/app-export.type.ts
new file mode 100644
index 00000000000..659314311c7
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-export.type.ts
@@ -0,0 +1,25 @@
+import { type ExportedManifest } from '@/app/types/exported-manifest.type';
+
+export type AppExportCoverageEntry = {
+ metadataName: string;
+ universalIdentifier: string;
+ status: string;
+ reason: string | null;
+};
+
+export type AppExportFile = {
+ folder: string;
+ path: string;
+ content: string;
+};
+
+export type AppExport = {
+ application: {
+ universalIdentifier: string;
+ displayName: string;
+ sourceType: string;
+ };
+ manifest: ExportedManifest;
+ coverage: AppExportCoverageEntry[];
+ files: AppExportFile[];
+};
diff --git a/packages/twenty-cli/src/app/types/app-init-next-step.type.ts b/packages/twenty-cli/src/app/types/app-init-next-step.type.ts
new file mode 100644
index 00000000000..d3fd26b6169
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-init-next-step.type.ts
@@ -0,0 +1,4 @@
+export type AppInitNextStep = {
+ command: string;
+ description: string;
+};
diff --git a/packages/twenty-cli/src/app/types/app-operation.type.ts b/packages/twenty-cli/src/app/types/app-operation.type.ts
new file mode 100644
index 00000000000..2e050f391df
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-operation.type.ts
@@ -0,0 +1 @@
+export type AppOperation = 'build' | 'typecheck';
diff --git a/packages/twenty-cli/src/app/types/app-worker-launch.type.ts b/packages/twenty-cli/src/app/types/app-worker-launch.type.ts
new file mode 100644
index 00000000000..558b53e7275
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-worker-launch.type.ts
@@ -0,0 +1,4 @@
+export type AppWorkerLaunch = {
+ modulePath: string;
+ execArgv: string[];
+};
diff --git a/packages/twenty-cli/src/app/types/app-worker-message.type.ts b/packages/twenty-cli/src/app/types/app-worker-message.type.ts
new file mode 100644
index 00000000000..eab434e1200
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-worker-message.type.ts
@@ -0,0 +1,39 @@
+import { type WatchInputs } from '@/app/dev/types/watch-inputs.type';
+import { type PullTarget } from '@/app/types/pull-target.type';
+
+export type AppWorkerRequest =
+ | { type: 'generateSourceClient'; appPath: string; schema: string }
+ | { type: 'readSourceIdentity'; appPath: string }
+ | { type: 'buildManifest'; appPath: string }
+ | { type: 'typecheckSource'; appPath: string }
+ | {
+ type: 'bundleSnapshot';
+ appPath: string;
+ holdSnapshot: boolean;
+ collectWatchInputs?: boolean;
+ }
+ | {
+ type: 'pull';
+ appPath: string;
+ applicationExport: unknown;
+ target: PullTarget;
+ }
+ | { type: 'release' }
+ | { type: 'cancel' };
+
+export type AppWorkerResponse =
+ | {
+ type: 'result';
+ result: unknown;
+ release?: unknown;
+ isSnapshotHeld: boolean;
+ watchInputs?: WatchInputs;
+ }
+ | { type: 'released'; release: unknown }
+ | {
+ type: 'failure';
+ message: string;
+ code?: string;
+ hint?: string;
+ details?: Record<string, unknown>;
+ };
diff --git a/packages/twenty-cli/src/app/types/app-worker-output.type.ts b/packages/twenty-cli/src/app/types/app-worker-output.type.ts
new file mode 100644
index 00000000000..09d15844b8a
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/app-worker-output.type.ts
@@ -0,0 +1,5 @@
+export type AppWorkerOutput = {
+ stdout: string;
+ stderr: string;
+ isTruncated: boolean;
+};
diff --git a/packages/twenty-cli/src/app/types/exported-manifest.type.ts b/packages/twenty-cli/src/app/types/exported-manifest.type.ts
new file mode 100644
index 00000000000..9da7d54f70b
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/exported-manifest.type.ts
@@ -0,0 +1,3 @@
+export type ExportedManifest = Record<string, unknown> & {
+ application: Record<string, unknown> & { universalIdentifier: string };
+};
diff --git a/packages/twenty-cli/src/app/types/pull-target.type.ts b/packages/twenty-cli/src/app/types/pull-target.type.ts
new file mode 100644
index 00000000000..2b8bc0fa40b
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/pull-target.type.ts
@@ -0,0 +1,4 @@
+export type PullTarget = {
+ apiUrl: string;
+ workspaceId: string;
+};
diff --git a/packages/twenty-cli/src/app/types/tooling-result.type.ts b/packages/twenty-cli/src/app/types/tooling-result.type.ts
new file mode 100644
index 00000000000..ab1fa5f371d
--- /dev/null
+++ b/packages/twenty-cli/src/app/types/tooling-result.type.ts
@@ -0,0 +1,43 @@
+export type ToolingDiagnostic = {
+ severity: 'error' | 'warning';
+ code: string;
+ message: string;
+ file?: string;
+ line?: number;
+ column?: number;
+};
+
+export type ToolingArtifact = {
+ path: string;
+ role: string;
+ sourcePath: string;
+ size: number;
+ sha256: string;
+};
+
+export type ToolingBuild = {
+ buildId: string;
+ directory?: string;
+ contentHash: string;
+ application: {
+ universalIdentifier: string;
+ name: string;
+ displayName: string;
+ };
+ manifestFormat: string;
+ manifest: Record<string, unknown>;
+ files: ToolingArtifact[];
+};
+
+export type ToolingResult<TData> =
+ | { success: true; data: TData; diagnostics: ToolingDiagnostic[] }
+ | {
+ success: false;
+ error: {
+ code: string;
+ message: string;
+ hint?: string;
+ details?: Record<string, unknown>;
+ };
+ diagnostics: ToolingDiagnostic[];
+ };
diff --git a/packages/twenty-cli/src/app/worker/app-worker.ts b/packages/twenty-cli/src/app/worker/app-worker.ts
new file mode 100644
index 00000000000..74da3b39fd4
--- /dev/null
+++ b/packages/twenty-cli/src/app/worker/app-worker.ts
@@ -0,0 +1,345 @@
+import { isNonEmptyString, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import type {
+ AppWorkerRequest,
+ AppWorkerResponse,
+} from '@/app/types/app-worker-message.type';
+
+type SnapshotApi = {
+ buildSourceSnapshot: (options: {
+ appPath: string;
+ signal: AbortSignal;
+ }) => Promise<unknown>;
+ releaseSourceSnapshot: (options: { buildId: string }) => Promise<unknown>;
+};
+
+type HeldSnapshot = {
+ snapshotApi: SnapshotApi;
+ buildId: string;
+};
+
+const PARENT_DISCONNECT_EXIT_MILLISECONDS = 5000;
+
+const abortController = new AbortController();
+
+let heldSnapshot: HeldSnapshot | undefined;
+
+const parseRequest = (message: unknown): AppWorkerRequest | undefined => {
+ if (!isPlainObject(message)) {
+ return undefined;
+ }
+
+ if (message.type === 'cancel' || message.type === 'release') {
+ return { type: message.type };
+ }
+
+ if (
+ message.type === 'readSourceIdentity' ||
+ message.type === 'buildManifest' ||
+ message.type === 'typecheckSource'
+ ) {
+ return isNonEmptyString(message.appPath)
+ ? { type: message.type, appPath: message.appPath }
+ : undefined;
+ }
+
+ if (message.type === 'bundleSnapshot') {
+ return isNonEmptyString(message.appPath)
+ ? {
+ type: 'bundleSnapshot',
+ collectWatchInputs: message.collectWatchInputs === true,
+ appPath: message.appPath,
+ holdSnapshot: message.holdSnapshot === true,
+ }
+ : undefined;
+ }
+
+ if (message.type === 'pull') {
+ if (
+ !isNonEmptyString(message.appPath) ||
+ !isPlainObject(message.target) ||
+ !isNonEmptyString(message.target.apiUrl) ||
+ !isNonEmptyString(message.target.workspaceId) ||
+ !isPlainObject(message.applicationExport) ||
+ !isPlainObject(message.applicationExport.application) ||
+ !isNonEmptyString(
+ message.applicationExport.application.universalIdentifier,
+ )
+ ) {
+ return undefined;
+ }
+ return {
+ type: 'pull',
+ appPath: message.appPath,
+ target: {
+ apiUrl: message.target.apiUrl,
+ workspaceId: message.target.workspaceId,
+ },
+ applicationExport: message.applicationExport,
+ };
+ }
+
+ if (message.type === 'generateSourceClient') {
+ return isNonEmptyString(message.appPath) && isString(message.schema)
+ ? {
+ type: 'generateSourceClient',
+ appPath: message.appPath,
+ schema: message.schema,
+ }
+ : undefined;
+ }
+
+ return undefined;
+};
+
+const respond = (response: AppWorkerResponse) => {
+ if (!process.connected) {
+ process.exit(1);
+ }
+
+ process.send?.(response, undefined, {}, () => process.exit(0));
+};
+
+const releaseHeldSnapshot = async () => {
+ if (!isDefined(heldSnapshot)) {
+ return null;
+ }
+
+ const { snapshotApi, buildId } = heldSnapshot;
+
+ heldSnapshot = undefined;
+
+ return snapshotApi.releaseSourceSnapshot({ buildId });
+};
+
+const exitAfterReleasing = () => {
+ void releaseHeldSnapshot().then(
+ () => process.exit(1),
+ () => process.exit(1),
+ );
+};
+
+const sendHeldResult = (response: AppWorkerResponse) => {
+ if (!process.connected) {
+ exitAfterReleasing();
+
+ return;
+ }
+
+ process.send?.(response);
+};
+
+const readSuccessfulBuildId = (result: unknown) => {
+ if (
+ !isPlainObject(result) ||
+ result.success !== true ||
+ !isPlainObject(result.data)
+ ) {
+ return undefined;
+ }
+
+ return isNonEmptyString(result.data.buildId)
+ ? result.data.buildId
+ : undefined;
+};
+
+const runSnapshotBuild = async ({
+ snapshotApi,
+ appPath,
+ holdSnapshot,
+}: {
+ snapshotApi: SnapshotApi;
+ appPath: string;
+ holdSnapshot: boolean;
+}): Promise<AppWorkerResponse> => {
+ const signal = abortController.signal;
+ const result = await snapshotApi.buildSourceSnapshot({ appPath, signal });
+ const buildId = readSuccessfulBuildId(result);
+
+ if (!isDefined(buildId)) {
+ return { type: 'result', result, isSnapshotHeld: false };
+ }
+
+ if (holdSnapshot) {
+ heldSnapshot = { snapshotApi, buildId };
+
+ return { type: 'result', result, isSnapshotHeld: true };
+ }
+
+ return {
+ type: 'result',
+ result,
+ release: await snapshotApi.releaseSourceSnapshot({ buildId }),
+ isSnapshotHeld: false,
+ };
+};
+
+const toFailure = (error: unknown): AppWorkerResponse => ({
+ type: 'failure',
+ message: error instanceof Error ? error.message : String(error),
+ ...(error instanceof Error && 'code' in error && isString(error.code)
+ ? { code: error.code }
+ : {}),
+ ...(error instanceof Error && 'hint' in error && isString(error.hint)
+ ? { hint: error.hint }
+ : {}),
+ ...(error instanceof Error &&
+ 'details' in error &&
+ isPlainObject(error.details)
+ ? { details: error.details }
+ : {}),
+});
+
+process.on('SIGINT', () => undefined);
+
+process.on('disconnect', () => {
+ abortController.abort();
+ setTimeout(() => process.exit(1), PARENT_DISCONNECT_EXIT_MILLISECONDS);
+
+ if (isDefined(heldSnapshot)) {
+ exitAfterReleasing();
+ }
+});
+
+process.on('message', (message: unknown) => {
+ const request = parseRequest(message);
+
+ if (!isDefined(request)) {
+ respond({
+ type: 'failure',
+ message: 'The app worker received a request it cannot read.',
+ });
+
+ return;
+ }
+
+ if (request.type === 'cancel') {
+ abortController.abort();
+
+ return;
+ }
+
+ if (request.type === 'release') {
+ releaseHeldSnapshot().then(
+ (release) => respond({ type: 'released', release }),
+ (error: unknown) => respond(toFailure(error)),
+ );
+
+ return;
+ }
+
+ if (request.type === 'pull') {
+ import('@/app/worker/pull-source')
+ .then(async ({ pullSource }) => {
+ const result = await pullSource({
+ ...request,
+ signal: abortController.signal,
+ });
+ respond({ type: 'result', result, isSnapshotHeld: false });
+ })
+ .catch((error: unknown) => respond(toFailure(error)));
+ return;
+ }
+
+ if (request.type === 'bundleSnapshot') {
+ import('@/app/worker/build-source-snapshot')
+ .then(async ({ buildSourceSnapshot, releaseSourceSnapshot }) => {
+ const run = () =>
+ runSnapshotBuild({
+ snapshotApi: {
+ buildSourceSnapshot,
+ releaseSourceSnapshot,
+ },
+ appPath: request.appPath,
+ holdSnapshot: request.holdSnapshot,
+ });
+
+ if (!request.collectWatchInputs) {
+ return run();
+ }
+
+ const { collectWatchInputs } =
+ await import('@/app/dev/collect-watch-inputs');
+ const { recordTypecheckConfigInputs } =
+ await import('@/app/dev/record-typecheck-config-inputs');
+ const collected = await collectWatchInputs(async () => {
+ await recordTypecheckConfigInputs(request.appPath);
+
+ return run();
+ });
+
+ return { ...collected.result, watchInputs: collected.watchInputs };
+ })
+ .then(
+ (response) =>
+ response.type === 'result' && response.isSnapshotHeld
+ ? sendHeldResult(response)
+ : respond(response),
+ (error: unknown) => respond(toFailure(error)),
+ );
+
+ return;
+ }
+
+ if (request.type === 'typecheckSource') {
+ import('@/app/typecheck/typecheck-application')
+ .then(async ({ typecheckApplication }) => {
+ const result = await typecheckApplication({
+ appPath: request.appPath,
+ signal: abortController.signal,
+ });
+
+ respond({ type: 'result', result, isSnapshotHeld: false });
+ })
+ .catch((error: unknown) => respond(toFailure(error)));
+
+ return;
+ }
+
+ if (request.type === 'buildManifest') {
+ import('@/app/worker/build-source-manifest')
+ .then(async ({ buildSourceManifest }) => {
+ const result = await buildSourceManifest({
+ appPath: request.appPath,
+ signal: abortController.signal,
+ });
+
+ respond({ type: 'result', result, isSnapshotHeld: false });
+ })
+ .catch((error: unknown) => respond(toFailure(error)));
+
+ return;
+ }
+
+ if (request.type === 'readSourceIdentity') {
+ import('@/app/worker/read-source-identity')
+ .then(async ({ readSourceIdentity }) => {
+ const result = await readSourceIdentity({
+ appPath: request.appPath,
+ signal: abortController.signal,
+ });
+
+ respond({ type: 'result', result, isSnapshotHeld: false });
+ })
+ .catch((error: unknown) => respond(toFailure(error)));
+
+ return;
+ }
+
+ if (request.type === 'generateSourceClient') {
+ import('@/app/client/generate-application-client')
+ .then(async ({ generateApplicationClient }) => {
+ const result = await generateApplicationClient({
+ appPath: request.appPath,
+ schema: request.schema,
+ signal: abortController.signal,
+ });
+
+ respond({ type: 'result', result, isSnapshotHeld: false });
+ })
+ .catch((error: unknown) => respond(toFailure(error)));
+
+ return;
+ }
+});
diff --git a/packages/twenty-cli/src/app/worker/build-source-manifest.ts b/packages/twenty-cli/src/app/worker/build-source-manifest.ts
new file mode 100644
index 00000000000..21fadc5518d
--- /dev/null
+++ b/packages/twenty-cli/src/app/worker/build-source-manifest.ts
@@ -0,0 +1,81 @@
+import { stop } from 'esbuild';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import { buildAndValidateManifest } from '@/app/manifest/build-and-validate-manifest';
+import { type AppManifest } from '@/app/manifest/types/app-manifest.type';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { compileApplicationTranslations } from '@/app/translations/compile-application-translations';
+import {
+ type ToolingDiagnostic,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+
+export const buildSourceManifest = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+}): Promise<ToolingResult<AppManifest>> => {
+ const diagnostics: ToolingDiagnostic[] = [];
+ const warn = (message: string) => {
+ diagnostics.push({ severity: 'warning', code: 'BUILD_WARNING', message });
+ };
+
+ try {
+ signal.throwIfAborted();
+ await resolveSourceSdk({ appPath });
+ const result = await buildAndValidateManifest(appPath);
+
+ signal.throwIfAborted();
+
+ if (!result.success) {
+ return {
+ success: false,
+ error: {
+ code: 'MANIFEST_BUILD_FAILED',
+ message: result.errors.join('\n'),
+ },
+ diagnostics: result.errors.map((message) => ({
+ severity: 'error',
+ code: 'MANIFEST_BUILD_FAILED',
+ message,
+ })),
+ };
+ }
+
+ result.warnings.forEach(warn);
+ const translations = await compileApplicationTranslations({
+ appPath,
+ onWarning: warn,
+ });
+
+ signal.throwIfAborted();
+
+ return {
+ success: true,
+ data: {
+ manifest: { ...result.manifest, translations },
+ filePaths: result.filePaths,
+ },
+ diagnostics,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code: signal.aborted
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'MANIFEST_BUILD_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ },
+ diagnostics,
+ };
+ } finally {
+ await stop();
+ }
+};
diff --git a/packages/twenty-cli/src/app/worker/build-source-snapshot.ts b/packages/twenty-cli/src/app/worker/build-source-snapshot.ts
new file mode 100644
index 00000000000..a2e99deeb8c
--- /dev/null
+++ b/packages/twenty-cli/src/app/worker/build-source-snapshot.ts
@@ -0,0 +1,43 @@
+import { stop } from 'esbuild';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { buildSnapshot, releaseSnapshot } from '@/app/snapshots/build-snapshot';
+import {
+ type ToolingBuild,
+ type ToolingResult,
+} from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+
+export const buildSourceSnapshot = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+}): Promise<ToolingResult<ToolingBuild>> => {
+ try {
+ signal.throwIfAborted();
+ await resolveSourceSdk({ appPath });
+
+ return await buildSnapshot({ appPath, signal });
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code: signal.aborted
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'BUILD_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ },
+ diagnostics: [],
+ };
+ } finally {
+ await stop();
+ }
+};
+
+export const releaseSourceSnapshot = releaseSnapshot;
diff --git a/packages/twenty-cli/src/app/worker/pull-source.ts b/packages/twenty-cli/src/app/worker/pull-source.ts
new file mode 100644
index 00000000000..67a0e4590dd
--- /dev/null
+++ b/packages/twenty-cli/src/app/worker/pull-source.ts
@@ -0,0 +1,34 @@
+import { stop } from 'esbuild';
+import { isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { parseAppExport } from '@/app/parse-app-export';
+import { pullApplication } from '@/app/pull/pull-application';
+import { type PullAppOptions } from '@/app/pull/types';
+
+export const pullSource = async (
+ options: Omit<PullAppOptions, 'applicationExport'> & {
+ applicationExport: unknown;
+ },
+) => {
+ try {
+ const exported = options.applicationExport;
+
+ const universalIdentifier =
+ isPlainObject(exported) &&
+ isPlainObject(exported.application) &&
+ isString(exported.application.universalIdentifier)
+ ? exported.application.universalIdentifier
+ : '';
+
+ return await pullApplication({
+ ...options,
+ applicationExport: parseAppExport({
+ value: exported,
+ universalIdentifier,
+ }),
+ });
+ } finally {
+ await stop();
+ }
+};
diff --git a/packages/twenty-cli/src/app/worker/read-source-identity.ts b/packages/twenty-cli/src/app/worker/read-source-identity.ts
new file mode 100644
index 00000000000..6fa7b22c9d2
--- /dev/null
+++ b/packages/twenty-cli/src/app/worker/read-source-identity.ts
@@ -0,0 +1,39 @@
+import { stop } from 'esbuild';
+
+import { getToolingErrorContext } from '@/app/get-tooling-error-context';
+import { readApplicationIdentity } from '@/app/source/read-application-identity';
+import { type AppSourceIdentity } from '@/app/source/types/app-source-identity.type';
+import { type ToolingResult } from '@/app/types/tooling-result.type';
+import { CliError } from '@/output/cli-error';
+
+export const readSourceIdentity = async ({
+ appPath,
+ signal,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+}): Promise<ToolingResult<AppSourceIdentity>> => {
+ try {
+ return {
+ success: true,
+ data: await readApplicationIdentity({ appPath, signal }),
+ diagnostics: [],
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: {
+ code: signal.aborted
+ ? 'CANCELLED'
+ : error instanceof CliError
+ ? error.code
+ : 'IDENTITY_READ_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ ...getToolingErrorContext(error),
+ },
+ diagnostics: [],
+ };
+ } finally {
+ await stop();
+ }
+};
diff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.ts
new file mode 100644
index 00000000000..b696d344bca
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/command-catalog.ts
@@ -0,0 +1,66 @@
+import { APP_DEV_COMMAND_DEFINITION } from '@/commands/app/dev/app-dev.command-definition';
+import { APP_ADD_COMMAND_DEFINITION } from '@/commands/app/add/app-add.command-definition';
+import { APP_EXEC_COMMAND_DEFINITION } from '@/commands/app/exec/app-exec.command-definition';
+import { APP_LOGS_COMMAND_DEFINITION } from '@/commands/app/function-logs/app-logs.command-definition';
+import { type CommandDefinition } from '@/catalog/types/command-definition.type';
+import { APP_APPLY_COMMAND_DEFINITION } from '@/commands/app/apply/app-apply.command-definition';
+import { APP_BUILD_COMMAND_DEFINITION } from '@/commands/app/build/app-build.command-definition';
+import { APP_INIT_COMMAND_DEFINITION } from '@/commands/app/init/app-init.command-definition';
+import { APP_PULL_COMMAND_DEFINITION } from '@/commands/app/pull/app-pull.command-definition';
+import { APP_PLAN_COMMAND_DEFINITION } from '@/commands/app/plan/app-plan.command-definition';
+import { APP_TYPECHECK_COMMAND_DEFINITION } from '@/commands/app/typecheck/app-typecheck.command-definition';
+import { APP_UNINSTALL_COMMAND_DEFINITION } from '@/commands/app/uninstall/app-uninstall.command-definition';
+import { AUTH_LOGIN_COMMAND_DEFINITION } from '@/commands/auth/login/auth-login.command-definition';
+import { AUTH_LOGOUT_COMMAND_DEFINITION } from '@/commands/auth/logout/auth-logout.command-definition';
+import { AUTH_STATUS_COMMAND_DEFINITION } from '@/commands/auth/status/auth-status.command-definition';
+import { AUTH_TOKEN_COMMAND_DEFINITION } from '@/commands/auth/token/auth-token.command-definition';
+import { API_GRAPHQL_COMMAND_DEFINITION } from '@/commands/api/graphql/api-graphql.command-definition';
+import { API_REST_COMMAND_DEFINITION } from '@/commands/api/rest/api-rest.command-definition';
+import { COMMANDS_COMMAND_DEFINITION } from '@/commands/commands/commands.command-definition';
+import { DATA_GET_COMMAND_DEFINITION } from '@/commands/data/get/data-get.command-definition';
+import { DATA_LIST_COMMAND_DEFINITION } from '@/commands/data/list/data-list.command-definition';
+import { DOCTOR_COMMAND_DEFINITION } from '@/commands/doctor/doctor.command-definition';
+import { METADATA_OBJECT_DESCRIBE_COMMAND_DEFINITION } from '@/commands/metadata/object/describe/metadata-object-describe.command-definition';
+import { METADATA_FIELD_LIST_COMMAND_DEFINITION } from '@/commands/metadata/field/list/metadata-field-list.command-definition';
+import { METADATA_FIELD_DESCRIBE_COMMAND_DEFINITION } from '@/commands/metadata/field/describe/metadata-field-describe.command-definition';
+import { METADATA_OBJECT_LIST_COMMAND_DEFINITION } from '@/commands/metadata/object/list/metadata-object-list.command-definition';
+import { OPEN_COMMAND_DEFINITION } from '@/commands/open/open.command-definition';
+import { REMOTE_LIST_COMMAND_DEFINITION } from '@/commands/remote/list/remote-list.command-definition';
+import { REMOTE_REMOVE_COMMAND_DEFINITION } from '@/commands/remote/remove/remote-remove.command-definition';
+import { REMOTE_RENAME_COMMAND_DEFINITION } from '@/commands/remote/rename/remote-rename.command-definition';
+import { REMOTE_USE_COMMAND_DEFINITION } from '@/commands/remote/use/remote-use.command-definition';
+import { VERSION_COMMAND_DEFINITION } from '@/commands/version/version.command-definition';
+
+export const COMMAND_CATALOG: CommandDefinition[] = [
+ APP_ADD_COMMAND_DEFINITION,
+ APP_APPLY_COMMAND_DEFINITION,
+ APP_DEV_COMMAND_DEFINITION,
+ APP_EXEC_COMMAND_DEFINITION,
+ APP_LOGS_COMMAND_DEFINITION,
+ APP_BUILD_COMMAND_DEFINITION,
+ APP_INIT_COMMAND_DEFINITION,
+ APP_PLAN_COMMAND_DEFINITION,
+ APP_PULL_COMMAND_DEFINITION,
+ APP_TYPECHECK_COMMAND_DEFINITION,
+ APP_UNINSTALL_COMMAND_DEFINITION,
+ AUTH_LOGIN_COMMAND_DEFINITION,
+ AUTH_LOGOUT_COMMAND_DEFINITION,
+ AUTH_STATUS_COMMAND_DEFINITION,
+ AUTH_TOKEN_COMMAND_DEFINITION,
+ REMOTE_LIST_COMMAND_DEFINITION,
+ REMOTE_USE_COMMAND_DEFINITION,
+ REMOTE_RENAME_COMMAND_DEFINITION,
+ REMOTE_REMOVE_COMMAND_DEFINITION,
+ API_GRAPHQL_COMMAND_DEFINITION,
+ API_REST_COMMAND_DEFINITION,
+ COMMANDS_COMMAND_DEFINITION,
+ DATA_LIST_COMMAND_DEFINITION,
+ DATA_GET_COMMAND_DEFINITION,
+ DOCTOR_COMMAND_DEFINITION,
+ METADATA_OBJECT_LIST_COMMAND_DEFINITION,
+ METADATA_OBJECT_DESCRIBE_COMMAND_DEFINITION,
+ METADATA_FIELD_LIST_COMMAND_DEFINITION,
+ METADATA_FIELD_DESCRIBE_COMMAND_DEFINITION,
+ OPEN_COMMAND_DEFINITION,
+ VERSION_COMMAND_DEFINITION,
+];
diff --git a/packages/twenty-cli/src/catalog/command-topics.ts b/packages/twenty-cli/src/catalog/command-topics.ts
new file mode 100644
index 00000000000..0d4f532f1cf
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/command-topics.ts
@@ -0,0 +1,43 @@
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { type CommandTopicDefinition } from '@/catalog/types/command-topic-definition.type';
+
+export const COMMAND_TOPICS: CommandTopicDefinition[] = [
+ {
+ path: ['app'],
+ description: 'Create, develop and manage applications',
+ helpGroup: HELP_GROUP.APP,
+ },
+ {
+ path: ['data'],
+ description: 'Read workspace records',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ },
+ {
+ path: ['auth'],
+ description: 'Sign in and manage credentials',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ },
+ {
+ path: ['remote'],
+ description: 'Manage saved workspace connections',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ },
+ {
+ path: ['metadata'],
+ description: 'Inspect the data model',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ },
+ {
+ path: ['metadata', 'object'],
+ description: 'Objects',
+ },
+ {
+ path: ['metadata', 'field'],
+ description: 'Fields',
+ },
+ {
+ path: ['api'],
+ description: 'Send raw REST and GraphQL requests',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ },
+];
diff --git a/packages/twenty-cli/src/catalog/constants/help-group.constant.ts b/packages/twenty-cli/src/catalog/constants/help-group.constant.ts
new file mode 100644
index 00000000000..dec5180e5ad
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/constants/help-group.constant.ts
@@ -0,0 +1,5 @@
+export const HELP_GROUP = {
+ WORKSPACE: 'Workspace:',
+ APP: 'App development:',
+ TOOLS: 'Tools:',
+} as const;
diff --git a/packages/twenty-cli/src/catalog/get-command-name.ts b/packages/twenty-cli/src/catalog/get-command-name.ts
new file mode 100644
index 00000000000..0650e071e91
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/get-command-name.ts
@@ -0,0 +1,4 @@
+import { type CommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const getCommandName = (definition: CommandDefinition) =>
+ definition.path.join(' ');
diff --git a/packages/twenty-cli/src/catalog/read-command-values.ts b/packages/twenty-cli/src/catalog/read-command-values.ts
new file mode 100644
index 00000000000..80a9157c604
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/read-command-values.ts
@@ -0,0 +1,24 @@
+import { isString } from '@sniptt/guards';
+
+export const readStringOption = (
+ options: Record<string, unknown>,
+ optionName: string,
+) => {
+ const value = options[optionName];
+
+ return isString(value) ? value : undefined;
+};
+
+export const readBooleanOption = (
+ options: Record<string, unknown>,
+ optionName: string,
+) => options[optionName] === true;
+
+export const readStringArgument = (
+ commandArguments: unknown[],
+ argumentIndex: number,
+) => {
+ const value = commandArguments[argumentIndex];
+
+ return isString(value) ? value : undefined;
+};
diff --git a/packages/twenty-cli/src/catalog/types/command-argument-definition.type.ts b/packages/twenty-cli/src/catalog/types/command-argument-definition.type.ts
new file mode 100644
index 00000000000..2c6af7bb2a8
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-argument-definition.type.ts
@@ -0,0 +1,5 @@
+export type CommandArgumentDefinition = {
+ name: string;
+ description: string;
+ required: boolean;
+};
diff --git a/packages/twenty-cli/src/catalog/types/command-context.type.ts b/packages/twenty-cli/src/catalog/types/command-context.type.ts
new file mode 100644
index 00000000000..cc001dd992f
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-context.type.ts
@@ -0,0 +1,11 @@
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { type Output } from '@/output/types/output.type';
+
+export type CommandContext = {
+ command: string;
+ arguments: unknown[];
+ options: Record<string, unknown>;
+ output: Output;
+ outputMode: OutputMode;
+ signal: AbortSignal;
+};
diff --git a/packages/twenty-cli/src/catalog/types/command-definition.type.ts b/packages/twenty-cli/src/catalog/types/command-definition.type.ts
new file mode 100644
index 00000000000..1932ca60147
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-definition.type.ts
@@ -0,0 +1,33 @@
+import { type CommandArgumentDefinition } from '@/catalog/types/command-argument-definition.type';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { type CommandOptionDefinition } from '@/catalog/types/command-option-definition.type';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { type OutputMode } from '@/output/types/output-mode.type';
+
+type BaseCommandDefinition = {
+ path: string[];
+ description: string;
+ helpGroup?: string;
+ arguments?: CommandArgumentDefinition[];
+ options?: CommandOptionDefinition[];
+ examples?: string[];
+ outputModes: OutputMode[];
+ writes: boolean;
+ needsProject: boolean;
+ requiredPermissions?: string[];
+};
+
+export type LocalCommandDefinition = BaseCommandDefinition & {
+ needsTarget: false;
+ load: () => Promise<CommandRun<CommandContext>>;
+};
+
+export type TargetCommandDefinition = BaseCommandDefinition & {
+ needsTarget: true;
+ load: () => Promise<CommandRun<TargetCommandContext>>;
+};
+
+export type CommandDefinition =
+ | LocalCommandDefinition
+ | TargetCommandDefinition;
diff --git a/packages/twenty-cli/src/catalog/types/command-option-definition.type.ts b/packages/twenty-cli/src/catalog/types/command-option-definition.type.ts
new file mode 100644
index 00000000000..10d84749104
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-option-definition.type.ts
@@ -0,0 +1,7 @@
+export type CommandOptionDefinition = {
+ flags: string;
+ description: string;
+ choices?: readonly string[];
+ required?: boolean;
+ hidden?: boolean;
+};
diff --git a/packages/twenty-cli/src/catalog/types/command-run.type.ts b/packages/twenty-cli/src/catalog/types/command-run.type.ts
new file mode 100644
index 00000000000..4730f05fa4d
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-run.type.ts
@@ -0,0 +1,6 @@
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { type CommandResult } from '@/output/types/command-result.type';
+
+export type CommandRun<TContext extends CommandContext = CommandContext> = (
+ context: TContext,
+) => Promise<CommandResult>;
diff --git a/packages/twenty-cli/src/catalog/types/command-topic-definition.type.ts b/packages/twenty-cli/src/catalog/types/command-topic-definition.type.ts
new file mode 100644
index 00000000000..c1e84173bcc
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/command-topic-definition.type.ts
@@ -0,0 +1,5 @@
+export type CommandTopicDefinition = {
+ path: string[];
+ description: string;
+ helpGroup?: string;
+};
diff --git a/packages/twenty-cli/src/catalog/types/target-command-context.type.ts b/packages/twenty-cli/src/catalog/types/target-command-context.type.ts
new file mode 100644
index 00000000000..6fb35c9339f
--- /dev/null
+++ b/packages/twenty-cli/src/catalog/types/target-command-context.type.ts
@@ -0,0 +1,6 @@
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+export type TargetCommandContext = CommandContext & {
+ target: ResolvedTarget;
+};
diff --git a/packages/twenty-cli/src/cli.ts b/packages/twenty-cli/src/cli.ts
new file mode 100644
index 00000000000..cf4f22d7074
--- /dev/null
+++ b/packages/twenty-cli/src/cli.ts
@@ -0,0 +1,14 @@
+#!/usr/bin/env node
+import { runCli } from '@/run-cli';
+
+const exitWhenStdoutCloses = (error: NodeJS.ErrnoException) => {
+ if (error.code !== 'EPIPE') {
+ throw error;
+ }
+
+ process.exit();
+};
+
+process.stdout.on('error', exitWhenStdoutCloses);
+
+void runCli(process.argv.slice(2));
diff --git a/packages/twenty-cli/src/commands/api/__tests__/api-commands.spec.ts b/packages/twenty-cli/src/commands/api/__tests__/api-commands.spec.ts
new file mode 100644
index 00000000000..f75ed2ba793
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/__tests__/api-commands.spec.ts
@@ -0,0 +1,369 @@
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+const RESPONSE_CHUNK = 'x'.repeat(1024 * 1024);
+
+const GRAPHQL_RESPONSES: [string, number, unknown][] = [
+ [
+ 'partial',
+ 200,
+ {
+ data: { companies: { totalCount: 3 }, secret: null },
+ errors: [{ message: 'secret failed', path: ['secret'] }],
+ },
+ ],
+ ['unauthorized', 401, { errors: [{ message: 'Not authenticated' }] }],
+ ['notGraphql', 200, { message: 'upstream failed' }],
+ ['nullData', 200, { data: null }],
+];
+
+const server = await startTestServer((request, response) => {
+ if (request.path === '/rest/companies' && request.method === 'GET') {
+ return sendJson(
+ response,
+ 200,
+ { data: { companies: [] } },
+ { 'x-request-id': 'request-200', 'set-cookie': 'session=secret' },
+ );
+ }
+
+ if (request.path === '/rest/companies' && request.method === 'POST') {
+ return sendJson(response, 201, { received: JSON.parse(request.body) });
+ }
+
+ if (request.path === '/rest/unauthorized') {
+ return sendJson(response, 401, { messages: ['Token invalid.'] });
+ }
+
+ if (request.path === '/rest/forbidden') {
+ return sendJson(response, 403, { message: 'Missing permission' });
+ }
+
+ if (request.path === '/rest/missing') {
+ return sendJson(response, 404, { message: 'Record not found' });
+ }
+
+ if (request.path === '/rest/conflict') {
+ return sendJson(response, 409, { message: 'Duplicate record' });
+ }
+
+ if (request.path === '/rest/broken') {
+ return sendJson(
+ response,
+ 500,
+ { message: 'boom' },
+ { 'x-request-id': 'request-500' },
+ );
+ }
+
+ if (request.path === '/rest/redirect') {
+ response.writeHead(302, {
+ location: 'https://elsewhere.example.com/rest/companies',
+ });
+
+ return response.end();
+ }
+
+ if (request.path === '/rest/huge') {
+ response.writeHead(200, { 'content-type': 'application/json' });
+
+ for (let chunkIndex = 0; chunkIndex < 17; chunkIndex++) {
+ response.write(RESPONSE_CHUNK);
+ }
+
+ return response.end();
+ }
+
+ if (request.path === '/rest/image') {
+ response.writeHead(200, { 'content-type': 'image/png' });
+
+ return response.end(Buffer.from([137, 80, 78, 71]));
+ }
+
+ if (request.path === '/metadata') {
+ return sendJson(response, 200, {
+ data: { currentWorkspace: { displayName: 'Acme' } },
+ });
+ }
+
+ const graphqlResponse = GRAPHQL_RESPONSES.find(([marker]) =>
+ request.body.includes(marker),
+ );
+
+ if (isDefined(graphqlResponse)) {
+ return sendJson(response, graphqlResponse[1], graphqlResponse[2]);
+ }
+
+ return sendJson(response, 200, { data: { companies: { totalCount: 3 } } });
+});
+
+const runJson = async (args: string[]) => {
+ const { stdout, exitCode } = await runCliForTest([...args, '--json']);
+
+ return { envelope: parseSingleJsonLine(stdout), exitCode };
+};
+
+describe('api commands', () => {
+ let inputDirectory: string;
+
+ beforeAll(async () => {
+ inputDirectory = await mkdtemp(join(tmpdir(), 'twenty-cli-api-spec-'));
+ });
+
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ server.requests.length = 0;
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ it('sends an authenticated REST request and keeps only safe headers', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ '/rest/companies',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope).toMatchObject({
+ ok: true,
+ command: 'api rest',
+ target: { apiUrl: server.url, source: 'environment' },
+ data: {
+ status: 200,
+ headers: { 'x-request-id': 'request-200' },
+ body: { data: { companies: [] } },
+ },
+ });
+ expect(envelope.data.headers).not.toHaveProperty('set-cookie');
+ expect(server.requests[0].headers.authorization).toBe('Bearer test-key');
+ });
+
+ it.each([
+ ['/rest/unauthorized', 'AUTH_REQUIRED', 3],
+ ['/rest/forbidden', 'PERMISSION_DENIED', 3],
+ ['/rest/missing', 'NOT_FOUND', 4],
+ ['/rest/conflict', 'CONFLICT', 6],
+ ['/rest/broken', 'HTTP_ERROR', 1],
+ ])(
+ 'maps %s to %s with exit code %i',
+ async (path, code, expectedExitCode) => {
+ const { envelope, exitCode } = await runJson(['api', 'rest', path]);
+
+ expect(exitCode).toBe(expectedExitCode);
+ expect(envelope.error.code).toBe(code);
+ },
+ );
+
+ it('keeps the request id on failures', async () => {
+ const { envelope } = await runJson(['api', 'rest', '/rest/broken']);
+
+ expect(envelope.error.details.headers['x-request-id']).toBe('request-500');
+ });
+
+ it('does not follow redirects', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ '/rest/redirect',
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'REDIRECT_NOT_FOLLOWED',
+ details: { redirectOrigin: 'https://elsewhere.example.com' },
+ });
+ expect(server.requests).toHaveLength(1);
+ });
+
+ it('stops reading responses larger than 16 MiB', async () => {
+ const { envelope } = await runJson(['api', 'rest', '/rest/huge']);
+
+ expect(envelope.error.code).toBe('RESPONSE_LIMIT_EXCEEDED');
+ });
+
+ it('refuses binary response bodies', async () => {
+ const { envelope } = await runJson(['api', 'rest', '/rest/image']);
+
+ expect(envelope.error.code).toBe('UNSUPPORTED_RESPONSE_TYPE');
+ });
+
+ it('sends a JSON body read from a file', async () => {
+ const inputPath = join(inputDirectory, 'company.json');
+
+ await writeFile(inputPath, '{"name":"Linear"}');
+
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ '/rest/companies',
+ '--method',
+ 'POST',
+ '--body',
+ `@${inputPath}`,
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.body).toEqual({ received: { name: 'Linear' } });
+ expect(server.requests[0].headers['content-type']).toBe('application/json');
+ });
+
+ it.each([
+ [['--body', '{"name":"Linear"}'], 'USAGE'],
+ [['--method', 'POST', '--body', '{broken'], 'INVALID_INPUT'],
+ ])(
+ 'rejects the body options %j before sending anything',
+ async (options, code) => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ '/rest/companies',
+ ...options,
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe(code);
+ expect(server.requests).toHaveLength(0);
+ },
+ );
+
+ it('refuses absolute URLs without sending the credentials', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ 'https://elsewhere.example.com/rest/companies',
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('INVALID_REQUEST_PATH');
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it('returns GraphQL data from the core or metadata API', async () => {
+ const core = await runJson([
+ 'api',
+ 'graphql',
+ '--query',
+ '{ companies { totalCount } }',
+ ]);
+ const metadata = await runJson([
+ 'api',
+ 'graphql',
+ '--metadata',
+ '--query',
+ '{ currentWorkspace { displayName } }',
+ ]);
+
+ expect(core.envelope.data).toEqual({ companies: { totalCount: 3 } });
+ expect(metadata.envelope.data).toEqual({
+ currentWorkspace: { displayName: 'Acme' },
+ });
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/graphql',
+ '/metadata',
+ ]);
+ });
+
+ it('keeps partial GraphQL data in the error details', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'graphql',
+ '--query',
+ '{ partial }',
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'GRAPHQL_ERROR',
+ message: 'secret failed',
+ details: { data: { companies: { totalCount: 3 }, secret: null } },
+ });
+ });
+
+ it.each([
+ ['{ unauthorized }', 'AUTH_REQUIRED', 3],
+ ['{ notGraphql }', 'INVALID_RESPONSE', 1],
+ ])(
+ 'maps the GraphQL response to %s',
+ async (query, code, expectedExitCode) => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'graphql',
+ '--query',
+ query,
+ ]);
+
+ expect(exitCode).toBe(expectedExitCode);
+ expect(envelope.error.code).toBe(code);
+ },
+ );
+
+ it('accepts a GraphQL result whose data is null', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'graphql',
+ '--query',
+ '{ nullData }',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toBeNull();
+ });
+
+ it.each([
+ [['--query', '{ a }', '--variables', '[1]'], 'INVALID_INPUT'],
+ [['--query', '-', '--variables', '-'], 'USAGE'],
+ ])('rejects the GraphQL inputs %j', async (options, code) => {
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'graphql',
+ ...options,
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe(code);
+ });
+
+ it('reports an unreachable server', async () => {
+ const closedServer = await startTestServer(() => undefined);
+
+ await closedServer.close();
+ vi.stubEnv('TWENTY_API_URL', closedServer.url);
+
+ const { envelope, exitCode } = await runJson([
+ 'api',
+ 'rest',
+ '/rest/companies',
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('NETWORK_ERROR');
+ });
+});
diff --git a/packages/twenty-cli/src/commands/api/format-body.ts b/packages/twenty-cli/src/commands/api/format-body.ts
new file mode 100644
index 00000000000..cf037cb4b99
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/format-body.ts
@@ -0,0 +1,10 @@
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+export const formatBody = (body: unknown) => {
+ if (!isDefined(body)) {
+ return '';
+ }
+
+ return isString(body) ? body : JSON.stringify(body, null, 2);
+};
diff --git a/packages/twenty-cli/src/commands/api/graphql/api-graphql.command-definition.ts b/packages/twenty-cli/src/commands/api/graphql/api-graphql.command-definition.ts
new file mode 100644
index 00000000000..cafb0485791
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/graphql/api-graphql.command-definition.ts
@@ -0,0 +1,35 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const API_GRAPHQL_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['api', 'graphql'],
+ description: 'Send a GraphQL query or mutation',
+ options: [
+ {
+ flags: '--query <query>',
+ description:
+ 'GraphQL document: inline, @file.graphql, or - for standard input',
+ required: true,
+ },
+ {
+ flags: '--variables <json>',
+ description:
+ 'Variables as a JSON object: inline, @file.json, or - for standard input',
+ },
+ {
+ flags: '--metadata',
+ description: 'Send to the metadata API instead of the core API',
+ },
+ ],
+ examples: [
+ "twenty api graphql --query '{ companies(first: 2) { edges { node { name } } } }'",
+ "twenty api graphql --metadata --query '{ currentWorkspace { displayName } }'",
+ 'twenty api graphql --query @create-company.graphql --variables @variables.json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/api/graphql/run-api-graphql-command'))
+ .runApiGraphqlCommand,
+};
diff --git a/packages/twenty-cli/src/commands/api/graphql/run-api-graphql-command.ts b/packages/twenty-cli/src/commands/api/graphql/run-api-graphql-command.ts
new file mode 100644
index 00000000000..896e3a6975a
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/graphql/run-api-graphql-command.ts
@@ -0,0 +1,61 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatBody } from '@/commands/api/format-body';
+import { assertSingleStandardInputReader } from '@/input/assert-single-standard-input-reader';
+import { parseJsonObjectInput } from '@/input/parse-json-input';
+import { readInputValue } from '@/input/read-input-value';
+import { sendGraphqlRequest } from '@/transport/graphql/send-graphql-request';
+
+const readVariables = async (
+ variablesOption: string | undefined,
+ signal: AbortSignal,
+) => {
+ if (!isDefined(variablesOption)) {
+ return undefined;
+ }
+
+ return parseJsonObjectInput({
+ text: await readInputValue({
+ value: variablesOption,
+ optionName: '--variables',
+ signal,
+ }),
+ optionName: '--variables',
+ });
+};
+
+export const runApiGraphqlCommand: CommandRun<TargetCommandContext> = async ({
+ options,
+ target,
+ signal,
+}) => {
+ const queryOption = readStringOption(options, 'query') ?? '';
+ const variablesOption = readStringOption(options, 'variables');
+
+ assertSingleStandardInputReader({
+ '--query': queryOption,
+ '--variables': variablesOption,
+ });
+
+ const query = await readInputValue({
+ value: queryOption,
+ optionName: '--query',
+ signal,
+ });
+ const variables = await readVariables(variablesOption, signal);
+ const data = await sendGraphqlRequest({
+ target,
+ signal,
+ endpoint: readBooleanOption(options, 'metadata') ? 'metadata' : 'core',
+ query,
+ variables,
+ });
+
+ return { data, human: formatBody(data) };
+};
diff --git a/packages/twenty-cli/src/commands/api/rest/api-rest.command-definition.ts b/packages/twenty-cli/src/commands/api/rest/api-rest.command-definition.ts
new file mode 100644
index 00000000000..1c98f6394cc
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/rest/api-rest.command-definition.ts
@@ -0,0 +1,37 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+import { REST_METHODS } from '@/commands/api/rest/constants/rest-methods.constant';
+
+export const API_REST_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['api', 'rest'],
+ description: 'Send a request to the REST API',
+ arguments: [
+ {
+ name: 'path',
+ description: 'Path under the API URL, for example /rest/companies',
+ required: true,
+ },
+ ],
+ options: [
+ {
+ flags: '-X, --method <method>',
+ description: 'HTTP method, defaults to GET; required with --body',
+ choices: REST_METHODS,
+ },
+ {
+ flags: '--body <json>',
+ description: 'Request body: JSON, @file.json, or - for standard input',
+ },
+ ],
+ examples: [
+ "twenty api rest '/rest/companies?limit=5'",
+ 'twenty api rest /rest/companies --method POST --body \'{"name":"Linear"}\'',
+ 'twenty api rest /rest/companies/<id> --method PATCH --body @changes.json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/api/rest/run-api-rest-command'))
+ .runApiRestCommand,
+};
diff --git a/packages/twenty-cli/src/commands/api/rest/constants/rest-methods.constant.ts b/packages/twenty-cli/src/commands/api/rest/constants/rest-methods.constant.ts
new file mode 100644
index 00000000000..2f6e0242ed3
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/rest/constants/rest-methods.constant.ts
@@ -0,0 +1 @@
+export const REST_METHODS = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'] as const;
diff --git a/packages/twenty-cli/src/commands/api/rest/run-api-rest-command.ts b/packages/twenty-cli/src/commands/api/rest/run-api-rest-command.ts
new file mode 100644
index 00000000000..fff22c4f4dc
--- /dev/null
+++ b/packages/twenty-cli/src/commands/api/rest/run-api-rest-command.ts
@@ -0,0 +1,65 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ readStringArgument,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatBody } from '@/commands/api/format-body';
+import { parseJsonInput } from '@/input/parse-json-input';
+import { readInputValue } from '@/input/read-input-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { sendRestRequest } from '@/transport/send-rest-request';
+
+const DEFAULT_METHOD = 'GET';
+
+const readRequestBody = async (
+ body: string | undefined,
+ signal: AbortSignal,
+) => {
+ if (!isDefined(body)) {
+ return undefined;
+ }
+
+ const text = await readInputValue({
+ value: body,
+ optionName: '--body',
+ signal,
+ });
+
+ parseJsonInput({ text, optionName: '--body' });
+
+ return text;
+};
+
+export const runApiRestCommand: CommandRun<TargetCommandContext> = async ({
+ arguments: commandArguments,
+ options,
+ target,
+ signal,
+}) => {
+ const path = readStringArgument(commandArguments, 0) ?? '';
+ const method = readStringOption(options, 'method');
+ const body = readStringOption(options, 'body');
+
+ if (isDefined(body) && !isDefined(method)) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'A request body needs an explicit method.',
+ hint: 'Add --method POST, PATCH or PUT.',
+ });
+ }
+
+ const response = await sendRestRequest({
+ target,
+ signal,
+ method: method ?? DEFAULT_METHOD,
+ path,
+ body: await readRequestBody(body, signal),
+ });
+
+ return { data: response, human: formatBody(response.body) };
+};
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts
new file mode 100644
index 00000000000..25e5ee43036
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts
@@ -0,0 +1,335 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import { promptForAppAddValue } from '@/app/add/prompt-for-app-add-value';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { CliError } from '@/output/cli-error';
+
+vi.mock('@/app/read-app-identity', () => ({ readAppIdentity: vi.fn() }));
+vi.mock('@/app/add/prompt-for-app-add-value', () => ({
+ promptForAppAddValue: vi.fn(),
+}));
+
+const OBJECT_IDENTIFIER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+describe('app add', () => {
+ let root: string;
+ let appPath: string;
+ const run = (args: string[]) => runCliForTest(['app', 'add', ...args]);
+ const runJson = async (args: string[]) => {
+ const result = await run([...args, '--json']);
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-app-add-'));
+ appPath = join(root, 'app');
+ await mkdir(appPath);
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'test-app',
+ dependencies: { 'twenty-sdk': '2.44.0' },
+ }),
+ );
+ vi.spyOn(process, 'cwd').mockReturnValue(appPath);
+ vi.mocked(readAppIdentity).mockResolvedValue({
+ application: {
+ universalIdentifier: OBJECT_IDENTIFIER,
+ displayName: 'App',
+ },
+ diagnostics: [],
+ });
+ vi.mocked(promptForAppAddValue).mockReset();
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it.each([
+ {
+ entity: 'object',
+ name: 'invoice',
+ options: ['--name-plural', 'invoices'],
+ path: 'src/objects/invoice.ts',
+ define: 'defineObject',
+ },
+ {
+ entity: 'field',
+ name: 'amount',
+ options: ['--type', 'NUMBER', '--object', OBJECT_IDENTIFIER],
+ path: 'src/fields/amount.ts',
+ define: 'defineField',
+ },
+ {
+ entity: 'logic-function',
+ name: 'SendInvoice',
+ options: [],
+ path: 'src/logic-functions/send-invoice.ts',
+ define: 'defineLogicFunction',
+ },
+ {
+ entity: 'front-component',
+ name: 'InvoicePanel',
+ options: [],
+ path: 'src/front-components/invoice-panel.tsx',
+ define: 'defineFrontComponent',
+ },
+ ])(
+ 'creates a standalone $entity definition with app-relative JSON paths',
+ async ({ entity, name, options, path, define }) => {
+ const result = await runJson([entity, '--name', name, ...options]);
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.envelope.data).toEqual({
+ app: { name: 'test-app', path: appPath },
+ entity,
+ name,
+ createdPaths: [path],
+ diagnostics: [],
+ });
+ const content = await readFile(join(appPath, path), 'utf8');
+
+ expect(content).toContain(`export default ${define}({`);
+ expect(content).toMatch(
+ /universalIdentifier: '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'/,
+ );
+ expect(await readdir(join(appPath, 'src'), { recursive: true })).toEqual(
+ expect.arrayContaining([path.slice(4)]),
+ );
+ expect(vi.mocked(promptForAppAddValue)).not.toHaveBeenCalled();
+ },
+ );
+
+ it('uses the containing app from a nested folder and honors --path from outside it', async () => {
+ const nestedPath = join(appPath, 'src', 'nested');
+
+ await mkdir(nestedPath, { recursive: true });
+ vi.spyOn(process, 'cwd').mockReturnValue(nestedPath);
+ expect(
+ (await runJson(['logic-function', '--name', 'first'])).exitCode,
+ ).toBe(0);
+ vi.spyOn(process, 'cwd').mockReturnValue(root);
+ expect(
+ (await runJson(['logic-function', '--name', 'second', '--path', 'app']))
+ .exitCode,
+ ).toBe(0);
+ expect(await readdir(join(appPath, 'src', 'logic-functions'))).toEqual([
+ 'first.ts',
+ 'second.ts',
+ ]);
+ });
+
+ it('refuses a normalized filename collision without changing the existing definition', async () => {
+ await runJson(['logic-function', '--name', 'SendInvoice']);
+ const path = join(appPath, 'src/logic-functions/send-invoice.ts');
+ const original = await readFile(path, 'utf8');
+ const result = await runJson(['logic-function', '--name', 'send-invoice']);
+
+ expect(result.exitCode).toBe(6);
+ expect(result.envelope.error.code).toBe('APP_PATH_UNAVAILABLE');
+ expect(await readFile(path, 'utf8')).toBe(original);
+ expect(await readdir(join(appPath, 'src/logic-functions'))).toEqual([
+ 'send-invoice.ts',
+ ]);
+ });
+
+ it('refuses a symlinked destination before writing outside the app', async () => {
+ const outside = join(root, 'outside');
+
+ await mkdir(outside);
+ await symlink(outside, join(appPath, 'src'));
+ const result = await runJson(['logic-function', '--name', 'send-invoice']);
+
+ expect(result.exitCode).toBe(6);
+ expect(await readdir(outside)).toEqual([]);
+ });
+
+ it.each([
+ [],
+ ['object', '--name', 'invoice'],
+ ['object', '--name', 'invoice', '--name-plural', 'invoice'],
+ ['field', '--name', 'amount'],
+ ['field', '--name', 'amount', '--object', 'fill-later'],
+ [
+ 'field',
+ '--name',
+ 'amount',
+ '--object',
+ 'aaaaaaaa-aaaa-1aaa-8aaa-aaaaaaaaaaaa',
+ ],
+ [
+ 'field',
+ '--name',
+ 'amount',
+ '--object',
+ OBJECT_IDENTIFIER,
+ '--type',
+ 'BOGUS',
+ ],
+ [
+ 'field',
+ '--name',
+ 'amount',
+ '--object',
+ OBJECT_IDENTIFIER,
+ '--on-delete',
+ 'CASCADE',
+ ],
+ [
+ 'field',
+ '--name',
+ 'invoices',
+ '--object',
+ OBJECT_IDENTIFIER,
+ '--type',
+ 'RELATION',
+ ],
+ ['view', '--name', 'invoices'],
+ ['logic-function', '--name', '../..'],
+ ['logic-function', '--name', 'send-invoice', '--name-plural', 'invoices'],
+ ])(
+ 'rejects incomplete or invalid input %j without prompting or writing',
+ async (...args) => {
+ const result = await runJson(args);
+
+ expect(result.exitCode, result.stdout).toBe(2);
+ expect(result.envelope.error.code).toBe('USAGE');
+ expect(promptForAppAddValue).not.toHaveBeenCalled();
+ expect(await readdir(appPath)).toEqual(['package.json']);
+ },
+ );
+
+ it('retains relation endpoint identifiers and creates only the requested field', async () => {
+ const targetObject = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+ const targetField = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+ const result = await runJson([
+ 'field',
+ '--name',
+ 'invoices',
+ '--object',
+ OBJECT_IDENTIFIER,
+ '--type',
+ 'MORPH_RELATION',
+ '--target-object',
+ targetObject,
+ '--target-field',
+ targetField,
+ '--relation-type',
+ 'ONE_TO_MANY',
+ '--on-delete',
+ 'None',
+ ]);
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ const content = await readFile(
+ join(appPath, 'src/fields/invoices.ts'),
+ 'utf8',
+ );
+
+ expect(content).toContain(
+ `objectUniversalIdentifier: '${OBJECT_IDENTIFIER}'`,
+ );
+ expect(content).toContain(
+ `relationTargetObjectMetadataUniversalIdentifier: '${targetObject}'`,
+ );
+ expect(content).toContain(
+ `relationTargetFieldMetadataUniversalIdentifier: '${targetField}'`,
+ );
+ expect(content).toContain('morphId:');
+ expect(content).not.toContain('OnDeleteAction');
+ expect(await readdir(join(appPath, 'src/fields'))).toEqual(['invoices.ts']);
+ });
+
+ it('accepts newer universal identifier versions supported by the manifest validator', async () => {
+ const identifier = 'aaaaaaaa-aaaa-7aaa-8aaa-aaaaaaaaaaaa';
+ const result = await runJson([
+ 'field',
+ '--name',
+ 'amount',
+ '--object',
+ identifier,
+ ]);
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(
+ await readFile(join(appPath, 'src/fields/amount.ts'), 'utf8'),
+ ).toContain(`objectUniversalIdentifier: '${identifier}'`);
+ });
+
+ it('prompts only in a human interactive terminal and reports the created file', async () => {
+ vi.stubEnv('CI', 'false');
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ isTerminal: true }),
+ );
+ vi.mocked(promptForAppAddValue)
+ .mockResolvedValueOnce('logic-function')
+ .mockResolvedValueOnce('send-invoice');
+ const result = await run([]);
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(result.stdout).toContain(
+ 'Created src/logic-functions/send-invoice.ts',
+ );
+ expect(promptForAppAddValue).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not prompt with --no-input', async () => {
+ const result = await run(['object', '--no-input']);
+
+ expect(result.exitCode).toBe(2);
+ expect(promptForAppAddValue).not.toHaveBeenCalled();
+ expect(await readdir(appPath)).toEqual(['package.json']);
+ });
+
+ it('checks the app identity before asking any interactive questions', async () => {
+ vi.stubEnv('CI', 'false');
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ isTerminal: true }),
+ );
+ vi.mocked(readAppIdentity).mockResolvedValue({
+ application: null,
+ diagnostics: [],
+ });
+
+ const result = await run([]);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain('No application definition found');
+ expect(promptForAppAddValue).not.toHaveBeenCalled();
+ expect(await readdir(appPath)).toEqual(['package.json']);
+ });
+
+ it('leaves app files untouched when the interactive prompt is cancelled', async () => {
+ vi.stubEnv('CI', 'false');
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ isTerminal: true }),
+ );
+ vi.mocked(promptForAppAddValue).mockRejectedValue(
+ new CliError({ code: 'CANCELLED', message: 'Cancelled.', exitCode: 130 }),
+ );
+
+ expect((await run([])).exitCode).toBe(130);
+ expect(await readdir(appPath)).toEqual(['package.json']);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.ts
new file mode 100644
index 00000000000..4508e342f2f
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.ts
@@ -0,0 +1,1862 @@
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { writeTestSourceSdk } from '@/app/__tests__/utils/write-test-source-sdk';
+import { createHash } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';
+import { isArray, isString } from '@sniptt/guards';
+import { type ServerResponse } from 'node:http';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import {
+ afterAll,
+ beforeAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import {
+ type RecordedRequest,
+ sendJson,
+ startTestServer,
+} from '@/__tests__/utils/start-test-server';
+
+const worker = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => worker,
+}));
+
+let workerDirectory: string;
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-command-worker-'));
+ await buildTestAppWorker(workerDirectory, { useToolingFixture: true });
+ worker.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60_000);
+
+afterAll(() => rm(workerDirectory, { recursive: true, force: true }));
+
+const APPLICATION = {
+ universalIdentifier: '6a0c9d8e-8f5f-4c43-9b8e-0e1f2a3b4c5d',
+ name: 'apply-app',
+ displayName: 'Apply App',
+};
+const MANIFEST = { application: APPLICATION };
+const WORKSPACE_ID = '48eb6ca1-dbd6-492e-8b53-5785a266c454';
+const EXPORTED_MANIFEST = {
+ application: { ...APPLICATION, displayName: 'Server-normalized app' },
+ objects: [],
+ fields: [],
+ logicFunctions: [],
+ frontComponents: [],
+ permissionFlags: [],
+ roles: [],
+ skills: [],
+ agents: [],
+ views: [],
+ viewFields: [],
+ navigationMenuItems: [],
+ pageLayouts: [],
+ pageLayoutTabs: [],
+ pageLayoutWidgets: [],
+ commandMenuItems: [],
+ timelineActivityTypes: [],
+ settingsMenuItems: [],
+ publicAssets: [],
+};
+const APPLICATION_EXPORT = {
+ application: { ...APPLICATION, sourceType: 'LOCAL' },
+ manifest: EXPORTED_MANIFEST,
+ coverage: [],
+ files: [],
+};
+const FILES = [
+ {
+ path: 'logic-functions/hello.mjs',
+ role: 'built-logic-function',
+ content: 'export default () => "hello";',
+ },
+ { path: 'public/logo.svg', role: 'public-asset', content: '<svg></svg>' },
+];
+const CREATE_ACTION = {
+ type: 'create',
+ metadataName: 'logicFunction',
+ flatEntity: { name: 'hello' },
+};
+const OBJECT_DELETION = {
+ type: 'delete',
+ metadataName: 'objectMetadata',
+ universalIdentifier: 'object-id',
+ flatEntity: { nameSingular: 'invoice' },
+};
+const SCHEMA =
+ 'type Query { companies: [Company!]! } type Company { id: ID! name: String! }';
+
+type ServerState = {
+ isRegistered: boolean;
+ previewActions: unknown[];
+ registrationError?: string;
+ installError?: string;
+ uploadTargetsStatus?: number;
+ completeError?: string;
+ syncError?: string;
+ syncResponseOverride?: unknown;
+ failingUploadFileId?: string;
+ hasInvalidFirstUploadUrl: boolean;
+ heldUploadFileId?: string;
+ wasSnapshotPresentDuringHeldUpload?: boolean;
+ isSyncHeld: boolean;
+ heldSyncResponse?: ServerResponse;
+ wasSnapshotPresentAtSync?: boolean;
+ snapshotPath: string;
+ workspaceResponse?: unknown;
+ exportResponse?: unknown;
+ exportStatus?: number;
+ isExportHeld?: boolean;
+ heldExportResponse?: ServerResponse;
+ schemaResponse?: unknown;
+ schemaError?: string;
+ isSchemaHeld?: boolean;
+ heldSchemaResponse?: ServerResponse;
+};
+
+const state: ServerState = {
+ isRegistered: true,
+ previewActions: [CREATE_ACTION],
+ hasInvalidFirstUploadUrl: false,
+ isSyncHeld: false,
+ snapshotPath: '',
+};
+
+const graphqlError = (code: string, subCode?: string) => ({
+ data: null,
+ errors: [
+ {
+ message: 'The server refused the request.',
+ extensions: { code, subCode },
+ },
+ ],
+});
+
+const getOperation = (request: RecordedRequest) => {
+ if (request.method === 'PUT') {
+ return 'put';
+ }
+
+ const { query, arguments: variables } = readGraphqlRequest(request);
+
+ if (variables.dryRun === true) {
+ return 'preview';
+ }
+
+ return (
+ [
+ ['createApplicationRegistration', 'registration'],
+ ['createDevelopmentApplication', 'installation'],
+ ['createApplicationFileUploads', 'upload-targets'],
+ ['completeApplicationFileUploads', 'upload-complete'],
+ ['syncApplication', 'sync'],
+ ['applicationCoreGraphqlSchema', 'schema'],
+ ['currentWorkspace', 'workspace'],
+ ['exportApplication', 'export'],
+ ].find(([field]) => query.includes(field))?.[1] ?? 'unknown'
+ );
+};
+
+const readUniversalIdentifier = (variables: Record<string, unknown>) => {
+ const manifest = isPlainObject(variables.manifest)
+ ? variables.manifest
+ : undefined;
+ const application = isPlainObject(manifest?.application)
+ ? manifest.application
+ : undefined;
+ const input = isPlainObject(variables.input) ? variables.input : undefined;
+
+ return [
+ application?.universalIdentifier,
+ input?.universalIdentifier,
+ variables.universalIdentifier,
+ ]
+ .find(isString)
+ ?.toLowerCase();
+};
+
+const syncResponse = (variables: Record<string, unknown>) => ({
+ data: {
+ syncApplication: {
+ applicationUniversalIdentifier: readUniversalIdentifier(variables),
+ actions: state.previewActions,
+ },
+ },
+});
+
+const server = await startTestServer((request, response) => {
+ const operation = getOperation(request);
+
+ if (operation === 'put') {
+ if (request.path.endsWith(`/${state.heldUploadFileId}`)) {
+ setTimeout(() => {
+ state.wasSnapshotPresentDuringHeldUpload = existsSync(
+ state.snapshotPath,
+ );
+ sendJson(response, 200, {});
+ }, 300);
+
+ return;
+ }
+
+ return sendJson(
+ response,
+ request.path.endsWith(`/${state.failingUploadFileId}`) ? 500 : 200,
+ {},
+ );
+ }
+
+ const { arguments: variables } = readGraphqlRequest(request);
+
+ if (operation === 'preview') {
+ return sendJson(
+ response,
+ 200,
+ state.isRegistered
+ ? syncResponse(variables)
+ : graphqlError('NOT_FOUND', 'APPLICATION_NOT_FOUND'),
+ );
+ }
+
+ if (operation === 'registration') {
+ if (isDefined(state.registrationError)) {
+ state.isRegistered = true;
+
+ return sendJson(response, 200, graphqlError(state.registrationError));
+ }
+
+ state.isRegistered = true;
+
+ return sendJson(response, 200, {
+ data: {
+ createApplicationRegistration: {
+ applicationRegistration: {
+ id: 'registration-id',
+ universalIdentifier: readUniversalIdentifier(variables),
+ },
+ },
+ },
+ });
+ }
+
+ if (operation === 'installation') {
+ return sendJson(
+ response,
+ 200,
+ isDefined(state.installError)
+ ? graphqlError(state.installError)
+ : {
+ data: {
+ createDevelopmentApplication: {
+ id: 'application-id',
+ universalIdentifier: readUniversalIdentifier(variables),
+ },
+ },
+ },
+ );
+ }
+
+ if (operation === 'upload-targets') {
+ if (isDefined(state.uploadTargetsStatus)) {
+ return sendJson(response, state.uploadTargetsStatus, {
+ message: 'Storage is unavailable.',
+ });
+ }
+
+ const files = isArray(variables.files) ? variables.files : [];
+
+ return sendJson(response, 200, {
+ data: {
+ createApplicationFileUploads: {
+ targets: files.filter(isPlainObject).map((file, index) => ({
+ fileId: `file-${index}`,
+ filePath: file.filePath,
+ uploadUrl:
+ state.hasInvalidFirstUploadUrl && index === 0
+ ? 'ftp://storage.example.com/upload'
+ : `${server.url}/upload/file-${index}`,
+ contentType: 'application/octet-stream',
+ })),
+ errors: [],
+ },
+ },
+ });
+ }
+
+ if (operation === 'upload-complete') {
+ return sendJson(
+ response,
+ 200,
+ isDefined(state.completeError)
+ ? graphqlError(state.completeError)
+ : { data: { completeApplicationFileUploads: { errors: [] } } },
+ );
+ }
+
+ if (operation === 'sync') {
+ state.wasSnapshotPresentAtSync = existsSync(state.snapshotPath);
+
+ if (isDefined(state.syncError)) {
+ return sendJson(response, 200, graphqlError(state.syncError));
+ }
+
+ if (isDefined(state.syncResponseOverride)) {
+ return sendJson(response, 200, state.syncResponseOverride);
+ }
+
+ if (state.isSyncHeld) {
+ state.heldSyncResponse = response;
+
+ return;
+ }
+
+ return sendJson(response, 200, syncResponse(variables));
+ }
+
+ if (operation === 'workspace') {
+ return sendJson(
+ response,
+ 200,
+ state.workspaceResponse ?? {
+ data: { currentWorkspace: { id: WORKSPACE_ID } },
+ },
+ );
+ }
+
+ if (operation === 'export') {
+ if (state.isExportHeld) {
+ state.heldExportResponse = response;
+ return;
+ }
+ return sendJson(
+ response,
+ state.exportStatus ?? 200,
+ state.exportResponse ?? {
+ data: { exportApplication: APPLICATION_EXPORT },
+ },
+ );
+ }
+
+ if (operation === 'schema') {
+ if (state.isSchemaHeld) {
+ state.heldSchemaResponse = response;
+
+ return;
+ }
+
+ if (
+ variables.applicationUniversalIdentifier !==
+ APPLICATION.universalIdentifier
+ ) {
+ return sendJson(
+ response,
+ 200,
+ graphqlError('NOT_FOUND', 'APPLICATION_NOT_FOUND'),
+ );
+ }
+
+ return sendJson(
+ response,
+ 200,
+ isDefined(state.schemaError)
+ ? graphqlError(state.schemaError)
+ : (state.schemaResponse ?? {
+ data: { applicationCoreGraphqlSchema: SCHEMA },
+ }),
+ );
+ }
+
+ return sendJson(response, 400, { errors: [{ message: 'Unexpected' }] });
+});
+
+describe('app apply', () => {
+ let appPath: string;
+
+ const run = (...args: string[]) =>
+ runCliForTest(['app', 'apply', '--path', appPath, ...args]);
+ const runJson = async (...args: string[]) => {
+ const result = await run(...args, '--json');
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+ const operations = () => server.requests.map(getOperation);
+ const readReleasedBuildId = () =>
+ readFile(join(appPath, 'released.txt'), 'utf8');
+
+ const writeTooling = async ({
+ corruptPath,
+ application = APPLICATION,
+ generateClientBody,
+ editDuringBuild,
+ }: {
+ corruptPath?: string;
+ application?: typeof APPLICATION;
+ generateClientBody?: string;
+ editDuringBuild?: { relativePath: string; content: string };
+ } = {}) => {
+ await writeFile(
+ join(appPath, 'test-tooling.cjs'),
+ `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ const { createHash } = require('node:crypto');
+ const FILES = ${JSON.stringify(FILES)};
+ const CORRUPT_PATH = ${JSON.stringify(corruptPath ?? null)};
+ const EDIT_DURING_BUILD = ${JSON.stringify(editDuringBuild ?? null)};
+ const sha256 = (content) => createHash('sha256').update(content).digest('hex');
+ let snapshotDirectory;
+ exports.buildSourceSnapshot = async ({ appPath }) => {
+ if (EDIT_DURING_BUILD) {
+ fs.writeFileSync(path.join(appPath, EDIT_DURING_BUILD.relativePath), EDIT_DURING_BUILD.content);
+ }
+ snapshotDirectory = path.join(appPath, '.twenty', 'cli', 'snapshots', 'build-test');
+ const filesDirectory = path.join(snapshotDirectory, 'files');
+ const files = FILES.map((file) => {
+ const absolutePath = path.join(filesDirectory, file.path);
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
+ fs.writeFileSync(absolutePath, file.content);
+ return {
+ path: file.path,
+ role: file.role,
+ sourcePath: 'src/' + path.basename(file.path),
+ size: Buffer.byteLength(file.content),
+ sha256: sha256(file.path === CORRUPT_PATH ? 'changed' : file.content),
+ };
+ });
+ return {
+ success: true,
+ data: {
+ buildId: 'build-id',
+ directory: filesDirectory,
+ contentHash: 'a'.repeat(64),
+ application: ${JSON.stringify(application)},
+ manifestFormat: 'twenty-application',
+ manifest: ${JSON.stringify({ application })},
+ files,
+ },
+ diagnostics: [],
+ };
+ };
+ exports.releaseSourceSnapshot = async ({ buildId }) => {
+ fs.rmSync(snapshotDirectory, { recursive: true, force: true });
+ fs.writeFileSync(path.join(__dirname, 'released.txt'), buildId);
+ return { success: true, data: null, diagnostics: [] };
+ };
+ ${isDefined(generateClientBody) ? `exports.generateApplicationClient = async ({ appPath, schema, signal }) => { ${generateClientBody} };` : ''}
+ `,
+ );
+ };
+
+ const enableClientGeneration = async (
+ body?: string,
+ application = APPLICATION,
+ ) => {
+ await mkdir(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ });
+
+ await writeTooling({ generateClientBody: body, application });
+ };
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-apply-'));
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'apply-app',
+ devDependencies: { 'twenty-sdk': '9.9.9' },
+ }),
+ );
+ await writeTestSourceSdk({ appPath });
+ await writeTooling();
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'apply-test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('CI', '');
+ Object.assign(state, {
+ isRegistered: true,
+ previewActions: [CREATE_ACTION],
+ registrationError: undefined,
+ installError: undefined,
+ uploadTargetsStatus: undefined,
+ completeError: undefined,
+ syncError: undefined,
+ syncResponseOverride: undefined,
+ failingUploadFileId: undefined,
+ hasInvalidFirstUploadUrl: false,
+ heldUploadFileId: undefined,
+ wasSnapshotPresentDuringHeldUpload: undefined,
+ isSyncHeld: false,
+ heldSyncResponse: undefined,
+ wasSnapshotPresentAtSync: undefined,
+ snapshotPath: join(appPath, '.twenty', 'cli', 'snapshots', 'build-test'),
+ workspaceResponse: undefined,
+ exportResponse: undefined,
+ exportStatus: undefined,
+ isExportHeld: false,
+ heldExportResponse: undefined,
+ schemaResponse: undefined,
+ schemaError: undefined,
+ isSchemaHeld: false,
+ heldSchemaResponse: undefined,
+ });
+ server.requests.length = 0;
+ });
+
+ afterEach(() => {
+ state.heldSyncResponse?.end();
+ state.heldExportResponse?.end();
+ state.heldSchemaResponse?.end();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ afterAll(() => server.close());
+
+ it.each([true, false])(
+ 'previews, installs, uploads without credentials, then syncs with deletion inference %s',
+ async (inferDeletion) => {
+ const { envelope, exitCode } = await runJson(
+ ...(inferDeletion ? [] : ['--no-delete']),
+ );
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ application: APPLICATION,
+ inferDeletionFromMissingEntities: inferDeletion,
+ registrationCreated: false,
+ completedPhases: [
+ 'build',
+ 'preview',
+ 'installation',
+ 'upload',
+ 'sync',
+ 'pullBase',
+ ],
+ actions: [CREATE_ACTION],
+ summary: { create: 1, update: 0, delete: 0, destructive: 0 },
+ upload: { fileCount: 2, byteCount: 40 },
+ clientGeneration: 'skipped',
+ });
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'CLIENT_NOT_GENERATED' }),
+ ]);
+ expect(operations()).toEqual([
+ 'preview',
+ 'installation',
+ 'upload-targets',
+ 'put',
+ 'put',
+ 'upload-complete',
+ 'sync',
+ 'workspace',
+ 'export',
+ ]);
+
+ const [preview, , uploadTargets] = server.requests;
+ const sync = server.requests.find(
+ (request) => getOperation(request) === 'sync',
+ );
+
+ expect(readGraphqlRequest(preview).arguments).toMatchObject({
+ manifest: MANIFEST,
+ inferDeletionFromMissingEntities: inferDeletion,
+ });
+ expect(isDefined(sync) && readGraphqlRequest(sync)).toMatchObject({
+ query: expect.not.stringContaining('dryRun'),
+ arguments: {
+ manifest: MANIFEST,
+ inferDeletionFromMissingEntities: inferDeletion,
+ },
+ });
+ expect(readGraphqlRequest(uploadTargets).arguments).toMatchObject({
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ files: [
+ {
+ fileFolder: 'BuiltLogicFunction',
+ filePath: 'logic-functions/hello.mjs',
+ size: 29,
+ },
+ { fileFolder: 'PublicAsset', filePath: 'public/logo.svg', size: 11 },
+ ],
+ });
+
+ const puts = server.requests.filter(
+ (request) => request.method === 'PUT',
+ );
+
+ expect(puts.map((request) => request.body).sort()).toEqual(
+ FILES.map((file) => file.content).sort(),
+ );
+ expect(
+ puts.every((request) => !isDefined(request.headers.authorization)),
+ ).toBe(true);
+ expect(state.wasSnapshotPresentAtSync).toBe(true);
+ expect(await readReleasedBuildId()).toBe('build-id');
+ expect(existsSync(state.snapshotPath)).toBe(false);
+ },
+ );
+
+ it('accepts the lowercase identifier the server returns for an uppercase manifest identifier', async () => {
+ await writeTooling({
+ application: {
+ ...APPLICATION,
+ universalIdentifier: APPLICATION.universalIdentifier.toUpperCase(),
+ },
+ });
+
+ const { exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(operations().at(-1)).toBe('export');
+ });
+
+ it('records the fresh remote export without changing the legacy base or local source', async () => {
+ const legacyBasePath = join(appPath, '.twenty', 'pull-base.json');
+ const sourcePath = join(appPath, 'application.ts');
+ await mkdir(join(appPath, '.twenty'), { recursive: true });
+ await writeFile(legacyBasePath, 'legacy baseline');
+ await writeFile(sourcePath, 'unrelated local edits');
+ vi.stubEnv('TWENTY_API_URL', `${server.url}/`);
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('recorded');
+ expect(
+ JSON.parse(
+ await readFile(join(appPath, '.twenty/cli/pull-base.json'), 'utf8'),
+ ),
+ ).toEqual({
+ version: 2,
+ target: { apiUrl: server.url, workspaceId: WORKSPACE_ID },
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ manifest: EXPORTED_MANIFEST,
+ sourceFingerprints: {
+ 'application.ts': createHash('sha256')
+ .update('unrelated local edits')
+ .digest('hex'),
+ },
+ });
+ expect(await readFile(legacyBasePath, 'utf8')).toBe('legacy baseline');
+ expect(await readFile(sourcePath, 'utf8')).toBe('unrelated local edits');
+ const exportRequest = server.requests.find(
+ (request) => getOperation(request) === 'export',
+ );
+ expect(exportRequest?.headers.authorization).toBe('Bearer apply-test-key');
+ expect(
+ exportRequest && readGraphqlRequest(exportRequest).arguments,
+ ).toEqual({
+ universalIdentifier: APPLICATION.universalIdentifier,
+ });
+ expect((await readdir(join(appPath, '.twenty/cli'))).sort()).toEqual([
+ 'pull-base.json',
+ 'snapshots',
+ ]);
+ });
+
+ it('fingerprints the source files as they were built, not as edited during the build', async () => {
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(join(appPath, 'src/role.ts'), 'applied role');
+ await mkdir(join(appPath, 'locales'), { recursive: true });
+ await writeFile(join(appPath, 'locales/fr-FR.json'), '{"Pet":"Animal"}');
+ await writeTooling({
+ editDuringBuild: {
+ relativePath: 'src/role.ts',
+ content: 'edited during the build',
+ },
+ });
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('recorded');
+ expect(
+ JSON.parse(
+ await readFile(join(appPath, '.twenty/cli/pull-base.json'), 'utf8'),
+ ).sourceFingerprints,
+ ).toEqual({
+ 'locales/fr-FR.json': createHash('sha256')
+ .update('{"Pet":"Animal"}')
+ .digest('hex'),
+ 'src/role.ts': createHash('sha256').update('applied role').digest('hex'),
+ });
+ expect(await readFile(join(appPath, 'src/role.ts'), 'utf8')).toBe(
+ 'edited during the build',
+ );
+ });
+
+ it.each([
+ ['missing workspace', { data: { currentWorkspace: null } }, undefined],
+ [
+ 'invalid workspace UUID',
+ { data: { currentWorkspace: { id: 'not-a-uuid' } } },
+ undefined,
+ ],
+ [
+ 'non-object application manifest',
+ undefined,
+ {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ manifest: { ...EXPORTED_MANIFEST, application: null },
+ },
+ },
+ },
+ ],
+ ['missing export', undefined, { data: { exportApplication: null } }],
+ [
+ 'wrong app',
+ undefined,
+ {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ application: {
+ ...APPLICATION_EXPORT.application,
+ universalIdentifier: WORKSPACE_ID,
+ },
+ },
+ },
+ },
+ ],
+ [
+ 'wrong manifest',
+ undefined,
+ {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ manifest: {
+ ...EXPORTED_MANIFEST,
+ application: {
+ ...APPLICATION,
+ universalIdentifier: WORKSPACE_ID,
+ },
+ },
+ },
+ },
+ },
+ ],
+ [
+ 'non-object manifest',
+ undefined,
+ {
+ data: {
+ exportApplication: { ...APPLICATION_EXPORT, manifest: null },
+ },
+ },
+ ],
+ [
+ 'non-string coverage status',
+ undefined,
+ {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ coverage: [
+ {
+ metadataName: 'object',
+ universalIdentifier: WORKSPACE_ID,
+ status: null,
+ reason: null,
+ },
+ ],
+ },
+ },
+ },
+ ],
+ ])(
+ 'preserves the previous base after a successful sync and %s',
+ async (_description, workspaceResponse, exportResponse) => {
+ const basePath = join(appPath, '.twenty/cli/pull-base.json');
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await writeFile(basePath, 'previous baseline');
+ state.workspaceResponse = workspaceResponse;
+ state.exportResponse = exportResponse;
+ await enableClientGeneration(
+ 'return { success: true, data: null, diagnostics: [] };',
+ );
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ pullBase: 'failed',
+ clientGeneration: 'generated',
+ });
+ expect(envelope.data.completedPhases).not.toContain('pullBase');
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ ]);
+ expect(await readFile(basePath, 'utf8')).toBe('previous baseline');
+ expect(operations()).toContain('schema');
+ },
+ );
+
+ it('refuses source exports before changing the base', async () => {
+ state.exportResponse = {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ files: [
+ {
+ folder: 'Source',
+ path: 'application.ts',
+ content: 'export default {};',
+ },
+ ],
+ },
+ },
+ };
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('failed');
+ expect(envelope.warnings).toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ expect(existsSync(join(appPath, '.twenty/cli/pull-base.json'))).toBe(false);
+ expect(await readdir(join(appPath, '.twenty/cli/snapshots'))).toEqual([]);
+ });
+
+ it('keeps permission failures separate from an unapplied app', async () => {
+ state.exportResponse = graphqlError('FORBIDDEN');
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('failed');
+ expect(envelope.warnings).toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ expect(existsSync(join(appPath, '.twenty/cli/pull-base.json'))).toBe(false);
+ expect(await readdir(join(appPath, '.twenty/cli/snapshots'))).toEqual([]);
+ });
+
+ it.each(['.twenty', '.twenty/cli', '.twenty/cli/pull-base.json'])(
+ 'does not follow a symlink at %s while recording the base',
+ async (relativePath) => {
+ const externalPath = await mkdtemp(
+ join(tmpdir(), 'twenty-external-base-'),
+ );
+ const destination = join(appPath, relativePath);
+ const isFile = relativePath.endsWith('.json');
+ const target = isFile ? join(externalPath, 'base.json') : externalPath;
+ if (isFile) {
+ await writeFile(target, 'external baseline');
+ }
+ await mkdir(join(destination, '..'), { recursive: true });
+ await symlink(target, destination);
+
+ try {
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('failed');
+ expect(envelope.warnings).toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ expect(await readdir(externalPath)).toEqual(
+ isFile
+ ? ['base.json']
+ : relativePath === '.twenty'
+ ? ['cli']
+ : ['snapshots'],
+ );
+ if (isFile) {
+ expect(await readFile(target, 'utf8')).toBe('external baseline');
+ }
+ } finally {
+ await rm(externalPath, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it('cleans up staged files when the base cannot be replaced', async () => {
+ const basePath = join(appPath, '.twenty/cli/pull-base.json');
+ await mkdir(basePath, { recursive: true });
+ await writeFile(join(basePath, 'keep.txt'), 'user contents');
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('failed');
+ expect(envelope.warnings).toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ expect(await readFile(join(basePath, 'keep.txt'), 'utf8')).toBe(
+ 'user contents',
+ );
+ expect((await readdir(join(appPath, '.twenty/cli'))).sort()).toEqual([
+ 'pull-base.json',
+ 'snapshots',
+ ]);
+ });
+
+ it.each([
+ ['missing collections', MANIFEST],
+ [
+ 'null collections',
+ { ...EXPORTED_MANIFEST, settingsMenuItems: null, objects: null },
+ ],
+ [
+ 'new collections',
+ { ...EXPORTED_MANIFEST, futureCollection: [{ name: 'preserved' }] },
+ ],
+ ])(
+ 'records %s exactly as the server sent them',
+ async (_description, manifest) => {
+ state.exportResponse = {
+ data: { exportApplication: { ...APPLICATION_EXPORT, manifest } },
+ };
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('recorded');
+ expect(
+ JSON.parse(
+ await readFile(join(appPath, '.twenty/cli/pull-base.json'), 'utf8'),
+ ).manifest,
+ ).toEqual(manifest);
+ },
+ );
+
+ it('records a baseline when the server adds a coverage status', async () => {
+ state.exportResponse = {
+ data: {
+ exportApplication: {
+ ...APPLICATION_EXPORT,
+ coverage: [
+ {
+ metadataName: 'object',
+ universalIdentifier: WORKSPACE_ID,
+ status: 'FUTURE_STATUS',
+ reason: null,
+ },
+ ],
+ },
+ },
+ };
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('recorded');
+ expect(envelope.warnings).not.toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ });
+
+ it.each([
+ [
+ 400,
+ undefined,
+ 'Cannot query field "exportApplication" on type "Query".',
+ 'unsupported',
+ ],
+ [
+ 400,
+ undefined,
+ 'Cannot query field "exportApplication" on type "Query". Did you mean "application"?',
+ 'unsupported',
+ ],
+ [
+ 200,
+ 'GRAPHQL_VALIDATION_FAILED',
+ 'Cannot query field "exportApplication" on type "Query".',
+ 'unsupported',
+ ],
+ [
+ 200,
+ 'GRAPHQL_VALIDATION_FAILED',
+ 'Cannot query field "exportApplication" on type "Query". Did you mean "application"?',
+ 'unsupported',
+ ],
+ [
+ 200,
+ 'GRAPHQL_VALIDATION_FAILED',
+ 'Cannot query field "coverage" on type "ApplicationExport".',
+ 'failed',
+ ],
+ [
+ 400,
+ undefined,
+ 'Cannot query field "coverage" on type "ApplicationExport".',
+ 'failed',
+ ],
+ [
+ 200,
+ undefined,
+ 'Cannot query field "exportApplication" on type "Query".',
+ 'failed',
+ ],
+ [
+ 400,
+ 'INTERNAL_SERVER_ERROR',
+ 'Cannot query field "exportApplication" on type "Query".',
+ 'failed',
+ ],
+ ])(
+ 'classifies only a missing export API as unsupported: %s %s %s',
+ async (httpStatus, code, message, status) => {
+ const basePath = join(appPath, '.twenty/cli/pull-base.json');
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await writeFile(basePath, 'previous baseline');
+ state.exportStatus = httpStatus;
+ state.exportResponse = {
+ errors: [
+ {
+ message,
+ locations: [{ line: 1, column: 27 }],
+ ...(isDefined(code) ? { extensions: { code } } : {}),
+ },
+ ],
+ };
+ await enableClientGeneration(
+ 'return { success: true, data: null, diagnostics: [] };',
+ );
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ pullBase: status,
+ clientGeneration: 'generated',
+ });
+ expect(envelope.data.completedPhases).not.toContain('pullBase');
+ expect(envelope.warnings).toEqual(
+ status === 'unsupported'
+ ? []
+ : [expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' })],
+ );
+ expect(await readFile(basePath, 'utf8')).toBe('previous baseline');
+ },
+ );
+
+ it('does not mistake an execution error for a missing export API', async () => {
+ state.exportStatus = 400;
+ state.exportResponse = {
+ errors: [
+ {
+ message: 'Cannot query field "exportApplication" on type "Query".',
+ path: ['exportApplication'],
+ },
+ ],
+ };
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.pullBase).toBe('failed');
+ expect(envelope.warnings).toContainEqual(
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ );
+ });
+
+ it('keeps a generation failure distinct from an earlier baseline warning', async () => {
+ state.exportResponse = graphqlError('FORBIDDEN');
+ await enableClientGeneration("throw new Error('generation failed');");
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.details).toMatchObject({
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ });
+ expect(envelope.error.details.completedPhases).not.toContain('pullBase');
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'PULL_BASE_NOT_RECORDED' }),
+ ]);
+ });
+
+ it('reports an applied app if export fetching is cancelled and preserves the base', async () => {
+ const basePath = join(appPath, '.twenty/cli/pull-base.json');
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await writeFile(basePath, 'previous baseline');
+ state.isExportHeld = true;
+ const pending = runJson();
+ await vi.waitFor(() => expect(state.heldExportResponse).toBeDefined(), {
+ timeout: 10_000,
+ });
+ process.emit('SIGINT');
+
+ const { envelope, exitCode } = await pending;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ details: { phase: 'pullBase', outcome: 'applied' },
+ });
+ expect(await readFile(basePath, 'utf8')).toBe('previous baseline');
+ expect(operations()).not.toContain('schema');
+ });
+
+ it('generates with the project SDK after sync and snapshot release, keeping target credentials in the CLI', async () => {
+ await enableClientGeneration(`
+ fs.writeFileSync(path.join(appPath, 'generated.json'), JSON.stringify({
+ appPath, schema,
+ hasSignal: signal instanceof AbortSignal,
+ snapshotReleased: fs.existsSync(path.join(__dirname, 'released.txt')),
+ apiKey: process.env.TWENTY_API_KEY ?? null,
+ apiUrl: process.env.TWENTY_API_URL ?? null,
+ }));
+ console.log('generator progress');
+ return { success: true, data: null, diagnostics: [] };
+ `);
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ clientGeneration: 'generated',
+ completedPhases: [
+ 'build',
+ 'preview',
+ 'installation',
+ 'upload',
+ 'sync',
+ 'pullBase',
+ 'clientGeneration',
+ ],
+ diagnostics: expect.arrayContaining([
+ expect.objectContaining({
+ message: expect.stringContaining('generator progress'),
+ }),
+ ]),
+ });
+ expect(envelope.warnings).toEqual([]);
+ expect(operations().slice(-4)).toEqual([
+ 'sync',
+ 'workspace',
+ 'export',
+ 'schema',
+ ]);
+ expect(
+ operations().filter((operation) => operation === 'sync'),
+ ).toHaveLength(1);
+ const schemaRequest = server.requests.at(-1);
+
+ expect(schemaRequest).toMatchObject({
+ path: '/metadata',
+ headers: { authorization: 'Bearer apply-test-key' },
+ });
+ expect(
+ isDefined(schemaRequest) && readGraphqlRequest(schemaRequest).arguments,
+ ).toEqual({
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ });
+ expect(
+ JSON.parse(await readFile(join(appPath, 'generated.json'), 'utf8')),
+ ).toEqual({
+ appPath,
+ schema: SCHEMA,
+ hasSignal: true,
+ snapshotReleased: true,
+ apiKey: null,
+ apiUrl: null,
+ });
+ });
+
+ it('fetches the schema with the lowercase identifier the server acknowledged', async () => {
+ await enableClientGeneration(
+ 'return { success: true, data: null, diagnostics: [] };',
+ {
+ ...APPLICATION,
+ universalIdentifier: APPLICATION.universalIdentifier.toUpperCase(),
+ },
+ );
+
+ const { envelope, exitCode } = await runJson();
+ const schemaRequest = server.requests.at(-1);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.clientGeneration).toBe('generated');
+ expect(
+ isDefined(schemaRequest) && readGraphqlRequest(schemaRequest).arguments,
+ ).toEqual({
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ });
+ });
+
+ it('skips generation with a warning when the app has no client package of its own', async () => {
+ await enableClientGeneration(
+ "throw new Error('generation must not start');",
+ );
+ await rm(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ });
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ clientGeneration: 'skipped',
+ completedPhases: [
+ 'build',
+ 'preview',
+ 'installation',
+ 'upload',
+ 'sync',
+ 'pullBase',
+ ],
+ });
+ expect(envelope.warnings).toEqual([
+ {
+ code: 'CLIENT_NOT_GENERATED',
+ message: expect.stringContaining(
+ "twenty-client-sdk is not installed in the app's own node_modules",
+ ),
+ },
+ ]);
+ expect(operations()).not.toContain('schema');
+ });
+
+ it('leaves a dangling client package link to the client generator instead of skipping generation', async () => {
+ await enableClientGeneration(`
+ if (!fs.existsSync(path.join(appPath, 'node_modules', 'twenty-client-sdk', 'package.json'))) {
+ return { success: false, error: { code: 'CLIENT_GENERATION_FAILED', message: 'twenty-client-sdk is unreadable.' }, diagnostics: [] };
+ }
+ return { success: true, data: null, diagnostics: [] };
+ `);
+ await rm(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ });
+ await symlink(
+ join(appPath, 'missing-client-sdk'),
+ join(appPath, 'node_modules', 'twenty-client-sdk'),
+ );
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'CLIENT_GENERATION_FAILED',
+ message: `Apply App was applied to ${server.url}, but its typed API client was not regenerated: twenty-client-sdk is unreadable.`,
+ details: { phase: 'clientGeneration', outcome: 'applied' },
+ });
+ expect(operations()).toContain('schema');
+ });
+
+ it('prints successful local client generation in the human summary', async () => {
+ await enableClientGeneration(
+ 'return { success: true, data: null, diagnostics: [] };',
+ );
+
+ const { exitCode, stdout, stderr } = await run();
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toContain('Regenerated the typed API client.');
+ expect(stderr).not.toContain('typed API client was not regenerated');
+ });
+
+ it.each([
+ null,
+ {},
+ { applicationCoreGraphqlSchema: '' },
+ { applicationCoreGraphqlSchema: ' ' },
+ { applicationCoreGraphqlSchema: 42 },
+ ])(
+ 'keeps the remote sync completed when the schema response is unreadable: %j',
+ async (data) => {
+ await enableClientGeneration(
+ "throw new Error('generation must not start');",
+ );
+ state.schemaResponse = { data };
+
+ const { exitCode, envelope } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'INVALID_RESPONSE',
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: [
+ 'build',
+ 'preview',
+ 'installation',
+ 'upload',
+ 'sync',
+ 'pullBase',
+ ],
+ },
+ });
+ },
+ );
+
+ it('does not classify a schema permission failure as an unapplied app', async () => {
+ await enableClientGeneration();
+ state.schemaError = 'FORBIDDEN';
+
+ const { exitCode, envelope } = await runJson();
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error).toMatchObject({
+ code: 'PERMISSION_DENIED',
+ message: expect.stringContaining(
+ `Apply App was applied to ${server.url}, but its typed API client was not regenerated`,
+ ),
+ hint: expect.stringContaining('already has this version of the app'),
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: expect.arrayContaining(['sync']),
+ },
+ });
+ });
+
+ it.each([
+ { body: undefined, code: 'WORKER_FAILED' },
+ { body: 'process.exit(7);', code: 'WORKER_FAILED' },
+ {
+ body: 'return { success: true, data: {}, diagnostics: [] };',
+ code: 'WORKER_FAILED',
+ },
+ {
+ body: `
+ fs.writeFileSync(path.join(appPath, 'partial-client.txt'), 'partial');
+ return { success: false, error: { code: 'CLIENT_GENERATION_FAILED', message: 'Write failed.' }, diagnostics: [{ severity: 'error', code: 'GENERATE', message: 'Write failed.' }] };
+ `,
+ code: 'CLIENT_GENERATION_FAILED',
+ },
+ ])(
+ 'preserves the sync when generation fails with $code',
+ async ({ body, code }) => {
+ await enableClientGeneration(body);
+
+ const { exitCode, envelope } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code,
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: expect.arrayContaining(['sync']),
+ },
+ hint: expect.stringContaining('may be incomplete'),
+ });
+ expect(envelope.error.details.completedPhases).not.toContain(
+ 'clientGeneration',
+ );
+ expect(await readReleasedBuildId()).toBe('build-id');
+ expect(
+ operations().filter((operation) => operation === 'sync'),
+ ).toHaveLength(1);
+ },
+ );
+
+ it('never fetches a schema or generates a client after a failed sync', async () => {
+ await enableClientGeneration(
+ "throw new Error('generation must not start');",
+ );
+ state.syncError = 'INTERNAL_SERVER_ERROR';
+
+ const { exitCode, envelope } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.details).toMatchObject({
+ phase: 'sync',
+ outcome: 'unknown',
+ });
+ expect(operations()).not.toContain('schema');
+ });
+
+ it('keeps the remote sync completed when schema fetching is cancelled', async () => {
+ await enableClientGeneration();
+ state.isSchemaHeld = true;
+ const pending = runJson();
+
+ await vi.waitFor(() => expect(state.heldSchemaResponse).toBeDefined(), {
+ timeout: 10_000,
+ });
+ process.emit('SIGINT');
+
+ const { exitCode, envelope } = await pending;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ message: `Apply App was applied to ${server.url}, but generating its typed API client was cancelled.`,
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: expect.arrayContaining(['sync']),
+ },
+ });
+ });
+
+ it.each(['CANCELLED', 'CLIENT_GENERATION_FAILED'])(
+ 'waits for generation to settle and preserves the SDK result %s after cancellation',
+ async (code) => {
+ await enableClientGeneration(`
+ fs.writeFileSync(path.join(appPath, 'generation-started.txt'), 'started');
+ await new Promise((resolve) => signal.addEventListener('abort', resolve, { once: true }));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ fs.writeFileSync(path.join(appPath, 'generation-settled.txt'), 'settled');
+ return { success: false, error: { code: '${code}', message: 'Generation stopped.' }, diagnostics: [] };
+ `);
+ const pending = runJson();
+
+ await vi.waitFor(
+ () =>
+ expect(existsSync(join(appPath, 'generation-started.txt'))).toBe(
+ true,
+ ),
+ { timeout: 10_000 },
+ );
+ process.emit('SIGINT');
+
+ const { exitCode, envelope } = await pending;
+
+ expect(exitCode).toBe(code === 'CANCELLED' ? 130 : 1);
+ expect(envelope.error).toMatchObject({
+ code,
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: expect.arrayContaining(['sync']),
+ },
+ });
+ expect(
+ await readFile(join(appPath, 'generation-settled.txt'), 'utf8'),
+ ).toBe('settled');
+ },
+ );
+
+ it('terminates an unresponsive generator on cancellation while preserving the completed sync', async () => {
+ await enableClientGeneration(`
+ fs.writeFileSync(path.join(appPath, 'generation-started.txt'), 'started');
+ setInterval(() => {}, 1000);
+ await new Promise(() => {});
+ `);
+ const pending = runJson();
+
+ await vi.waitFor(
+ () =>
+ expect(existsSync(join(appPath, 'generation-started.txt'))).toBe(true),
+ { timeout: 10_000 },
+ );
+ process.emit('SIGINT');
+
+ const { exitCode, envelope } = await pending;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: expect.arrayContaining(['sync']),
+ },
+ });
+ }, 15_000);
+
+ it('refuses to register an unknown app without --create', async () => {
+ state.isRegistered = false;
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error).toMatchObject({
+ code: 'CREATE_REQUIRED',
+ hint: expect.stringContaining('--create'),
+ details: {
+ phase: 'confirmation',
+ outcome: 'not-started',
+ completedPhases: ['build'],
+ },
+ });
+ expect(operations()).toEqual(['preview']);
+ expect(await readReleasedBuildId()).toBe('build-id');
+ });
+
+ it('registers, installs and previews an unknown app with --create before uploading', async () => {
+ state.isRegistered = false;
+
+ const { envelope, exitCode } = await runJson('--create');
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ registrationCreated: true,
+ completedPhases: [
+ 'build',
+ 'registration',
+ 'installation',
+ 'preview',
+ 'upload',
+ 'sync',
+ 'pullBase',
+ ],
+ });
+ expect(operations()).toEqual([
+ 'preview',
+ 'registration',
+ 'installation',
+ 'preview',
+ 'upload-targets',
+ 'put',
+ 'put',
+ 'upload-complete',
+ 'sync',
+ 'workspace',
+ 'export',
+ ]);
+ expect(server.requests[1].body).not.toContain('clientSecret');
+ });
+
+ it('keeps a completed registration in the report when a later step fails', async () => {
+ state.isRegistered = false;
+ state.installError = 'FORBIDDEN';
+
+ const { envelope, exitCode } = await runJson('--create');
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error).toMatchObject({
+ code: 'PERMISSION_DENIED',
+ details: {
+ phase: 'installation',
+ outcome: 'not-started',
+ completedPhases: ['build', 'registration'],
+ },
+ });
+ expect(operations()).toEqual(['preview', 'registration', 'installation']);
+ });
+
+ it.each([
+ [
+ 'registration',
+ { isRegistered: false, registrationError: 'INTERNAL_SERVER_ERROR' },
+ ['--create'],
+ 'GRAPHQL_ERROR',
+ ['build'],
+ ],
+ [
+ 'installation',
+ { installError: 'INTERNAL_SERVER_ERROR' },
+ [],
+ 'GRAPHQL_ERROR',
+ ['build', 'preview'],
+ ],
+ [
+ 'upload',
+ { uploadTargetsStatus: 500 },
+ [],
+ 'HTTP_ERROR',
+ ['build', 'preview', 'installation'],
+ ],
+ ])(
+ 'reports an unknown outcome when the server fails a %s request after receiving it',
+ async (phase, serverState, args, code, completedPhases) => {
+ Object.assign(state, serverState);
+
+ const { envelope, exitCode } = await runJson(...args);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code,
+ details: { phase, outcome: 'unknown', completedPhases },
+ });
+ expect(operations()).not.toContain('sync');
+ },
+ );
+
+ it('requires --yes before deleting objects or fields in automation', async () => {
+ state.previewActions = [CREATE_ACTION, OBJECT_DELETION];
+
+ const refused = await runJson();
+
+ expect(refused.exitCode).toBe(2);
+ expect(refused.envelope.error).toMatchObject({
+ code: 'CONFIRMATION_REQUIRED',
+ message:
+ 'The preview includes 1 object or field deletion that permanently deletes stored data.',
+ hint: expect.stringContaining('--yes'),
+ details: { phase: 'confirmation', completedPhases: ['build', 'preview'] },
+ });
+ expect(operations()).toEqual(['preview']);
+
+ server.requests.length = 0;
+
+ const approved = await runJson('--yes');
+
+ expect(approved.exitCode).toBe(0);
+ expect(approved.envelope.data.summary).toMatchObject({
+ delete: 1,
+ destructive: 1,
+ });
+ expect(operations().at(-1)).toBe('export');
+ });
+
+ it.each([
+ ['y\n', 0, 'export'],
+ ['n\n', 2, 'preview'],
+ ])(
+ 'asks before deleting objects in an interactive terminal (answer %j)',
+ async (answer, expectedExitCode, lastOperation) => {
+ state.previewActions = [OBJECT_DELETION];
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ content: answer, isTerminal: true }),
+ );
+
+ const { exitCode, stderr } = await run();
+
+ expect(exitCode).toBe(expectedExitCode);
+ expect(stderr).toContain(
+ 'Warning: 1 destructive change(s) will permanently delete data.',
+ );
+ expect(stderr).toContain(
+ ' - objectMetadata "invoice": drops the table and all its rows',
+ );
+ expect(operations().at(-1)).toBe(lastOperation);
+ },
+ );
+
+ it('reports a partial upload and never syncs', async () => {
+ state.failingUploadFileId = 'file-1';
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'UPLOAD_FAILED',
+ details: {
+ phase: 'upload',
+ outcome: 'partial',
+ completedPhases: ['build', 'preview', 'installation'],
+ failures: [
+ { path: 'public/logo.svg', message: 'File storage answered 500.' },
+ ],
+ },
+ });
+ expect(operations()).not.toContain('sync');
+ expect(await readReleasedBuildId()).toBe('build-id');
+ });
+
+ it('waits for uploads in flight before releasing the snapshot after an upload error', async () => {
+ state.hasInvalidFirstUploadUrl = true;
+ state.heldUploadFileId = 'file-1';
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'INVALID_RESPONSE',
+ details: {
+ phase: 'upload',
+ outcome: 'unknown',
+ completedPhases: ['build', 'preview', 'installation'],
+ },
+ });
+ expect(state.wasSnapshotPresentDuringHeldUpload).toBe(true);
+ expect(operations()).not.toContain('upload-complete');
+ expect(operations()).not.toContain('sync');
+ expect(await readReleasedBuildId()).toBe('build-id');
+ });
+
+ it('does not claim an untouched workspace once upload targets exist', async () => {
+ state.completeError = 'FORBIDDEN';
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error).toMatchObject({
+ code: 'PERMISSION_DENIED',
+ details: { phase: 'upload', outcome: 'unknown' },
+ });
+ expect(operations()).not.toContain('sync');
+ });
+
+ it('refuses a snapshot file that changed after the build before uploading', async () => {
+ await writeTooling({ corruptPath: 'public/logo.svg' });
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'SNAPSHOT_INVALID',
+ details: { phase: 'upload', outcome: 'not-started' },
+ });
+ expect(operations()).toEqual(['preview', 'installation']);
+ });
+
+ it('keeps an existing base unchanged while planning or after an unacknowledged sync', async () => {
+ const basePath = join(appPath, '.twenty/cli/pull-base.json');
+ await mkdir(join(appPath, '.twenty/cli'), { recursive: true });
+ await writeFile(basePath, 'previous baseline');
+ const plan = await runCliForTest([
+ 'app',
+ 'plan',
+ '--path',
+ appPath,
+ '--json',
+ ]);
+
+ expect(plan.exitCode).toBe(0);
+ expect(await readFile(basePath, 'utf8')).toBe('previous baseline');
+ expect(operations()).not.toContain('export');
+ state.syncResponseOverride = { data: null };
+
+ const { exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(await readFile(basePath, 'utf8')).toBe('previous baseline');
+ expect(operations()).not.toContain('export');
+ expect(operations()).not.toContain('workspace');
+ });
+
+ it('reports an unknown outcome when the sync fails', async () => {
+ state.syncError = 'BAD_USER_INPUT';
+
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'GRAPHQL_ERROR',
+ hint: expect.stringContaining('twenty app plan'),
+ details: {
+ phase: 'sync',
+ outcome: 'unknown',
+ completedPhases: ['build', 'preview', 'installation', 'upload'],
+ },
+ });
+ expect(await readReleasedBuildId()).toBe('build-id');
+ });
+
+ it.each([
+ ['no result', { data: null }],
+ ['an empty result', { data: {} }],
+ [
+ 'the wrong application',
+ {
+ data: {
+ syncApplication: {
+ applicationUniversalIdentifier: 'another-app',
+ actions: [],
+ },
+ },
+ },
+ ],
+ ])(
+ 'never reports an applied app when the sync answers with %s',
+ async (_description, response) => {
+ state.syncResponseOverride = response;
+
+ const { envelope, exitCode, stdout } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'INVALID_RESPONSE',
+ details: { phase: 'sync', outcome: 'unknown' },
+ });
+ expect(stdout).not.toContain('Applied');
+ },
+ );
+
+ it('keeps variable values from a failed sync out of the error', async () => {
+ state.syncResponseOverride = {
+ data: {
+ syncApplication: {
+ applicationUniversalIdentifier: APPLICATION.universalIdentifier,
+ actions: [
+ {
+ type: 'create',
+ metadataName: 'applicationVariable',
+ flatEntity: { name: 'API_TOKEN', value: 'super-secret' },
+ },
+ ],
+ },
+ },
+ errors: [
+ { message: 'Partial failure.', extensions: { code: 'BAD_USER_INPUT' } },
+ ],
+ };
+
+ const { envelope, exitCode, stdout } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'GRAPHQL_ERROR',
+ details: { phase: 'sync', outcome: 'unknown', data: null },
+ });
+ expect(stdout).not.toContain('super-secret');
+ });
+
+ it('exits with 130 and an unknown sync outcome when cancelled during the sync', async () => {
+ state.isSyncHeld = true;
+
+ const pending = runJson();
+
+ await vi.waitFor(() => expect(operations()).toContain('sync'), {
+ timeout: 10_000,
+ });
+ process.emit('SIGINT');
+
+ const { envelope, exitCode } = await pending;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ details: { phase: 'sync', outcome: 'unknown' },
+ });
+ expect(await readReleasedBuildId()).toBe('build-id');
+ });
+
+ it('prints the preview on stderr and a summary on stdout', async () => {
+ const { stdout, stderr, exitCode } = await run();
+
+ expect(exitCode).toBe(0);
+ expect(stderr).toContain('Plan: 1 to add, 0 to change, 0 to destroy.');
+ expect(stderr).toContain('typed API client was not regenerated');
+ expect(stdout).toContain(`Applied Apply App to ${server.url}`);
+ expect(stdout).toContain('2 files uploaded (40 B)');
+ });
+
+ it('lists the command as a write with its permissions', async () => {
+ const { stdout } = await runCliForTest(['commands', '--json']);
+ const commands: unknown = parseSingleJsonLine(stdout).data.commands;
+
+ expect(commands).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'app apply',
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS', 'UPLOAD_FILE'],
+ }),
+ ]),
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts
new file mode 100644
index 00000000000..dfc461aa829
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-build.spec.ts
@@ -0,0 +1,671 @@
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { writeTestSourceSdk } from '@/app/__tests__/utils/write-test-source-sdk';
+import {
+ access,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import Module from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { isFunction } from '@sniptt/guards';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+
+const initializeModulePaths = () => {
+ if (!('_initPaths' in Module) || !isFunction(Module._initPaths)) {
+ throw new Error('node:module does not expose _initPaths.');
+ }
+
+ Module._initPaths();
+};
+
+const worker = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => worker,
+}));
+
+let workerDirectory: string;
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-command-worker-'));
+ await buildTestAppWorker(workerDirectory, { useToolingFixture: true });
+ worker.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60_000);
+
+afterAll(() => rm(workerDirectory, { recursive: true, force: true }));
+
+vi.mock('@/app/constants/app-worker.constant', () => ({
+ APP_WORKER: { CANCEL_GRACE_MILLISECONDS: 300, OUTPUT_LIMIT_BYTES: 2048 },
+}));
+
+const SUCCESSFUL_BUILD = `return {
+ success: true,
+ data: {
+ buildId: 'build-1',
+ directory: path.join(appPath, '.twenty', 'cli', 'snapshots', 'build-1', 'files'),
+ contentHash: 'c'.repeat(64),
+ application: { universalIdentifier: 'app-id', name: 'fake-app', displayName: 'Fake App' },
+ manifestFormat: 'twenty-application',
+ manifest: { application: { universalIdentifier: 'app-id' } },
+ files: [
+ { path: 'src/hello.mjs', role: 'built-logic-function', sourcePath: 'src/hello.ts', size: 1200, sha256: 'a'.repeat(64) },
+ { path: 'src/hello.ts', role: 'source', sourcePath: 'src/hello.ts', size: 300, sha256: 'b'.repeat(64) },
+ ],
+ },
+ diagnostics: [{ severity: 'warning', code: 'BUILD_WARNING', message: 'A deprecated option is used.' }],
+};`;
+
+const SUCCESSFUL_TYPECHECK = `return { success: true, data: null, diagnostics: [] };`;
+
+const exists = (filePath: string) =>
+ access(filePath).then(
+ () => true,
+ () => false,
+ );
+
+const createApp = async (name = 'fake-app') => {
+ const root = await mkdtemp(join(tmpdir(), 'twenty-cli-app-'));
+ const appPath = join(root, name);
+
+ await mkdir(join(appPath, 'src'), { recursive: true });
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({ name, devDependencies: { 'twenty-sdk': '9.9.9' } }),
+ );
+
+ return { root, appPath };
+};
+
+const writeFixture = async ({
+ appPath,
+ version = '9.9.9',
+ requiredNode = '^24.5.0',
+ hasSourceExports = true,
+ build = SUCCESSFUL_BUILD,
+ typecheck = SUCCESSFUL_TYPECHECK,
+}: {
+ appPath: string;
+ version?: string;
+ requiredNode?: string;
+ hasSourceExports?: boolean;
+ build?: string;
+ typecheck?: string;
+}) => {
+ await writeTestSourceSdk({
+ appPath,
+ version,
+ requiredNode,
+ hasSourceExports,
+ });
+ await writeFile(
+ join(appPath, 'test-tooling.cjs'),
+ `const fs = require('node:fs');
+const path = require('node:path');
+const appPath = __dirname;
+const mark = (name, content = '') => fs.writeFileSync(path.join(appPath, name), content);
+mark('loaded.txt');
+module.exports = {
+ buildSourceSnapshot: async ({ signal }) => { ${build} },
+ typecheckApplication: async ({ signal }) => { ${typecheck} },
+ releaseSourceSnapshot: async ({ buildId }) => {
+ mark('released.txt', buildId);
+ return { success: true, data: null, diagnostics: [] };
+ },
+};`,
+ );
+};
+
+const runJson = async (args: string[]) => {
+ const result = await runCliForTest([...args, '--json']);
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+
+describe('app build and typecheck', () => {
+ beforeEach(() => {
+ vi.stubEnv('CI', '');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it("reports the app's own SDK version and releases the snapshot", async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({ appPath, version: '9.9.9' });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ app: { path: appPath, name: 'fake-app' },
+ sdk: { version: '9.9.9' },
+ application: { displayName: 'Fake App' },
+ contentHash: 'c'.repeat(64),
+ diagnostics: [{ severity: 'warning', code: 'BUILD_WARNING' }],
+ });
+ expect(envelope.data.files).toHaveLength(2);
+ expect(envelope).not.toHaveProperty('target');
+ expect(await exists(join(appPath, 'released.txt'))).toBe(true);
+ });
+
+ it('prints a readable summary in human mode', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({ appPath });
+
+ const { stdout, stderr, exitCode } = await runCliForTest([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(stderr).toContain('Building fake-app with twenty 0.3.0');
+ expect(stderr).toContain('A deprecated option is used.');
+ expect(stdout).toContain('Built Fake App with twenty 0.3.0');
+ expect(stdout).toContain('2 files · 1.5 KB');
+ expect(stdout).toContain('1 logic function · 1 source file');
+ expect(stdout).toContain('Nothing was uploaded.');
+ });
+
+ it('keeps the original diagnostic when the worker throws instead of returning a result', async () => {
+ const { appPath } = await createApp();
+ await writeFixture({
+ appPath,
+ build: `throw Object.assign(new Error('The entry file is missing.'), {
+ code: 'ENOENT',
+ hint: 'Restore src/function.ts before building.',
+ details: { path: 'src/function.ts', exitCode: 99, output: 'untrusted' },
+ });`,
+ });
+
+ const result = await runJson(['app', 'build', '--path', appPath]);
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'WORKER_FAILED',
+ message: 'The app worker failed: The entry file is missing.',
+ hint: 'Restore src/function.ts before building.',
+ details: {
+ workerErrorCode: 'ENOENT',
+ path: 'src/function.ts',
+ exitCode: 0,
+ output: { stdout: '', stderr: '', isTruncated: false },
+ },
+ });
+ });
+
+ it('keeps recovery hints and failure details through worker results in JSON and human output', async () => {
+ const { appPath } = await createApp();
+ await writeFixture({
+ appPath,
+ build: `return {
+ success: false,
+ error: {
+ code: 'MISSING_ENTRY',
+ message: 'The entry file is missing.',
+ hint: 'Restore src/function.ts before building.',
+ details: { path: 'src/function.ts', sdkVersion: 'untrusted', diagnostics: [] },
+ },
+ diagnostics: [{ severity: 'warning', code: 'BUILD_WARNING', message: 'Check the app entry.' }],
+ };`,
+ });
+
+ const result = await runJson(['app', 'build', '--path', appPath]);
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'BUILD_FAILED',
+ hint: 'Restore src/function.ts before building.',
+ details: {
+ path: 'src/function.ts',
+ toolingErrorCode: 'MISSING_ENTRY',
+ sdkVersion: '9.9.9',
+ diagnostics: [expect.objectContaining({ code: 'BUILD_WARNING' })],
+ },
+ });
+ const human = await runCliForTest(['app', 'build', '--path', appPath]);
+ expect(human.exitCode).toBe(1);
+ expect(human.stderr).toContain('Restore src/function.ts before building.');
+ });
+
+ it('finds the app from a nested folder', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({ appPath });
+ vi.spyOn(process, 'cwd').mockReturnValue(join(appPath, 'src'));
+
+ const { envelope, exitCode } = await runJson(['app', 'typecheck']);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.app.path).toBe(appPath);
+ });
+
+ it('asks for --path in a folder with several apps', async () => {
+ const { root } = await createApp('first-app');
+
+ await mkdir(join(root, 'second-app'));
+ await writeFile(
+ join(root, 'second-app', 'package.json'),
+ JSON.stringify({
+ name: 'second-app',
+ dependencies: { 'twenty-sdk': '1.0.0' },
+ }),
+ );
+ vi.spyOn(process, 'cwd').mockReturnValue(root);
+
+ const { envelope, exitCode } = await runJson(['app', 'build']);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('APP_PATH_REQUIRED');
+ expect(envelope.error.details.candidates).toEqual([
+ join(root, 'first-app'),
+ join(root, 'second-app'),
+ ]);
+ });
+
+ it.each([
+ ['a folder without an app', (root: string) => root],
+ ['a path that is not an app', (root: string) => join(root, 'missing')],
+ ])('refuses %s', async (_, getPath) => {
+ const root = await mkdtemp(join(tmpdir(), 'twenty-cli-empty-'));
+
+ vi.spyOn(process, 'cwd').mockReturnValue(root);
+
+ const { envelope, exitCode } = await runJson(
+ getPath(root) === root
+ ? ['app', 'build']
+ : ['app', 'build', '--path', getPath(root)],
+ );
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('APP_NOT_FOUND');
+ });
+
+ describe('refuses before loading any SDK code', () => {
+ it.each([
+ [
+ 'when twenty-sdk is not installed',
+ async (appPath: string) => appPath,
+ 'SDK_NOT_INSTALLED',
+ 'twenty-sdk is not installed for this app.',
+ ],
+ [
+ "when the app uses Yarn Plug'n'Play",
+ async (appPath: string) => {
+ await writeFile(join(appPath, '.pnp.cjs'), '');
+
+ return appPath;
+ },
+ 'TOOLING_UNSUPPORTED',
+ "Yarn Plug'n'Play",
+ ],
+ [
+ 'when the SDK has no source exports',
+ async (appPath: string) => {
+ await writeFixture({ appPath, hasSourceExports: false });
+ return appPath;
+ },
+ 'SDK_SOURCE_UNSUPPORTED',
+ 'cannot load app source with this CLI',
+ ],
+ [
+ 'when the SDK needs another Node version',
+ async (appPath: string) => {
+ await writeFixture({
+ appPath,
+ requiredNode: '>=99.0.0',
+ });
+
+ return appPath;
+ },
+ 'NODE_VERSION_UNSUPPORTED',
+ 'declares Node >=99.0.0',
+ ],
+ [
+ 'when the SDK declares a Node range it cannot read',
+ async (appPath: string) => {
+ await writeFixture({
+ appPath,
+ requiredNode: 'latest',
+ });
+
+ return appPath;
+ },
+ 'SDK_SOURCE_UNSUPPORTED',
+ 'declares Node latest',
+ ],
+ ])('%s', async (_, prepare, code, message) => {
+ const { appPath } = await createApp();
+
+ await prepare(appPath);
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe(code);
+ expect(envelope.error.message).toContain(message);
+ expect(await exists(join(appPath, 'loaded.txt'))).toBe(false);
+ });
+
+ it('never uses an SDK found only through global module paths', async () => {
+ const { appPath } = await createApp();
+ const globalRoot = await mkdtemp(join(tmpdir(), 'twenty-cli-global-'));
+ await writeFixture({ appPath: globalRoot });
+ vi.stubEnv('NODE_PATH', join(globalRoot, 'node_modules'));
+ initializeModulePaths();
+
+ try {
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('SDK_NOT_INSTALLED');
+ expect(await exists(join(globalRoot, 'loaded.txt'))).toBe(false);
+ } finally {
+ vi.unstubAllEnvs();
+ initializeModulePaths();
+ }
+ });
+
+ it('does not skip a broken nearer installation for a hoisted SDK', async () => {
+ const { root, appPath } = await createApp();
+
+ await writeFixture({ appPath: root });
+ await mkdir(join(appPath, 'node_modules', 'twenty-sdk'), {
+ recursive: true,
+ });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('TOOLING_UNSUPPORTED');
+ expect(envelope.error.message).toContain('is incomplete');
+ expect(await exists(join(root, 'loaded.txt'))).toBe(false);
+ });
+
+ it('uses a hoisted SDK when the app has no nearer installation', async () => {
+ const { root, appPath } = await createApp();
+
+ await writeFixture({ appPath });
+ await rm(join(appPath, 'node_modules', 'twenty-sdk'), {
+ recursive: true,
+ });
+ await writeTestSourceSdk({ appPath: root, version: '8.8.8' });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.sdk.version).toBe('8.8.8');
+ });
+ });
+
+ describe('isolates the worker', () => {
+ it('keeps JSON clean when app code prints, and reports the output', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: `console.log('noise from app code'); console.error('x'.repeat(5000)); ${SUCCESSFUL_BUILD}`,
+ });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+ const outputDiagnostics = envelope.data.diagnostics.filter(
+ (diagnostic: { code: string }) => diagnostic.code === 'PROJECT_OUTPUT',
+ );
+
+ expect(exitCode).toBe(0);
+ expect(outputDiagnostics).toHaveLength(2);
+ expect(outputDiagnostics[0].message).toContain('noise from app code');
+ expect(outputDiagnostics[1].message).toContain('(output truncated)');
+ });
+
+ it('reports a structured error when app code exits the process', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: `console.error('about to exit'); process.exit(7);`,
+ });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('WORKER_FAILED');
+ expect(envelope.error.details.exitCode).toBe(7);
+ expect(envelope.error.details.output.stderr).toContain('about to exit');
+ });
+
+ it('never passes CLI credentials or targets to the worker', async () => {
+ const { appPath } = await createApp();
+
+ vi.stubEnv('TWENTY_API_URL', 'https://crm.example.com');
+ vi.stubEnv('TWENTY_API_KEY', 'secret-key');
+ vi.stubEnv('TWENTY_REMOTE', 'prod');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'secret-token');
+ vi.stubEnv('TWENTY_FUTURE_SERVICE_TOKEN', 'secret-future');
+ vi.stubEnv('TWENTY_APP_PUBLISH_DISABLE_PROVENANCE', 'true');
+ await writeFixture({
+ appPath,
+ build: `mark('environment.json', JSON.stringify(Object.keys(process.env).filter((name) => name.startsWith('TWENTY_')))); ${SUCCESSFUL_BUILD}`,
+ });
+
+ const { exitCode } = await runJson(['app', 'build', '--path', appPath]);
+ const visibleVariables: unknown = JSON.parse(
+ await readFile(join(appPath, 'environment.json'), 'utf8'),
+ );
+
+ expect(exitCode).toBe(0);
+ expect(visibleVariables).toEqual([
+ 'TWENTY_APP_PUBLISH_DISABLE_PROVENANCE',
+ ]);
+ });
+ });
+
+ describe('failures', () => {
+ it('reports build failures with the tooling diagnostics', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: `return {
+ success: false,
+ error: { code: 'MANIFEST_BUILD_FAILED', message: 'No defineApplication() call found.' },
+ diagnostics: [{ severity: 'error', code: 'MANIFEST_BUILD_FAILED', message: 'No defineApplication() call found.' }],
+ };`,
+ });
+
+ const json = await runJson(['app', 'build', '--path', appPath]);
+ const human = await runCliForTest(['app', 'build', '--path', appPath]);
+
+ expect(json.exitCode).toBe(1);
+ expect(json.envelope.error).toMatchObject({
+ code: 'BUILD_FAILED',
+ message: 'The build failed: No defineApplication() call found.',
+ details: { toolingErrorCode: 'MANIFEST_BUILD_FAILED' },
+ });
+ expect(human.stderr).toContain('MANIFEST_BUILD_FAILED');
+ expect(await exists(join(appPath, 'released.txt'))).toBe(false);
+ });
+
+ it('reports type errors with their locations', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ typecheck: `return {
+ success: false,
+ error: { code: 'TYPECHECK_FAILED', message: 'Typecheck failed.' },
+ diagnostics: [{ severity: 'error', code: 'TS2322', message: "Type 'string' is not assignable to type 'number'.", file: 'src/hello.ts', line: 3, column: 7 }],
+ };`,
+ });
+
+ const json = await runJson(['app', 'typecheck', '--path', appPath]);
+ const human = await runCliForTest([
+ 'app',
+ 'typecheck',
+ '--path',
+ appPath,
+ ]);
+
+ expect(json.exitCode).toBe(1);
+ expect(json.envelope.error).toMatchObject({
+ code: 'TYPECHECK_FAILED',
+ message: 'Typecheck failed with 1 error.',
+ });
+ expect(human.stderr).toContain('src/hello.ts:3:7');
+ expect(human.stderr).toContain('TS2322');
+ });
+
+ it.each(['build', 'typecheck'])(
+ 'rejects a %s response containing the other operation result',
+ async (operation) => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: SUCCESSFUL_TYPECHECK,
+ typecheck: SUCCESSFUL_BUILD,
+ });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ operation,
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('WORKER_FAILED');
+ },
+ );
+
+ it('rejects a result it cannot read', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({ appPath, build: `return { success: true };` });
+
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ appPath,
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('WORKER_FAILED');
+ });
+ });
+
+ describe('cancellation', () => {
+ it('cancels the build on Ctrl+C and exits with 130', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: `mark('started.txt');
+ await new Promise((resolve) => signal.addEventListener('abort', resolve, { once: true }));
+ mark('cancelled.txt');
+ return { success: false, error: { code: 'CANCELLED', message: 'Cancelled.' }, diagnostics: [] };`,
+ });
+
+ const run = runJson(['app', 'build', '--path', appPath]);
+
+ await vi.waitFor(
+ () =>
+ exists(join(appPath, 'started.txt')).then((started) =>
+ expect(started).toBe(true),
+ ),
+ { timeout: 10_000 },
+ );
+ process.emit('SIGINT');
+
+ const { envelope, exitCode } = await run;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error.code).toBe('CANCELLED');
+ expect(await exists(join(appPath, 'cancelled.txt'))).toBe(true);
+ expect(await exists(join(appPath, 'released.txt'))).toBe(false);
+ });
+
+ it('stops a worker that ignores cancellation', async () => {
+ const { appPath } = await createApp();
+
+ await writeFixture({
+ appPath,
+ build: `mark('started.txt'); await new Promise(() => undefined);`,
+ });
+
+ const run = runJson(['app', 'build', '--path', appPath]);
+
+ await vi.waitFor(
+ () =>
+ exists(join(appPath, 'started.txt')).then((started) =>
+ expect(started).toBe(true),
+ ),
+ { timeout: 10_000 },
+ );
+ process.emit('SIGINT');
+
+ const { envelope, exitCode } = await run;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error.code).toBe('CANCELLED');
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-cli-typecheck.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-cli-typecheck.spec.ts
new file mode 100644
index 00000000000..ef34055a095
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-cli-typecheck.spec.ts
@@ -0,0 +1,146 @@
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+
+describe('app typecheck with CLI tooling', () => {
+ let workerDirectory: string;
+ let appPath: string;
+
+ const run = async () => {
+ const result = await runCliForTest([
+ 'app',
+ 'typecheck',
+ '--path',
+ appPath,
+ '--json',
+ ]);
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+
+ beforeAll(async () => {
+ workerDirectory = await mkdtemp(
+ join(tmpdir(), 'twenty-cli-typecheck-worker-'),
+ );
+ await buildTestAppWorker(workerDirectory);
+ launch.modulePath = join(workerDirectory, 'app-worker.cjs');
+ }, 60_000);
+
+ afterAll(() => rm(workerDirectory, { recursive: true, force: true }));
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-typecheck-app-'));
+ const sdkPath = join(appPath, 'node_modules/twenty-sdk');
+ await mkdir(sdkPath, { recursive: true });
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'typecheck-app',
+ devDependencies: { 'twenty-sdk': '2.42.0', typescript: '^5.9.3' },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version: '2.42.0',
+ exports: {
+ './define': './index.cjs',
+ './front-component': './index.cjs',
+ },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'index.cjs'),
+ "throw new Error('Typechecking must not load the authoring SDK');",
+ );
+ await symlink(
+ dirname(
+ createRequire(import.meta.url).resolve('typescript/package.json'),
+ ),
+ join(appPath, 'node_modules/typescript'),
+ );
+ await writeFile(
+ join(appPath, 'tsconfig.json'),
+ JSON.stringify({
+ compilerOptions: { strict: true, types: [], skipLibCheck: true },
+ include: ['*.ts'],
+ }),
+ );
+ await writeFile(
+ join(appPath, 'application.ts'),
+ 'export const name: string = "Example";',
+ );
+ });
+
+ afterEach(() => rm(appPath, { recursive: true, force: true }));
+
+ it('uses the project compiler without an SDK build API', async () => {
+ const result = await run();
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.envelope.data).toMatchObject({
+ sdk: { version: '2.42.0' },
+ diagnostics: [],
+ });
+ });
+
+ it('reports project diagnostics through the public command', async () => {
+ await writeFile(
+ join(appPath, 'application.ts'),
+ 'export const name: string = 42;',
+ );
+ const result = await run();
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'TYPECHECK_FAILED',
+ details: {
+ diagnostics: [
+ expect.objectContaining({ code: 'TS2322', file: 'application.ts' }),
+ ],
+ },
+ });
+ });
+
+ it('reports the missing project compiler without borrowing the CLI compiler', async () => {
+ await rm(join(appPath, 'node_modules/typescript'));
+ const result = await run();
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'TYPESCRIPT_NOT_INSTALLED',
+ details: { appPath },
+ });
+ });
+
+ it('fails on a missing TypeScript configuration', async () => {
+ await rm(join(appPath, 'tsconfig.json'));
+ const result = await run();
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'TYPECHECK_FAILED',
+ details: { diagnostics: [expect.objectContaining({ code: 'TS5083' })] },
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-dev.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-dev.spec.ts
new file mode 100644
index 00000000000..f87186348ff
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-dev.spec.ts
@@ -0,0 +1,286 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { runCliForTest } from '@/__tests__/utils/run-cli-for-test';
+import { applyAppBuild } from '@/app/deployment/apply-app-build';
+import {
+ buildDevSnapshot,
+ type BuiltDevSnapshot,
+} from '@/app/dev/build-dev-snapshot';
+import { createDevClientGenerator } from '@/app/dev/generate-dev-client';
+import { watchAppInputs } from '@/app/dev/watch-app-inputs';
+import { recordPullBase } from '@/app/record-pull-base';
+import { resolveCommandTarget } from '@/program/resolve-command-target';
+import { CliError } from '@/output/cli-error';
+
+vi.mock('@/app/dev/build-dev-snapshot');
+vi.mock('@/app/dev/watch-app-inputs');
+vi.mock('@/app/dev/generate-dev-client');
+vi.mock('@/app/deployment/apply-app-build');
+vi.mock('@/app/record-pull-base');
+vi.mock('@/app/project/resolve-app-project', () => ({
+ resolveAppProject: async () => ({ path: '/test-app', name: 'test-app' }),
+}));
+vi.mock('@/program/resolve-command-target');
+
+const makeSnapshot = (contentHash: string): BuiltDevSnapshot => ({
+ contentHash,
+ build: {
+ buildId: contentHash,
+ contentHash,
+ directory: '/test-app/.twenty/cli/snapshots/dev-test',
+ manifest: {},
+ manifestFormat: 'twenty-application',
+ files: [],
+ application: {
+ name: 'test-app',
+ displayName: 'Test App',
+ universalIdentifier: 'app-id',
+ },
+ },
+ release: vi.fn(async () => {}),
+ tooling: {
+ version: '2.44.0',
+ packagePath: '/test-app/node_modules/twenty-sdk',
+ },
+ diagnostics: [],
+ sourceFingerprints: { 'application.config.ts': 'source-hash' },
+});
+
+let invalidate = () => {};
+const close = vi.fn(async () => {});
+const generateClient = vi.fn<ReturnType<typeof createDevClientGenerator>>(
+ async () => 'skipped',
+);
+
+beforeEach(() => {
+ vi.mocked(resolveCommandTarget).mockResolvedValue({
+ apiUrl: 'http://localhost:3000',
+ bearerToken: 'test-token',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ });
+ vi.mocked(watchAppInputs).mockImplementation(async ({ onChange }) => {
+ invalidate = onChange;
+ return { close, update: vi.fn(async () => {}) };
+ });
+ vi.mocked(recordPullBase).mockResolvedValue('recorded');
+ vi.mocked(createDevClientGenerator).mockReturnValue(generateClient);
+ vi.mocked(applyAppBuild).mockResolvedValue({
+ completedPhases: ['build', 'preview', 'installation', 'upload', 'sync'],
+ isRegistrationCreated: false,
+ acknowledgedUniversalIdentifier: 'app-id',
+ appliedActions: [],
+ upload: { byteCount: 0, fileCount: 0, hasCreatedTargets: false },
+ });
+});
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.resetAllMocks();
+});
+
+describe('twenty app dev', () => {
+ it('rejects finite JSON before target lookup or starting a watcher', async () => {
+ const result = await runCliForTest(['app', 'dev', '--json']);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ ok: false,
+ error: { code: 'USAGE' },
+ });
+ expect(resolveCommandTarget).not.toHaveBeenCalled();
+ expect(watchAppInputs).not.toHaveBeenCalled();
+ expect(buildDevSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('streams build failure and recovery, carries approvals and pull fingerprints, cleans up on Ctrl+C', async () => {
+ const fixed = makeSnapshot('fixed');
+ vi.mocked(buildDevSnapshot)
+ .mockRejectedValueOnce(
+ new CliError({
+ code: 'TYPECHECK_FAILED',
+ message: 'Typecheck failed.',
+ }),
+ )
+ .mockResolvedValue(fixed);
+ const session = runCliForTest([
+ 'app',
+ 'dev',
+ '--format',
+ 'ndjson',
+ '--create',
+ '--yes',
+ '--no-delete',
+ ]);
+
+ await vi.waitFor(() => expect(buildDevSnapshot).toHaveBeenCalledOnce());
+ expect(applyAppBuild).not.toHaveBeenCalled();
+ invalidate();
+ await vi.waitFor(() => expect(generateClient).toHaveBeenCalledOnce());
+ process.emit('SIGINT');
+ const result = await session;
+ const events = result.stdout
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ expect(events.map((event) => event.data?.kind).filter(Boolean)).toEqual(
+ expect.arrayContaining([
+ 'watch-ready',
+ 'build-failure',
+ 'build-success',
+ 'sync-success',
+ ]),
+ );
+ expect(events.at(-1)).toMatchObject({
+ type: 'error',
+ data: { code: 'CANCELLED' },
+ });
+ expect(result.exitCode).toBe(130);
+ expect(applyAppBuild).toHaveBeenCalledWith(
+ expect.objectContaining({
+ isCreationApproved: true,
+ isDeletionApproved: true,
+ inferDeletionFromMissingEntities: false,
+ }),
+ );
+ expect(recordPullBase).toHaveBeenCalledWith(
+ expect.objectContaining({ sourceFingerprints: fixed.sourceFingerprints }),
+ );
+ expect(fixed.release).toHaveBeenCalledOnce();
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('keeps watching after a remote failure and requests a fresh preview only on a new revision', async () => {
+ const first = makeSnapshot('same');
+ const second = makeSnapshot('same');
+ vi.mocked(buildDevSnapshot)
+ .mockResolvedValueOnce(first)
+ .mockResolvedValue(second);
+ vi.mocked(applyAppBuild).mockRejectedValueOnce(
+ new CliError({
+ code: 'NETWORK_ERROR',
+ message: 'Connection lost',
+ details: {
+ phase: 'sync',
+ outcome: 'unknown',
+ completedPhases: ['build', 'preview', 'upload'],
+ },
+ }),
+ );
+ const session = runCliForTest(['app', 'dev', '--format', 'ndjson']);
+
+ await vi.waitFor(() => expect(applyAppBuild).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(first.release).toHaveBeenCalledOnce());
+ expect(generateClient).not.toHaveBeenCalled();
+ invalidate();
+ await vi.waitFor(() => expect(applyAppBuild).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() => expect(second.release).toHaveBeenCalledOnce());
+ process.emit('SIGINT');
+ const result = await session;
+ const failure = result.stdout
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line))
+ .find((event) => event.data?.kind === 'sync-failure');
+ expect(failure.data.error.details).toMatchObject({
+ phase: 'sync',
+ outcome: 'unknown',
+ });
+ });
+
+ it('terminates with acknowledged phases if client generation fails after writing starts', async () => {
+ const built = makeSnapshot('built');
+ vi.mocked(buildDevSnapshot).mockResolvedValue(built);
+ generateClient.mockRejectedValueOnce(
+ new CliError({
+ code: 'CLIENT_GENERATION_FAILED',
+ message: 'Client files may be incomplete',
+ details: {
+ phase: 'clientGeneration',
+ outcome: 'applied',
+ completedPhases: ['sync', 'pullBase'],
+ },
+ }),
+ );
+ const result = await runCliForTest(['app', 'dev', '--format', 'ndjson']);
+ const terminal = result.stdout
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line))
+ .at(-1);
+ expect(terminal).toMatchObject({
+ type: 'error',
+ data: {
+ code: 'CLIENT_GENERATION_FAILED',
+ details: { phase: 'clientGeneration', outcome: 'applied' },
+ },
+ });
+ expect(buildDevSnapshot).toHaveBeenCalledOnce();
+ expect(built.release).toHaveBeenCalledOnce();
+ expect(close).toHaveBeenCalledOnce();
+ });
+ it('preserves the remote phase and unknown outcome on Ctrl+C', async () => {
+ const built = makeSnapshot('cancelled');
+ vi.mocked(buildDevSnapshot).mockResolvedValue(built);
+ vi.mocked(applyAppBuild).mockImplementation(
+ async ({ context: { signal } }) =>
+ new Promise((_, reject) => {
+ signal.addEventListener(
+ 'abort',
+ () =>
+ reject(
+ new CliError({
+ code: 'CANCELLED',
+ exitCode: 130,
+ message: 'Sync interrupted',
+ details: {
+ phase: 'sync',
+ outcome: 'unknown',
+ completedPhases: ['build', 'preview', 'upload'],
+ },
+ }),
+ ),
+ { once: true },
+ );
+ }),
+ );
+ const session = runCliForTest(['app', 'dev', '--format', 'ndjson']);
+ await vi.waitFor(() => expect(applyAppBuild).toHaveBeenCalledOnce());
+ process.emit('SIGINT');
+ const result = await session;
+ const terminal = result.stdout
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line))
+ .at(-1);
+ expect(result.exitCode).toBe(130);
+ expect(terminal).toMatchObject({
+ type: 'error',
+ data: {
+ code: 'CANCELLED',
+ details: { phase: 'sync', outcome: 'unknown' },
+ },
+ });
+ expect(built.release).toHaveBeenCalledOnce();
+ });
+
+ it('makes abnormal worker termination actionable and stops watching', async () => {
+ vi.mocked(buildDevSnapshot).mockRejectedValue(
+ new CliError({
+ code: 'WORKER_FAILED',
+ message: 'The worker exited early',
+ }),
+ );
+ const result = await runCliForTest(['app', 'dev', '--format', 'ndjson']);
+ const terminal = result.stdout
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line))
+ .at(-1);
+ expect(terminal).toMatchObject({
+ type: 'error',
+ data: {
+ code: 'WORKER_FAILED',
+ hint: expect.stringContaining('restart twenty app dev'),
+ },
+ });
+ expect(close).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts
new file mode 100644
index 00000000000..7c5cfbc9292
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-exec.spec.ts
@@ -0,0 +1,507 @@
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { runAppWorker } from '@/app/run-app-worker';
+import { resolveCommandTarget } from '@/program/resolve-command-target';
+
+vi.mock('@/app/run-app-worker');
+vi.mock('@/program/resolve-command-target');
+vi.mock('@/app/project/resolve-app-project', () => ({
+ resolveAppProject: async () => ({ path: '/test-app', name: 'test-app' }),
+}));
+vi.mock('@/app/project/resolve-source-sdk', () => ({
+ resolveSourceSdk: async () => ({
+ version: '2.44.0',
+ packagePath: '/test-app/node_modules/twenty-sdk',
+ }),
+}));
+
+const APPLICATION_IDENTIFIER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const FUNCTION_IDENTIFIER = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const OTHER_FUNCTION_IDENTIFIER = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const APPLICATION = {
+ id: 'application-id',
+ universalIdentifier: APPLICATION_IDENTIFIER,
+};
+const FUNCTION = {
+ id: 'function-id',
+ name: 'helloWorld',
+ universalIdentifier: FUNCTION_IDENTIFIER,
+ applicationId: APPLICATION.id,
+ timeoutSeconds: 300,
+};
+const EXECUTION = {
+ status: 'SUCCESS',
+ duration: 12,
+ data: { greeting: 'Hello' },
+ logs: 'Hello from the function\n',
+ error: null,
+};
+let queryResult: unknown;
+let executionResult: unknown;
+let executionStatus = 200;
+let disconnect = false;
+let interrupt = false;
+
+const server = await startTestServer((request, response) => {
+ const { query } = JSON.parse(request.body);
+ if (query.includes('executeOneLogicFunction')) {
+ if (disconnect) {
+ return response.destroy();
+ }
+ if (interrupt) {
+ process.emit('SIGINT');
+ return;
+ }
+ sendJson(response, executionStatus, executionResult);
+ } else {
+ sendJson(response, 200, queryResult);
+ }
+});
+
+const run = (...options: string[]) =>
+ runCliForTest(['app', 'exec', ...options]);
+const runJson = async (...options: string[]) => {
+ const result = await run(...options, '--json');
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+const mutations = () =>
+ server.requests.filter(({ body }) =>
+ body.includes('executeOneLogicFunction'),
+ );
+const setManifest = (
+ application: Record<string, unknown> = {},
+ functionIdentifier = FUNCTION_IDENTIFIER,
+) => {
+ vi.mocked(runAppWorker).mockResolvedValue({
+ result: {
+ success: true,
+ data: {
+ manifest: {
+ application: {
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ ...application,
+ },
+ logicFunctions: [{ universalIdentifier: functionIdentifier }],
+ },
+ },
+ diagnostics: [],
+ },
+ isSnapshotHeld: false,
+ output: { stdout: '', stderr: '', isTruncated: false },
+ });
+};
+
+beforeEach(() => {
+ server.requests.length = 0;
+ disconnect = false;
+ interrupt = false;
+ executionStatus = 200;
+ queryResult = {
+ data: {
+ findOneApplication: APPLICATION,
+ findManyLogicFunctions: [FUNCTION],
+ },
+ };
+ executionResult = { data: { executeOneLogicFunction: EXECUTION } };
+ vi.mocked(resolveCommandTarget).mockResolvedValue({
+ apiUrl: server.url,
+ bearerToken: 'user-token',
+ credentialKind: 'oauth',
+ source: 'remote',
+ remoteName: 'dev',
+ });
+ setManifest();
+});
+afterEach(() => vi.clearAllMocks());
+afterAll(async () => server.close());
+
+describe('twenty app exec', () => {
+ it.each([
+ [],
+ ['--name', 'helloWorld', '--pre-install'],
+ ['--post-install', '--uninstall-hook'],
+ ['--name', ''],
+ ['--universal-identifier', 'invalid'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-1bbb-8bbb-bbbbbbbbbbbb'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-2bbb-8bbb-bbbbbbbbbbbb'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-3bbb-8bbb-bbbbbbbbbbbb'],
+ ])(
+ 'rejects invalid selectors %j before loading project source or sending requests',
+ async (...options) => {
+ const result = await runJson(...options);
+ expect(result.exitCode).toBe(2);
+ expect(result.envelope.error.code).toBe('INVALID_INPUT');
+ expect(runAppWorker).not.toHaveBeenCalled();
+ expect(server.requests).toEqual([]);
+ },
+ );
+
+ it('rejects an API-key target before loading source, with browser-login guidance', async () => {
+ vi.mocked(resolveCommandTarget).mockResolvedValue({
+ apiUrl: server.url,
+ bearerToken: 'api-key',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ });
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(3);
+ expect(result.envelope.error).toMatchObject({
+ code: 'AUTH_REQUIRED',
+ hint: expect.stringContaining('twenty auth login'),
+ });
+ expect(runAppWorker).not.toHaveBeenCalled();
+ expect(server.requests).toEqual([]);
+ });
+
+ it.each(['not json', '[]', 'null', '42'])(
+ 'rejects a non-object payload %s before reading source',
+ async (payload) => {
+ const result = await runJson(
+ '--name',
+ 'helloWorld',
+ '--payload',
+ payload,
+ );
+ expect(result.exitCode).toBe(2);
+ expect(runAppWorker).not.toHaveBeenCalled();
+ expect(server.requests).toEqual([]);
+ },
+ );
+
+ it('executes the deployed app function once with the given payload and returns its result', async () => {
+ const result = await runJson(
+ '--name',
+ 'helloWorld',
+ '--payload',
+ '{"name":"Ada"}',
+ );
+ expect(result.exitCode).toBe(0);
+ expect(result.envelope).toMatchObject({
+ ok: true,
+ command: 'app exec',
+ data: {
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ functionName: 'helloWorld',
+ functionUniversalIdentifier: FUNCTION_IDENTIFIER,
+ status: 'SUCCESS',
+ durationMilliseconds: 12,
+ data: { greeting: 'Hello' },
+ logs: EXECUTION.logs,
+ error: null,
+ },
+ });
+ expect(runAppWorker).toHaveBeenCalledWith(
+ expect.objectContaining({
+ request: { type: 'buildManifest', appPath: '/test-app' },
+ }),
+ );
+ expect(mutations()).toHaveLength(1);
+ expect(JSON.parse(mutations()[0].body).variables).toEqual({
+ v1: { id: FUNCTION.id, payload: { name: 'Ada' } },
+ });
+ expect(
+ server.requests.every(
+ ({ headers }) => headers.authorization === 'Bearer user-token',
+ ),
+ ).toBe(true);
+ expect(result.stdout).not.toContain('user-token');
+ });
+
+ it.each([
+ ['--universal-identifier', FUNCTION_IDENTIFIER.toUpperCase(), undefined],
+ ['--post-install', undefined, 'postInstallLogicFunction'],
+ ['--pre-install', undefined, 'preInstallLogicFunction'],
+ ['--uninstall-hook', undefined, 'uninstallLogicFunction'],
+ ])(
+ 'supports selector %s without installing or uninstalling the app',
+ async (flag, value, hook) => {
+ if (hook) {
+ setManifest({ [hook]: { universalIdentifier: FUNCTION_IDENTIFIER } });
+ }
+ const result = await runJson(flag, ...(value ? [value] : []));
+ expect(result.exitCode).toBe(0);
+ expect(mutations()).toHaveLength(1);
+ expect(server.requests).toHaveLength(2);
+ },
+ );
+
+ it.each([4, 5, 6, 7, 8])(
+ 'executes a function selected by its UUIDv%s universal identifier',
+ async (version) => {
+ const universalIdentifier = `bbbbbbbb-bbbb-${version}bbb-8bbb-bbbbbbbbbbbb`;
+ setManifest({}, universalIdentifier);
+ queryResult = {
+ data: {
+ findOneApplication: APPLICATION,
+ findManyLogicFunctions: [{ ...FUNCTION, universalIdentifier }],
+ },
+ };
+
+ const result = await runJson(
+ '--universal-identifier',
+ universalIdentifier.toUpperCase(),
+ );
+
+ expect(result.exitCode).toBe(0);
+ expect(result.envelope.data.functionUniversalIdentifier).toBe(
+ universalIdentifier,
+ );
+ expect(mutations()).toHaveLength(1);
+ expect(JSON.parse(mutations()[0].body).variables).toEqual({
+ v1: { id: FUNCTION.id, payload: {} },
+ });
+ },
+ );
+
+ it('reads payload from an explicit file', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'twenty-exec-payload-'));
+ try {
+ const file = join(directory, 'payload.json');
+ await writeFile(file, '{"name":"Grace"}');
+ const result = await runJson(
+ '--name',
+ 'helloWorld',
+ '--payload',
+ `@${file}`,
+ );
+ expect(result.exitCode).toBe(0);
+ expect(JSON.parse(mutations()[0].body).variables).toEqual({
+ v1: { id: FUNCTION.id, payload: { name: 'Grace' } },
+ });
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ it('does not execute a function owned by another installed app, even if the local identifier matches', async () => {
+ queryResult = {
+ data: {
+ findOneApplication: APPLICATION,
+ findManyLogicFunctions: [{ ...FUNCTION, applicationId: 'another-app' }],
+ },
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(4);
+ expect(result.envelope.error.code).toBe('NOT_FOUND');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('does not execute a function absent from the local manifest', async () => {
+ queryResult = {
+ data: {
+ findOneApplication: APPLICATION,
+ findManyLogicFunctions: [
+ { ...FUNCTION, universalIdentifier: OTHER_FUNCTION_IDENTIFIER },
+ ],
+ },
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(4);
+ expect(mutations()).toEqual([]);
+ });
+
+ it('reports a missing hook without executing another function', async () => {
+ const result = await runJson('--post-install');
+ expect(result.exitCode).toBe(4);
+ expect(result.envelope.error.details.availableFunctions).toEqual([
+ { name: FUNCTION.name, universalIdentifier: FUNCTION_IDENTIFIER },
+ ]);
+ expect(mutations()).toEqual([]);
+ });
+
+ it('fails ambiguous selection rather than choosing the first function', async () => {
+ queryResult = {
+ data: {
+ findOneApplication: APPLICATION,
+ findManyLogicFunctions: [FUNCTION, { ...FUNCTION, id: 'duplicate-id' }],
+ },
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(6);
+ expect(result.envelope.error.code).toBe('AMBIGUOUS_RESOURCE');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('reports manifest diagnostics and does not execute when source loading fails', async () => {
+ vi.mocked(runAppWorker).mockResolvedValue({
+ result: {
+ success: false,
+ error: { code: 'MANIFEST_BUILD_FAILED', message: 'Broken definition' },
+ diagnostics: [],
+ },
+ isSnapshotHeld: false,
+ output: { stdout: '', stderr: '', isTruncated: false },
+ });
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error.code).toBe('BUILD_FAILED');
+ expect(server.requests).toEqual([]);
+ });
+
+ it('returns nonzero with logs and structured function errors for a completed failure', async () => {
+ executionResult = {
+ data: {
+ executeOneLogicFunction: {
+ ...EXECUTION,
+ status: 'ERROR',
+ error: {
+ errorType: 'Error',
+ errorMessage: 'Oops',
+ stackTrace: 'stack',
+ },
+ },
+ },
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope).toMatchObject({
+ ok: false,
+ error: {
+ code: 'EXECUTION_FAILED',
+ details: {
+ outcome: 'completed',
+ status: 'ERROR',
+ durationMilliseconds: 12,
+ logs: EXECUTION.logs,
+ error: { errorMessage: 'Oops' },
+ },
+ },
+ });
+ expect(mutations()).toHaveLength(1);
+ });
+
+ it('shows returned error details and logs in human mode', async () => {
+ executionResult = {
+ data: {
+ executeOneLogicFunction: {
+ ...EXECUTION,
+ status: 'ERROR',
+ error: { errorMessage: 'Oops' },
+ },
+ },
+ };
+ const result = await run('--name', 'helloWorld');
+ expect(result.exitCode).toBe(1);
+ expect(result.stderr).toContain('Status: ERROR');
+ expect(result.stderr).toContain('Oops');
+ expect(result.stderr).toContain('Hello from the function');
+ });
+
+ it('preserves permission errors without retrying execution', async () => {
+ executionResult = {
+ errors: [
+ {
+ message: 'This endpoint requires a token bound to a user.',
+ extensions: { code: 'FORBIDDEN' },
+ },
+ ],
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(3);
+ expect(result.envelope.error).toMatchObject({
+ code: 'PERMISSION_DENIED',
+ details: { outcome: 'not-started' },
+ });
+ expect(mutations()).toHaveLength(1);
+ });
+
+ it.each(['NOT_FOUND', 'BAD_USER_INPUT', 'GRAPHQL_VALIDATION_FAILED'])(
+ 'reports a rejected request for %s without claiming execution started',
+ async (code) => {
+ executionResult = {
+ errors: [{ message: 'Execution rejected', extensions: { code } }],
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error.details.outcome).toBe('not-started');
+ expect(mutations()).toHaveLength(1);
+ },
+ );
+
+ it('keeps an unknown outcome for server internal errors', async () => {
+ executionResult = {
+ errors: [
+ {
+ message: 'Internal error',
+ extensions: { code: 'INTERNAL_SERVER_ERROR' },
+ },
+ ],
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.envelope.error.details.outcome).toBe('unknown');
+ expect(mutations()).toHaveLength(1);
+ });
+
+ it('reports an uninstalled app without attempting execution', async () => {
+ queryResult = {
+ errors: [
+ {
+ message: 'Application not found',
+ path: ['findOneApplication'],
+ extensions: { code: 'NOT_FOUND', subCode: 'APPLICATION_NOT_FOUND' },
+ },
+ ],
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(4);
+ expect(result.envelope.error.code).toBe('APP_NOT_INSTALLED');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('rejects a mismatched application identity before execution', async () => {
+ queryResult = {
+ data: {
+ findOneApplication: {
+ ...APPLICATION,
+ universalIdentifier: OTHER_FUNCTION_IDENTIFIER,
+ },
+ findManyLogicFunctions: [FUNCTION],
+ },
+ };
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(mutations()).toEqual([]);
+ });
+
+ it.each(['disconnect', 'http-error', 'invalid-response', 'interrupt'])(
+ 'reports an uncertain outcome after %s without replaying',
+ async (mode) => {
+ disconnect = mode === 'disconnect';
+ interrupt = mode === 'interrupt';
+ if (mode === 'http-error') {
+ executionStatus = 503;
+ }
+ if (mode === 'invalid-response') {
+ executionResult = { data: { executeOneLogicFunction: null } };
+ }
+ const result = await runJson('--name', 'helloWorld');
+ expect(result.exitCode).toBe(mode === 'interrupt' ? 130 : 1);
+ expect(result.envelope.error.details.outcome).toBe('unknown');
+ expect(result.envelope.error.hint).toContain('before retrying');
+ expect(mutations()).toHaveLength(1);
+ },
+ );
+
+ it('rejects streaming output before resolving the target', async () => {
+ const result = await run('--name', 'helloWorld', '--format', 'ndjson');
+ expect(result.exitCode).toBe(2);
+ expect(resolveCommandTarget).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
new file mode 100644
index 00000000000..606ff5ccc93
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
@@ -0,0 +1,423 @@
+import {
+ copyFile,
+ cp,
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises';
+import type * as fileSystemPromises from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';
+import { isDefined } from 'twenty-shared/utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { getAppTemplateDirectory } from '@/app/get-app-template-directory';
+import { getAppTemplateOverlayDirectory } from '@/app/get-app-template-overlay-directory';
+
+vi.mock('@/app/get-app-template-directory', () => ({
+ getAppTemplateDirectory: vi.fn(),
+}));
+
+vi.mock('@/app/get-app-template-overlay-directory', () => ({
+ getAppTemplateOverlayDirectory: vi.fn(),
+}));
+
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof fileSystemPromises>();
+
+ return { ...actual, copyFile: vi.fn(actual.copyFile) };
+});
+
+const TEMPLATE_DIRECTORY = fileURLToPath(
+ new URL(
+ '../../../../../create-twenty-app/src/constants/template',
+ import.meta.url,
+ ),
+);
+
+const TEMPLATE_OVERLAY_DIRECTORY = fileURLToPath(
+ new URL('../../../../app-template-overlay', import.meta.url),
+);
+
+const UUID_PATTERN =
+ /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/g;
+
+const LOGIN_STEP = 'twenty auth login --url <url> --name <name>';
+
+describe('app init', () => {
+ let root: string;
+ let workDirectory: string;
+
+ const run = (args: string[]) => runCliForTest(['app', 'init', ...args]);
+ const runJson = async (args: string[]) => {
+ const result = await run([...args, '--json']);
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+ const readUniversalIdentifiers = (appDirectory: string) =>
+ readFile(
+ join(appDirectory, 'src', 'constants', 'universal-identifiers.ts'),
+ 'utf8',
+ );
+ const readPackageJson = async (appDirectory: string) =>
+ JSON.parse(await readFile(join(appDirectory, 'package.json'), 'utf8'));
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-app-init-'));
+ workDirectory = join(root, 'work');
+ await mkdir(join(root, 'home'));
+ await mkdir(workDirectory);
+ vi.mocked(getAppTemplateDirectory).mockReturnValue(TEMPLATE_DIRECTORY);
+ vi.mocked(getAppTemplateOverlayDirectory).mockReturnValue(
+ TEMPLATE_OVERLAY_DIRECTORY,
+ );
+ vi.stubEnv('HOME', join(root, 'home'));
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.spyOn(process, 'cwd').mockReturnValue(workDirectory);
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('creates the app from the bundled template without installing or saving anything', async () => {
+ const result = await run(['my-app']);
+ const appDirectory = join(workDirectory, 'my-app');
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(await readdir(workDirectory)).toEqual(['my-app']);
+ expect(await readdir(appDirectory)).toEqual(
+ expect.arrayContaining([
+ '.github',
+ '.gitignore',
+ '.yarnrc.yml',
+ 'AGENTS.md',
+ 'CLAUDE.md',
+ 'package.json',
+ 'public',
+ 'src',
+ ]),
+ );
+ expect(await readdir(appDirectory)).not.toContain('node_modules');
+ expect(await readPackageJson(appDirectory)).toMatchObject({
+ name: 'my-app',
+ engines: {
+ node: '^24.5.0',
+ npm: 'please-use-yarn',
+ twenty: `>=${TEMPLATE_PACKAGE_VERSION}`,
+ yarn: '>=4.0.2',
+ },
+ devDependencies: {
+ 'twenty-client-sdk': TEMPLATE_PACKAGE_VERSION,
+ 'twenty-sdk': TEMPLATE_PACKAGE_VERSION,
+ 'twenty-ui': TEMPLATE_PACKAGE_VERSION,
+ },
+ });
+
+ const universalIdentifiers = await readUniversalIdentifiers(appDirectory);
+ const identifiers = universalIdentifiers.match(UUID_PATTERN) ?? [];
+
+ expect(universalIdentifiers).toContain("APP_DISPLAY_NAME = 'My app'");
+ expect(universalIdentifiers).not.toContain('TO-BE-GENERATED');
+ expect(identifiers.length).toBeGreaterThan(1);
+ expect(new Set(identifiers).size).toBe(identifiers.length);
+ expect(result.stdout).toContain('Created my-app in my-app');
+
+ for (const command of [
+ 'cd my-app',
+ 'yarn install',
+ LOGIN_STEP,
+ 'twenty app apply --create',
+ ]) {
+ expect(result.stdout).toContain(command);
+ }
+
+ await expect(stat(join(root, 'home', '.twenty'))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ });
+
+ it('writes an integration test setup that runs the globally installed CLI', async () => {
+ const result = await run(['my-app']);
+ const testsDirectory = join(workDirectory, 'my-app', 'src', '__tests__');
+
+ expect(result.exitCode, result.stderr).toBe(0);
+
+ const globalSetup = await readFile(
+ join(testsDirectory, 'global-setup.ts'),
+ 'utf8',
+ );
+
+ expect(globalSetup).toContain("import { runTwenty } from './run-twenty';");
+ expect(globalSetup).toContain("runTwenty(['app', 'apply', '--create'])");
+ expect(globalSetup).not.toContain('twenty-sdk/cli');
+ expect(await readFile(join(testsDirectory, 'run-twenty.ts'), 'utf8')).toBe(
+ await readFile(
+ join(TEMPLATE_OVERLAY_DIRECTORY, 'src', '__tests__', 'run-twenty.ts'),
+ 'utf8',
+ ),
+ );
+ expect((await readdir(testsDirectory)).sort()).toEqual([
+ 'application-config.test.ts',
+ 'global-setup.ts',
+ 'run-twenty.ts',
+ 'schema.integration-test.ts',
+ ]);
+ });
+
+ it('returns the app, its pins and the next steps as JSON, without a login step when a workspace is set', async () => {
+ vi.stubEnv('TWENTY_API_URL', 'https://crm.example.com');
+ vi.stubEnv('TWENTY_API_KEY', 'test-key');
+
+ const result = await runJson([
+ '@acme/billing',
+ '--path',
+ 'apps/billing',
+ '--description',
+ 'Invoices',
+ ]);
+ const appDirectory = join(workDirectory, 'apps', 'billing');
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.envelope.data).toEqual({
+ app: {
+ name: '@acme/billing',
+ displayName: 'Acme billing',
+ description: 'Invoices',
+ path: appDirectory,
+ },
+ packages: [
+ { name: 'twenty-client-sdk', version: TEMPLATE_PACKAGE_VERSION },
+ { name: 'twenty-sdk', version: TEMPLATE_PACKAGE_VERSION },
+ { name: 'twenty-ui', version: TEMPLATE_PACKAGE_VERSION },
+ ],
+ nextSteps: [
+ { command: 'cd apps/billing', description: 'Enter the new app' },
+ {
+ command: 'yarn install',
+ description: 'Install the pinned dependencies',
+ },
+ {
+ command: 'twenty app apply --create',
+ description: 'Build the app and install it in your workspace',
+ },
+ ],
+ });
+ expect((await readPackageJson(appDirectory)).name).toBe('@acme/billing');
+ });
+
+ it('writes quotes and replacement patterns in the display name and description literally', async () => {
+ const result = await run([
+ 'my-app',
+ '--display-name',
+ "Bob's app",
+ '--description',
+ 'Costs $& more',
+ ]);
+ const universalIdentifiers = await readUniversalIdentifiers(
+ join(workDirectory, 'my-app'),
+ );
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(universalIdentifiers).toContain("APP_DISPLAY_NAME = 'Bob\\'s app'");
+ expect(universalIdentifiers).toContain("APP_DESCRIPTION = 'Costs $& more'");
+ });
+
+ it('fills an existing empty directory in place, including the current one', async () => {
+ const appDirectory = join(workDirectory, 'my-app');
+
+ await mkdir(appDirectory);
+
+ const { ino } = await stat(appDirectory);
+
+ vi.spyOn(process, 'cwd').mockReturnValue(appDirectory);
+
+ const result = await runJson(['my-app', '--path', '.']);
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect((await stat(appDirectory)).ino).toBe(ino);
+ expect(await readdir(appDirectory)).toContain('package.json');
+ expect(await readdir(workDirectory)).toEqual(['my-app']);
+ expect(
+ result.envelope.data.nextSteps.map(
+ ({ command }: { command: string }) => command,
+ ),
+ ).toEqual(['yarn install', LOGIN_STEP, 'twenty app apply --create']);
+ });
+
+ it('never overwrites a file that appears in the empty directory while the app is copied in', async () => {
+ const appDirectory = join(workDirectory, 'my-app');
+ const actualFileSystem =
+ await vi.importActual<typeof fileSystemPromises>('node:fs/promises');
+ let concurrentFile = '';
+
+ await mkdir(appDirectory);
+ vi.mocked(copyFile).mockImplementationOnce(
+ async (source, destination, mode) => {
+ concurrentFile = String(destination);
+ await actualFileSystem.writeFile(
+ destination,
+ 'concurrent user contents',
+ );
+
+ return actualFileSystem.copyFile(source, destination, mode);
+ },
+ );
+
+ const result = await runJson(['my-app']);
+ const remainingFiles = (
+ await readdir(appDirectory, { recursive: true, withFileTypes: true })
+ )
+ .filter((entry) => entry.isFile())
+ .map((entry) => join(entry.parentPath, entry.name));
+
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error.code).toBe('APP_INIT_FAILED');
+ expect(remainingFiles).toEqual([concurrentFile]);
+ expect(await readFile(concurrentFile, 'utf8')).toBe(
+ 'concurrent user contents',
+ );
+ expect(await readdir(workDirectory)).toEqual(['my-app']);
+ });
+
+ it.each([
+ {
+ title: 'a saved remote',
+ config: {
+ version: 1,
+ defaultRemote: 'production',
+ remotes: {
+ production: { apiUrl: 'https://crm.example.com', apiKey: 'key' },
+ staging: {
+ apiUrl: 'https://staging.example.com',
+ apiKey: 'staging-key',
+ },
+ },
+ },
+ expectedCommands: ['twenty app apply --create --remote staging'],
+ },
+ {
+ title: 'a remote that is not saved yet',
+ config: undefined,
+ expectedCommands: [
+ 'twenty auth login --url <url> --name staging',
+ 'twenty app apply --create --remote staging',
+ ],
+ },
+ ])(
+ 'points the next steps at $title passed with --remote',
+ async ({ config, expectedCommands }) => {
+ if (isDefined(config)) {
+ await mkdir(join(root, 'home', '.twenty'));
+ await writeFile(
+ join(root, 'home', '.twenty', 'config.json'),
+ JSON.stringify(config),
+ );
+ }
+
+ const result = await runJson(['remote-app', '--remote', 'staging']);
+
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(
+ result.envelope.data.nextSteps
+ .map(({ command }: { command: string }) => command)
+ .slice(2),
+ ).toEqual(expectedCommands);
+ },
+ );
+
+ it.each([
+ {
+ title: 'a directory with files',
+ prepare: async (target: string) => {
+ await mkdir(target);
+ await writeFile(join(target, 'notes.md'), 'mine');
+ },
+ ownFile: (target: string) => join(target, 'notes.md'),
+ reason: 'is not empty',
+ },
+ {
+ title: 'a file',
+ prepare: (target: string) => writeFile(target, 'mine'),
+ ownFile: (target: string) => target,
+ reason: 'is not a directory',
+ },
+ ])(
+ 'refuses to create the app over $title and leaves it untouched',
+ async ({ prepare, ownFile, reason }) => {
+ const target = join(workDirectory, 'my-app');
+
+ await prepare(target);
+
+ const result = await runJson(['my-app']);
+
+ expect(result.exitCode).toBe(6);
+ expect(result.envelope.error).toMatchObject({
+ code: 'APP_PATH_UNAVAILABLE',
+ message: `${target} already exists and ${reason}.`,
+ });
+ expect(await readFile(ownFile(target), 'utf8')).toBe('mine');
+ expect(await readdir(workDirectory)).toEqual(['my-app']);
+ },
+ );
+
+ it.each([
+ 'My App',
+ '.hidden',
+ '_private',
+ 'UPPER',
+ 'apps/billing',
+ 'node_modules',
+ 'favicon.ico',
+ ])('rejects %s as a package name', async (name) => {
+ const result = await runJson([name]);
+
+ expect(result.exitCode).toBe(2);
+ expect(result.envelope.error.code).toBe('INVALID_APP_NAME');
+ expect(await readdir(workDirectory)).toEqual([]);
+ });
+
+ it('leaves nothing behind when the template cannot be copied', async () => {
+ vi.mocked(getAppTemplateDirectory).mockReturnValue(
+ join(root, 'missing-template'),
+ );
+
+ const result = await runJson(['my-app']);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error.code).toBe('APP_INIT_FAILED');
+ expect(await readdir(workDirectory)).toEqual([]);
+ });
+
+ it('refuses a template it cannot fully render and leaves nothing behind', async () => {
+ const template = join(root, 'template');
+
+ await cp(TEMPLATE_DIRECTORY, template, { recursive: true });
+ await writeFile(join(template, 'OWNERS.md'), 'Owner: TO-BE-GENERATED');
+ vi.mocked(getAppTemplateDirectory).mockReturnValue(template);
+
+ const result = await runJson(['my-app']);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'APP_INIT_FAILED',
+ details: { unrenderedFiles: ['OWNERS.md'] },
+ });
+ expect(await readdir(workDirectory)).toEqual([]);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-logs.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-logs.spec.ts
new file mode 100644
index 00000000000..855db622f37
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-logs.spec.ts
@@ -0,0 +1,482 @@
+import { type ServerResponse } from 'node:http';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { runCliForTest } from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { resolveCommandTarget } from '@/program/resolve-command-target';
+import { runCli } from '@/run-cli';
+
+vi.mock('@/app/read-app-identity');
+vi.mock('@/program/resolve-command-target');
+vi.mock('@/app/project/resolve-app-project', () => ({
+ resolveAppProject: async () => ({ path: '/test-app', name: 'test-app' }),
+}));
+
+const APPLICATION_IDENTIFIER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const FIRST_FUNCTION_IDENTIFIER = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const SECOND_FUNCTION_IDENTIFIER = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const entry = (identifier = FIRST_FUNCTION_IDENTIFIER, logs = 'Hello\n') => ({
+ data: {
+ logicFunctionLogs: {
+ logs,
+ name: 'same-name',
+ universalIdentifier: identifier,
+ },
+ },
+});
+const next = (data: unknown) =>
+ `event: next\ndata: ${JSON.stringify(data)}\n\n`;
+const complete = 'event: complete\n\n';
+const open = (response: ServerResponse) => {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.write(': ping\n\n');
+};
+let handler: (body: string, response: ServerResponse) => void;
+const server = await startTestServer((request, response) =>
+ handler(request.body, response),
+);
+const run = (...options: string[]) =>
+ runCliForTest(['app', 'logs', ...options]);
+const runStream = async (...options: string[]) => {
+ const result = await run(...options, '--format', 'ndjson');
+ return {
+ ...result,
+ events: result.stdout
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line)),
+ };
+};
+
+beforeEach(() => {
+ server.requests.length = 0;
+ handler = (_body, response) => {
+ open(response);
+ response.end(
+ next(entry()) +
+ next(entry(SECOND_FUNCTION_IDENTIFIER, 'Second\n')) +
+ complete,
+ );
+ };
+ vi.mocked(readAppIdentity).mockResolvedValue({
+ application: {
+ universalIdentifier: APPLICATION_IDENTIFIER,
+ displayName: 'Test app',
+ },
+ diagnostics: [],
+ });
+ vi.mocked(resolveCommandTarget).mockResolvedValue({
+ apiUrl: server.url,
+ bearerToken: 'private-api-key',
+ credentialKind: 'apiKey',
+ source: 'remote',
+ remoteName: 'dev',
+ });
+});
+afterEach(() => vi.clearAllMocks());
+afterAll(async () => server.close());
+
+describe('twenty app logs', () => {
+ it('subscribes only to this app and labels every matching function, including duplicate names', async () => {
+ const result = await runStream();
+ expect(result.exitCode).toBe(0);
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0]).toMatchObject({
+ method: 'POST',
+ path: '/metadata',
+ headers: {
+ authorization: 'Bearer private-api-key',
+ accept: 'text/event-stream',
+ },
+ });
+ expect(JSON.parse(server.requests[0].body).variables).toEqual({
+ input: { applicationUniversalIdentifier: APPLICATION_IDENTIFIER },
+ });
+ expect(result.events.map(({ type }) => type)).toEqual([
+ 'start',
+ 'progress',
+ 'record',
+ 'record',
+ 'result',
+ ]);
+ expect(
+ result.events
+ .filter(({ type }) => type === 'record')
+ .map(({ data }) => data.functionUniversalIdentifier),
+ ).toEqual([FIRST_FUNCTION_IDENTIFIER, SECOND_FUNCTION_IDENTIFIER]);
+ expect(result.events.at(-1).data.recordCount).toBe(2);
+ expect(result.stdout).not.toContain('private-api-key');
+ });
+
+ it('treats an exact name as a filter that can match several functions', async () => {
+ const result = await runStream('--name', 'same-name');
+ expect(result.events.filter(({ type }) => type === 'record')).toHaveLength(
+ 2,
+ );
+ expect(JSON.parse(server.requests[0].body).variables.input).toEqual({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'same-name',
+ });
+ });
+
+ it.each([4, 5, 6, 7, 8])(
+ 'subscribes with a canonical UUIDv%s universal identifier filter',
+ async (version) => {
+ const universalIdentifier = `bbbbbbbb-bbbb-${version}bbb-8bbb-bbbbbbbbbbbb`;
+ handler = (_body, response) => {
+ open(response);
+ response.end(next(entry(universalIdentifier)) + complete);
+ };
+
+ const result = await runStream(
+ '--universal-identifier',
+ universalIdentifier.toUpperCase(),
+ );
+
+ expect(result.exitCode).toBe(0);
+ expect(server.requests).toHaveLength(1);
+ expect(JSON.parse(server.requests[0].body).variables.input).toEqual({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ universalIdentifier,
+ });
+ expect(
+ result.events
+ .filter(({ type }) => type === 'record')
+ .map(({ data }) => data.functionUniversalIdentifier),
+ ).toEqual([universalIdentifier]);
+ },
+ );
+
+ it.each([
+ ['--name', ''],
+ ['--universal-identifier', 'invalid'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-1bbb-8bbb-bbbbbbbbbbbb'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-2bbb-8bbb-bbbbbbbbbbbb'],
+ ['--universal-identifier', 'bbbbbbbb-bbbb-3bbb-8bbb-bbbbbbbbbbbb'],
+ ['--name', 'test', '--universal-identifier', FIRST_FUNCTION_IDENTIFIER],
+ ])('rejects invalid filters before loading source', async (...options) => {
+ const result = await runStream(...options);
+ expect(result.exitCode).toBe(2);
+ expect(readAppIdentity).not.toHaveBeenCalled();
+ expect(server.requests).toEqual([]);
+ });
+
+ it('rejects finite JSON before target resolution', async () => {
+ const result = await run('--json');
+ expect(result.exitCode).toBe(2);
+ expect(resolveCommandTarget).not.toHaveBeenCalled();
+ });
+
+ it('requires an application definition', async () => {
+ vi.mocked(readAppIdentity).mockResolvedValue({
+ application: null,
+ diagnostics: [],
+ });
+ const result = await runStream();
+ expect(result.exitCode).toBe(2);
+ expect(server.requests).toEqual([]);
+ });
+
+ it('prints escaped human logs with function identities', async () => {
+ handler = (_body, response) => {
+ open(response);
+ response.end(
+ next(entry(FIRST_FUNCTION_IDENTIFIER, 'Hello\n\u001b[2J')) + complete,
+ );
+ };
+ const result = await run();
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain(
+ `[same-name · ${FIRST_FUNCTION_IDENTIFIER}]`,
+ );
+ expect(result.stdout).toContain('Hello');
+ expect(result.stdout).not.toContain('\u001b');
+ expect(result.stdout).toContain('\\u001b');
+ });
+
+ it('colors the function name and dims its identifier in a color terminal', async () => {
+ vi.stubEnv('FORCE_COLOR', '1');
+ try {
+ const result = await run();
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain(
+ `[\u001b[36msame-name\u001b[39m · \u001b[2m${FIRST_FUNCTION_IDENTIFIER}\u001b[22m]`,
+ );
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it.each(['http', 'sse', 'sse-without-code'])(
+ 'falls back once for missing identity fields over %s, with an explicit warning',
+ async (transport) => {
+ handler = (body, response) => {
+ if (JSON.parse(body).query.includes('name universalIdentifier')) {
+ const payload = {
+ errors: [
+ {
+ message:
+ 'Cannot query field "name" on type "LogicFunctionLogs".',
+ ...(transport === 'sse-without-code'
+ ? {}
+ : { extensions: { code: 'GRAPHQL_VALIDATION_FAILED' } }),
+ },
+ ],
+ };
+ if (transport === 'http') {
+ sendJson(response, 400, payload);
+ } else {
+ open(response);
+ response.end(next(payload) + complete);
+ }
+ } else {
+ open(response);
+ response.end(
+ next({ data: { logicFunctionLogs: { logs: 'Legacy\n' } } }) +
+ complete,
+ );
+ }
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(0);
+ expect(server.requests).toHaveLength(2);
+ expect(
+ result.events.find(({ type }) => type === 'warning').data.code,
+ ).toBe('LOG_IDENTITY_UNAVAILABLE');
+ expect(
+ result.events.find(({ type }) => type === 'record').data,
+ ).toMatchObject({
+ functionName: null,
+ functionUniversalIdentifier: null,
+ logs: 'Legacy\n',
+ });
+ },
+ );
+
+ it('does not fall back on unrelated validation errors', async () => {
+ handler = (_body, response) => {
+ open(response);
+ response.end(
+ next({
+ errors: [
+ {
+ message: 'Cannot query field "name" on type "LogicFunctionLogs".',
+ },
+ {
+ message:
+ 'Unknown argument "input" on field "Subscription.logicFunctionLogs".',
+ },
+ ],
+ }) + complete,
+ );
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(1);
+ expect(server.requests).toHaveLength(1);
+ expect(result.events.some(({ type }) => type === 'warning')).toBe(false);
+ });
+
+ it.each([
+ ['--name', 'same-name', 'functionName'],
+ [
+ '--universal-identifier',
+ FIRST_FUNCTION_IDENTIFIER,
+ 'functionUniversalIdentifier',
+ ],
+ ])(
+ 'retains the explicit %s filter identity with an older server',
+ async (option, value, field) => {
+ handler = (body, response) => {
+ open(response);
+ response.end(
+ next(
+ JSON.parse(body).query.includes('name universalIdentifier')
+ ? {
+ errors: [
+ {
+ message:
+ 'Cannot query field "name" on type "LogicFunctionLogs".',
+ },
+ ],
+ }
+ : { data: { logicFunctionLogs: { logs: 'Legacy' } } },
+ ) + complete,
+ );
+ };
+ const result = await runStream(option, value);
+ expect(result.exitCode).toBe(0);
+ expect(
+ result.events.find(({ type }) => type === 'record').data[field],
+ ).toBe(value);
+ expect(server.requests).toHaveLength(2);
+ },
+ );
+
+ it.each(['FORBIDDEN', 'UNAUTHENTICATED', 'INTERNAL_SERVER_ERROR'])(
+ 'does not retry or fall back on %s',
+ async (code) => {
+ handler = (_body, response) => {
+ open(response);
+ response.end(
+ next({ errors: [{ message: 'Rejected', extensions: { code } }] }) +
+ complete,
+ );
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(code === 'INTERNAL_SERVER_ERROR' ? 1 : 3);
+ expect(server.requests).toHaveLength(1);
+ expect(result.events.at(-1).type).toBe('error');
+ },
+ );
+
+ it('never falls back after emitting a log record', async () => {
+ handler = (_body, response) => {
+ open(response);
+ response.end(
+ next(entry()) +
+ next({
+ errors: [
+ {
+ message:
+ 'Cannot query field "name" on type "LogicFunctionLogs".',
+ extensions: { code: 'GRAPHQL_VALIDATION_FAILED' },
+ },
+ ],
+ }),
+ );
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(1);
+ expect(server.requests).toHaveLength(1);
+ expect(result.events.at(-1).data.details.recordCount).toBe(1);
+ });
+
+ it.each([
+ 'broken-json',
+ 'broken-record',
+ 'unexpected-event',
+ 'eof',
+ 'disconnect',
+ ])(
+ 'reports %s with no reconnect and preserves prior records',
+ async (failure) => {
+ handler = (_body, response) => {
+ open(response);
+ response.write(next(entry()));
+ if (failure === 'disconnect') {
+ setTimeout(() => response.destroy(), 20);
+ return;
+ }
+ const last =
+ failure === 'broken-json'
+ ? 'event: next\ndata: not-json\n\n'
+ : failure === 'broken-record'
+ ? next({ data: { logicFunctionLogs: null } })
+ : failure === 'unexpected-event'
+ ? 'event: unknown\ndata: {}\n\n'
+ : '';
+ response.end(last);
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(1);
+ expect(server.requests).toHaveLength(1);
+ expect(result.events.at(-1).type).toBe('error');
+ expect(result.events.at(-1).data.details.recordCount).toBe(1);
+ if (failure === 'disconnect' || failure === 'eof') {
+ expect(result.events.at(-1).data.hint).toContain('cannot be replayed');
+ }
+ },
+ );
+
+ it.each(['human', 'ndjson'])(
+ 'waits for %s output to drain before writing the next record',
+ async (mode) => {
+ const firstRecord = Promise.withResolvers<void>();
+ const records: string[] = [];
+ const stdout = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation((chunk) => {
+ const text = String(chunk);
+ if (
+ mode === 'ndjson'
+ ? text.includes('"type":"record"')
+ : text.startsWith('[same-name')
+ ) {
+ records.push(text);
+ if (records.length === 1) {
+ firstRecord.resolve();
+ return false;
+ }
+ }
+ return true;
+ });
+ const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true);
+ const previousExitCode = process.exitCode;
+ const running = runCli(['app', 'logs', '--format', mode]);
+ try {
+ await firstRecord.promise;
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(records).toHaveLength(1);
+ process.stdout.emit('drain');
+ await running;
+ expect(records).toHaveLength(2);
+ } finally {
+ process.stdout.emit('drain');
+ await running;
+ stdout.mockRestore();
+ stderr.mockRestore();
+ process.exitCode = previousExitCode;
+ }
+ },
+ );
+
+ it.each([401, 403, 503])(
+ 'preserves HTTP %s failures without a retry',
+ async (status) => {
+ handler = (_body, response) =>
+ sendJson(response, status, { message: 'Unavailable' });
+ const result = await runStream();
+ expect(result.exitCode).toBe(status === 503 ? 1 : 3);
+ expect(server.requests).toHaveLength(1);
+ },
+ );
+
+ it('does not follow redirects or forward credentials elsewhere', async () => {
+ handler = (_body, response) => {
+ response.writeHead(307, {
+ location: 'https://elsewhere.invalid/metadata',
+ });
+ response.end();
+ };
+ const result = await runStream();
+ expect(result.events.at(-1).data.code).toBe('REDIRECT_NOT_FOLLOWED');
+ expect(server.requests).toHaveLength(1);
+ });
+
+ it('cancels an idle subscription with exit 130 and closes its connection', async () => {
+ let closed = false;
+ handler = (_body, response) => {
+ open(response);
+ response.on('close', () => {
+ closed = true;
+ });
+ setTimeout(() => process.emit('SIGINT'), 20);
+ };
+ const result = await runStream();
+ expect(result.exitCode).toBe(130);
+ expect(result.events.at(-1).data.code).toBe('CANCELLED');
+ await vi.waitFor(() => expect(closed).toBe(true));
+ expect(server.requests).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-plan.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-plan.spec.ts
new file mode 100644
index 00000000000..d2f967f7d8a
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-plan.spec.ts
@@ -0,0 +1,504 @@
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { writeTestSourceSdk } from '@/app/__tests__/utils/write-test-source-sdk';
+import { rm, mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ afterAll,
+ beforeAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+const worker = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => worker,
+}));
+
+let workerDirectory: string;
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-command-worker-'));
+ await buildTestAppWorker(workerDirectory, { useToolingFixture: true });
+ worker.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60_000);
+
+afterAll(() => rm(workerDirectory, { recursive: true, force: true }));
+
+const APPLICATION = {
+ universalIdentifier: 'app-id',
+ name: 'plan-app',
+ displayName: 'Plan App',
+};
+const MANIFEST = { application: APPLICATION };
+const ACTIONS = [
+ {
+ type: 'create',
+ metadataName: 'logicFunction',
+ flatEntity: { name: 'sendWelcome', universalIdentifier: 'function-id' },
+ },
+ {
+ type: 'update',
+ metadataName: 'fieldMetadata',
+ universalIdentifier: 'field-id',
+ flatEntity: { name: 'name' },
+ diff: { label: { before: 'Name', after: 'Full name' } },
+ },
+ {
+ type: 'delete',
+ metadataName: 'objectMetadata',
+ universalIdentifier: 'object-id',
+ flatEntity: { nameSingular: 'company' },
+ },
+ {
+ type: 'delete',
+ metadataName: 'view',
+ universalIdentifier: 'view-id',
+ flatEntity: { name: 'Old view' },
+ },
+];
+
+const planResponse = (
+ actions: unknown = ACTIONS,
+ applicationUniversalIdentifier = 'app-id',
+) => ({
+ data: { syncApplication: { applicationUniversalIdentifier, actions } },
+});
+
+const state: { response: unknown; status: number } = {
+ response: planResponse(),
+ status: 200,
+};
+const server = await startTestServer((_request, response) => {
+ sendJson(response, state.status, state.response);
+});
+
+const graphqlError = (code: string, subCode?: string, path?: string) => ({
+ data: null,
+ errors: [
+ {
+ message: 'The server refused the preview.',
+ ...(isDefined(path) ? { path: [path] } : {}),
+ extensions: { code, subCode },
+ },
+ ],
+});
+
+describe('app plan', () => {
+ let appPath: string;
+
+ const run = (...args: string[]) =>
+ runCliForTest(['app', 'plan', '--path', appPath, ...args]);
+ const runJson = async (...args: string[]) => {
+ const result = await run(...args, '--json');
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+ const writeBuild = async (overrides: Record<string, unknown> = {}) => {
+ const build = {
+ buildId: 'build-id',
+ contentHash: 'a'.repeat(64),
+ application: APPLICATION,
+ manifestFormat: 'twenty-application',
+ manifest: MANIFEST,
+ files: [],
+ ...overrides,
+ };
+
+ await writeFile(
+ join(appPath, 'test-tooling.cjs'),
+ `
+ const fs = require('node:fs');
+ exports.buildSourceSnapshot = async () => {
+ console.log('project output');
+ fs.appendFileSync(__dirname + '/builds.txt', 'built\\n');
+ return { success: true, data: ${JSON.stringify(build)}, diagnostics: [] };
+ };
+ exports.releaseSourceSnapshot = async ({ buildId }) => {
+ fs.writeFileSync(__dirname + '/released.txt', buildId);
+ return { success: true, data: null, diagnostics: [] };
+ };
+ `,
+ );
+ };
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-plan-'));
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'plan-app',
+ devDependencies: { 'twenty-sdk': '9.9.9' },
+ }),
+ );
+ await writeTestSourceSdk({ appPath });
+ await writeBuild();
+ await mkdir(join(appPath, '.twenty'), { recursive: true });
+ await writeFile(join(appPath, '.twenty', 'base.json'), 'existing base');
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'plan-test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ state.response = planResponse();
+ state.status = 200;
+ server.requests.length = 0;
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+ afterAll(() => server.close());
+
+ it.each([true, false])(
+ 'requests only a dry run with deletion inference %s',
+ async (inferDeletion) => {
+ const options = inferDeletion ? [] : ['--no-delete'];
+ const { envelope, exitCode, stdout } = await runJson(...options);
+
+ expect(exitCode).toBe(0);
+ expect(envelope).toMatchObject({
+ command: 'app plan',
+ target: { apiUrl: server.url },
+ data: {
+ application: APPLICATION,
+ plan: true,
+ inferDeletionFromMissingEntities: options.length === 0,
+ actions: ACTIONS,
+ summary: { create: 1, update: 1, delete: 2, destructive: 1 },
+ },
+ });
+ expect(envelope.data).not.toHaveProperty('manifest');
+ expect(stdout).not.toContain('plan-test-key');
+ expect(envelope.data.diagnostics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ code: 'PROJECT_OUTPUT' }),
+ ]),
+ );
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0]).toMatchObject({
+ path: '/metadata',
+ headers: { authorization: 'Bearer plan-test-key' },
+ });
+ expect(readGraphqlRequest(server.requests[0])).toMatchObject({
+ query: expect.stringContaining('mutation PreviewApplication'),
+ arguments: {
+ dryRun: true,
+ manifest: MANIFEST,
+ inferDeletionFromMissingEntities: options.length === 0,
+ },
+ });
+ expect(await readFile(join(appPath, 'builds.txt'), 'utf8')).toBe(
+ 'built\n',
+ );
+ expect(await readFile(join(appPath, 'released.txt'), 'utf8')).toBe(
+ 'build-id',
+ );
+ expect(
+ await readFile(join(appPath, '.twenty', 'base.json'), 'utf8'),
+ ).toBe('existing base');
+ },
+ );
+
+ it('shows every deletion, the selected target and the plan limitation', async () => {
+ const { stdout, exitCode } = await run();
+
+ expect(exitCode).toBe(0);
+ for (const text of [
+ 'Plan for Plan App',
+ server.url,
+ 'Twenty will perform the following actions:',
+ ' # logicFunction "sendWelcome" will be created',
+ ' + name = "sendWelcome"',
+ ' # fieldMetadata "name" will be updated in-place',
+ ' ~ label = "Name" -> "Full name"',
+ ' # objectMetadata "company" will be destroyed',
+ ' # view "Old view" will be destroyed',
+ 'Plan: 1 to add, 1 to change, 2 to destroy.',
+ '--no-delete',
+ 'Warning: 1 destructive change(s) will permanently delete data.',
+ ' - objectMetadata "company": drops the table and all its rows',
+ 'Nothing was registered',
+ 'different actions',
+ ]) {
+ expect(stdout).toContain(text);
+ }
+ expect(stdout).not.toContain('project output');
+ });
+
+ it('reports an empty plan as a success', async () => {
+ state.response = planResponse([]);
+ const { stdout, exitCode } = await run();
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toContain('No changes.');
+ expect(stdout).toContain('Plan for Plan App');
+ });
+
+ it('truncates long values in human output but keeps them whole in JSON', async () => {
+ const name = 'very-long-name-'.repeat(1000);
+ const action = {
+ type: 'delete',
+ metadataName: 'view',
+ universalIdentifier: 'long-view',
+ flatEntity: { name },
+ };
+
+ state.response = planResponse([action, ...ACTIONS]);
+ const human = await run();
+ const { envelope, exitCode } = await runJson();
+
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout.length).toBeLessThan(2500);
+ expect(human.stdout).toContain(`${JSON.stringify(name).slice(0, 79)}…`);
+ expect(human.stdout).toContain('Old view');
+ expect(human.stdout).toContain('3 to destroy');
+ expect(exitCode).toBe(0);
+ expect(envelope.data.actions[0].flatEntity.name).toBe(name);
+ });
+
+ it('shows secret application variables as secret and redacts other values', async () => {
+ state.response = planResponse([
+ {
+ type: 'create',
+ metadataName: 'applicationVariable',
+ flatEntity: {
+ key: 'API_TOKEN',
+ value: 'created-secret',
+ isSecret: true,
+ },
+ },
+ {
+ type: 'create',
+ metadataName: 'applicationVariable',
+ flatEntity: { key: 'REGION', value: 'eu', isSecret: false },
+ },
+ {
+ type: 'update',
+ metadataName: 'applicationVariable',
+ universalIdentifier: 'variable-id',
+ flatEntity: { key: 'API_TOKEN', isSecret: true },
+ diff: { value: { before: 'old-secret', after: 'new-secret' } },
+ },
+ ]);
+ const { stdout, exitCode } = await run();
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toContain(' + value = (secret)');
+ expect(stdout).toContain(' + value = "(redacted)"');
+ expect(stdout).toContain(' ~ value = (secret) -> (secret)');
+ for (const value of [
+ 'created-secret',
+ '"eu"',
+ 'old-secret',
+ 'new-secret',
+ ]) {
+ expect(stdout).not.toContain(value);
+ }
+ });
+
+ it.each([undefined, 'syncApplication'])(
+ 'refuses an unregistered app without creating it when the error path is %s',
+ async (path) => {
+ state.response = graphqlError('NOT_FOUND', 'APPLICATION_NOT_FOUND', path);
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'PLAN_UNAVAILABLE',
+ hint: expect.stringContaining('twenty app apply --create'),
+ details: { plan: true, applicationUniversalIdentifier: 'app-id' },
+ });
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0].body).not.toMatch(
+ /createApplication|createDevelopment|FileUpload/,
+ );
+ expect(await readFile(join(appPath, 'released.txt'), 'utf8')).toBe(
+ 'build-id',
+ );
+ },
+ );
+
+ it.each([
+ ['FORBIDDEN', undefined, 'syncApplication', 'PERMISSION_DENIED', 3],
+ ['UNAUTHENTICATED', undefined, 'syncApplication', 'AUTH_REQUIRED', 3],
+ ['NOT_FOUND', 'FIELD_NOT_FOUND', 'syncApplication', 'GRAPHQL_ERROR', 1],
+ ['NOT_FOUND', undefined, 'syncApplication', 'GRAPHQL_ERROR', 1],
+ ['NOT_FOUND', 'APPLICATION_NOT_FOUND', 'anotherField', 'GRAPHQL_ERROR', 1],
+ [
+ 'BAD_USER_INPUT',
+ 'SERVER_VERSION_INCOMPATIBLE',
+ 'syncApplication',
+ 'GRAPHQL_ERROR',
+ 1,
+ ],
+ ] as const)(
+ 'preserves the server refusal %s/%s at %s',
+ async (code, subCode, path, expectedCode, expectedExitCode) => {
+ state.response = graphqlError(String(code), subCode, path);
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(expectedExitCode);
+ expect(envelope.error.code).toBe(expectedCode);
+ expect(server.requests).toHaveLength(1);
+ },
+ );
+
+ it.each([
+ null,
+ [],
+ planResponse(null),
+ planResponse(ACTIONS, 'another-app'),
+ planResponse([{ type: 'delete', metadataName: 'objectMetadata' }]),
+ planResponse([{ type: 'unknown', metadataName: 'fieldMetadata' }]),
+ planResponse([
+ {
+ type: 'update',
+ metadataName: 'fieldMetadata',
+ universalIdentifier: 'id',
+ diff: { label: 'invalid' },
+ },
+ ]),
+ ])('rejects malformed preview %j', async (response) => {
+ state.response = response;
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+ });
+
+ it('fails instead of truncating a plan over the action limit', async () => {
+ state.response = planResponse(
+ Array.from({ length: 10001 }, () => ACTIONS[0]),
+ );
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('RESPONSE_LIMIT_EXCEEDED');
+ });
+
+ it('accepts a diff whose undefined side was omitted by JSON serialization', async () => {
+ const action = {
+ type: 'update',
+ metadataName: 'fieldMetadata',
+ universalIdentifier: 'field-id',
+ diff: { description: { after: 'New description' } },
+ };
+
+ state.response = planResponse([action]);
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.actions).toEqual([action]);
+ });
+
+ it('does not expose an unvalidated partial plan on GraphQL failure', async () => {
+ state.response = {
+ ...graphqlError('METADATA_VALIDATION_FAILED'),
+ data: {
+ syncApplication: {
+ actions: [
+ { metadataName: 'applicationVariable', value: 'SECRET_PARTIAL' },
+ ],
+ },
+ },
+ };
+ const { envelope, stdout, stderr, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'GRAPHQL_ERROR',
+ details: { data: null },
+ });
+ expect(stdout + stderr).not.toContain('SECRET_PARTIAL');
+ });
+
+ it('does not interpret an endpoint 404 as a missing app registration', async () => {
+ state.status = 404;
+ state.response = { message: 'Endpoint missing' };
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(4);
+ expect(envelope.error.code).toBe('NOT_FOUND');
+ expect(server.requests).toHaveLength(1);
+ });
+
+ it('rejects an unsupported SDK before contacting the workspace', async () => {
+ await writeTestSourceSdk({ appPath, hasSourceExports: false });
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('SDK_SOURCE_UNSUPPORTED');
+ expect(server.requests).toHaveLength(0);
+ await expect(readFile(join(appPath, 'builds.txt'))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ });
+
+ it.each([true, false, undefined])(
+ 'redacts variable values with isSecret %s, including previous values',
+ async (isSecret) => {
+ state.response = planResponse([
+ {
+ type: 'update',
+ metadataName: 'applicationVariable',
+ universalIdentifier: 'variable-id',
+ flatEntity: { name: 'API_TOKEN', value: 'SECRET_AFTER', isSecret },
+ diff: {
+ value: { before: 'SECRET_BEFORE', after: 'SECRET_AFTER' },
+ isSecret: { before: true, after: isSecret ?? null },
+ },
+ },
+ ]);
+ const { stdout, stderr, envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(0);
+ expect(stdout + stderr).not.toContain('SECRET_');
+ expect(envelope.data.actions[0]).toMatchObject({
+ flatEntity: { value: '(redacted)' },
+ diff: { value: { before: '(redacted)', after: '(redacted)' } },
+ });
+ },
+ );
+
+ it.each([
+ { manifestFormat: 'future-format' },
+ { manifest: { application: { universalIdentifier: 'other-app' } } },
+ ])(
+ 'rejects an incompatible build %j before any request',
+ async (overrides) => {
+ await writeBuild(overrides);
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('TOOLING_UNSUPPORTED');
+ expect(server.requests).toHaveLength(0);
+ },
+ );
+
+ it('advertises the read-only preview and its permission in the catalog', async () => {
+ const { stdout } = await runCliForTest(['commands', '--json']);
+
+ expect(parseSingleJsonLine(stdout).data.commands).toContainEqual(
+ expect.objectContaining({
+ name: 'app plan',
+ writes: false,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS'],
+ flags: expect.arrayContaining(['--no-delete']),
+ }),
+ );
+ expect(server.requests).toHaveLength(0);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts
new file mode 100644
index 00000000000..2d91b587f5b
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts
@@ -0,0 +1,339 @@
+import {
+ access,
+ appendFile,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ stat,
+ writeFile,
+} from 'node:fs/promises';
+import { MetadataWritability } from 'twenty-shared/types';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import {
+ createSourceTestApp,
+ sourceApplication,
+ SOURCE_TEST_APPLICATION_ID,
+} from '@/app/source/__tests__/utils/create-source-test-app';
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => launch,
+}));
+const OBJECT_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const WORKSPACE_ID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+const BASE_PATH = '.twenty/cli/pull-base.json';
+const createExport = () => ({
+ application: {
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ displayName: 'Source app',
+ sourceType: 'LOCAL',
+ },
+ manifest: {
+ application: {
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ displayName: 'Source app',
+ },
+ objects: [
+ {
+ universalIdentifier: OBJECT_ID,
+ nameSingular: 'pet',
+ namePlural: 'pets',
+ labelSingular: 'Pet',
+ labelPlural: 'Pets',
+ fields: [],
+ },
+ ],
+ fields: [],
+ },
+ coverage: [] as {
+ metadataName: string;
+ universalIdentifier: string;
+ status: string;
+ reason: string | null;
+ }[],
+ files: [] as { folder: string; path: string; content: string }[],
+});
+let exported = createExport();
+let forbidden = false;
+const server = await startTestServer((request, response) => {
+ if (request.body.includes('currentWorkspace')) {
+ return sendJson(response, 200, {
+ data: { currentWorkspace: { id: WORKSPACE_ID } },
+ });
+ }
+ if (forbidden) {
+ return sendJson(response, 403, { message: 'Forbidden' });
+ }
+ return sendJson(response, 200, { data: { exportApplication: exported } });
+});
+
+describe('app pull command with the packaged worker', () => {
+ let appPath: string;
+ let workerPath: string;
+ let sdkPath: string;
+ const run = (...args: string[]) =>
+ runCliForTest(['app', 'pull', '--path', appPath, ...args]);
+ const runJson = async (...args: string[]) => {
+ const result = await run(...args, '--json');
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+ beforeAll(async () => {
+ workerPath = await mkdtemp(join(tmpdir(), 'twenty-pull-worker-'));
+ launch.modulePath = join(workerPath, 'app-worker.cjs');
+ await buildTestAppWorker(workerPath);
+ });
+ afterAll(async () => {
+ await server.close();
+ await rm(workerPath, { recursive: true, force: true });
+ });
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-pull-'));
+ sdkPath = await createSourceTestApp(appPath);
+ await writeFile(join(appPath, 'app.ts'), sourceApplication());
+ exported = createExport();
+ forbidden = false;
+ server.requests.length = 0;
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'must-not-reach-source');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('CI', 'true');
+ });
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('pulls without an SDK build entry or compiler, preserves pins and emits one JSON result', async () => {
+ await writeFile(
+ join(appPath, 'app.ts'),
+ sourceApplication(
+ "if (process.env.TWENTY_API_KEY) throw new Error('credential leaked'); console.log('project noise');",
+ ),
+ );
+ await writeFile(join(appPath, 'yarn.lock'), 'keep-this-lock');
+ const packageJson = await readFile(join(appPath, 'package.json'), 'utf8');
+ const result = await runJson();
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ expect(result.envelope.data).toMatchObject({
+ pulled: true,
+ base: { status: 'missing' },
+ application: { universalIdentifier: SOURCE_TEST_APPLICATION_ID },
+ });
+ expect(result.envelope.data.diagnostics).toContainEqual(
+ expect.objectContaining({
+ code: 'PROJECT_OUTPUT',
+ message: expect.stringContaining('project noise'),
+ }),
+ );
+ expect(
+ result.envelope.data.writes.every(
+ (write: Record<string, unknown>) =>
+ !('content' in write) && !('requiredSdkExports' in write),
+ ),
+ ).toBe(true);
+ expect(
+ await readFile(join(appPath, 'src/objects/pet.object.ts'), 'utf8'),
+ ).toContain('defineObject');
+ expect(
+ JSON.parse(await readFile(join(appPath, BASE_PATH), 'utf8')),
+ ).toMatchObject({
+ target: { apiUrl: server.url, workspaceId: WORKSPACE_ID },
+ });
+ expect((await stat(join(appPath, BASE_PATH))).mode & 0o777).toBe(0o600);
+ expect(await readFile(join(appPath, 'package.json'), 'utf8')).toBe(
+ packageJson,
+ );
+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(
+ 'keep-this-lock',
+ );
+ expect(
+ server.requests.every((request) => !request.body.includes('mutation')),
+ ).toBe(true);
+ expect((await runJson()).envelope.data.writes).toEqual([]);
+ });
+
+ it('refuses incompatible writer exports before any destination changes', async () => {
+ await appendFile(
+ join(sdkPath, 'define.cjs'),
+ '\ndelete exports.defineObject;',
+ );
+ const original = await readFile(join(appPath, 'app.ts'), 'utf8');
+ const result = await runJson();
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ details: { outcome: 'unchanged', missingNames: ['defineObject'] },
+ });
+ expect(await readFile(join(appPath, 'app.ts'), 'utf8')).toBe(original);
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'app.ts',
+ 'node_modules',
+ 'package.json',
+ ]);
+ });
+
+ it('preserves the source recovery hint instead of suggesting an unrelated SDK upgrade', async () => {
+ await writeFile(
+ join(appPath, 'invalid.object.ts'),
+ `const defineObject = (config: unknown) => config;
+export default defineObject({ nameSingular: 'invalid' });`,
+ );
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error).toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ hint: 'Use the SDK define functions, rename local helpers with the same names, or install a compatible twenty-sdk version.',
+ details: { outcome: 'unchanged' },
+ });
+ expect(await readdir(appPath)).toContain('invalid.object.ts');
+ expect(await readdir(appPath)).not.toContain('.twenty');
+ });
+
+ it('checks enum imports actually used by generated files', async () => {
+ const state = JSON.parse(JSON.stringify(exported));
+ state.manifest.objects[0].writability = MetadataWritability.APPLICATION;
+ exported = state;
+ const result = await runJson();
+ expect(result.envelope.error).toMatchObject({
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ details: { missingNames: ['MetadataWritability'] },
+ });
+ });
+
+ it('requires an explicit UUID in a project without an app definition', async () => {
+ await rm(join(appPath, 'app.ts'));
+ expect((await runJson()).envelope.error.code).toBe('INVALID_INPUT');
+ expect(server.requests).toHaveLength(0);
+ expect(
+ (
+ await runJson(
+ '--universal-identifier',
+ SOURCE_TEST_APPLICATION_ID.toUpperCase(),
+ )
+ ).exitCode,
+ ).toBe(0);
+ });
+
+ it('rejects a different app before requesting the export', async () => {
+ expect(
+ (await runJson('--universal-identifier', OBJECT_ID)).envelope.error.code,
+ ).toBe('INVALID_INPUT');
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it('leaves local files untouched when server authorization fails', async () => {
+ forbidden = true;
+ const original = await readFile(join(appPath, 'app.ts'), 'utf8');
+ expect((await runJson()).exitCode).toBe(3);
+ expect(await readFile(join(appPath, 'app.ts'), 'utf8')).toBe(original);
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'app.ts',
+ 'node_modules',
+ 'package.json',
+ ]);
+ });
+
+ it('rejects exported source and dependency files before writes', async () => {
+ exported.files.push({ folder: '.', path: 'package.json', content: '{}' });
+ expect((await runJson()).envelope.error.code).toBe('TOOLING_UNSUPPORTED');
+ expect((await readdir(appPath)).sort()).toEqual([
+ 'app.ts',
+ 'node_modules',
+ 'package.json',
+ ]);
+ });
+
+ it('reports coverage gaps in human and machine output, without a prompt', async () => {
+ exported.coverage.push({
+ metadataName: 'futureEntity',
+ universalIdentifier: OBJECT_ID,
+ status: 'FUTURE_STATUS',
+ reason: 'Not supported yet',
+ });
+ const result = await runJson();
+ expect(result.exitCode).toBe(0);
+ expect(result.envelope.data.coverage).toEqual(exported.coverage);
+ const human = await run('--verbose');
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout).toContain('FUTURE_STATUS');
+ });
+
+ it('contains a process exit during reconciliation and reports an unknown outcome', async () => {
+ await mkdir(join(appPath, 'src'));
+ await writeFile(
+ join(appPath, 'src/broken.object.ts'),
+ "import { defineObject } from 'twenty-sdk/define'; process.exit(17); export default defineObject({});",
+ );
+ const result = await runJson();
+ expect(result.envelope.error).toMatchObject({
+ code: 'WORKER_FAILED',
+ details: { outcome: 'unknown', exitCode: 17 },
+ });
+ expect(result.envelope.error.hint).toContain('pull-backup-');
+ });
+ it('reports unknown after forced cancellation mid-commit and retains recoverable backups', async () => {
+ const startedPath = join(appPath, 'commit-started');
+ const original = sourceApplication(`
+ import { createRequire } from 'node:module';
+ const filesystem = createRequire(process.cwd() + '/package.json')('node:fs/promises');
+ const originalCopy = filesystem.cp;
+ filesystem.cp = async (...args) => {
+ await originalCopy(...args);
+ if (args[0].includes('pull-staging-') && args[1] === ${JSON.stringify(join(appPath, 'app.ts'))}) {
+ await filesystem.writeFile(${JSON.stringify(startedPath)}, 'started');
+ await new Promise(() => {});
+ }
+ };
+ `);
+ await writeFile(join(appPath, 'app.ts'), original);
+ const pending = runJson();
+ try {
+ await vi.waitFor(() => access(startedPath), {
+ timeout: 10000,
+ interval: 20,
+ });
+ } finally {
+ process.emit('SIGINT');
+ }
+ const result = await pending;
+ expect(result.exitCode).toBe(130);
+ expect(result.envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ details: { outcome: 'unknown' },
+ });
+ expect(await readFile(join(appPath, 'app.ts'), 'utf8')).not.toBe(original);
+ await expect(access(join(appPath, BASE_PATH))).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ const backup = (await readdir(join(appPath, '.twenty/cli'))).find((name) =>
+ name.startsWith('pull-backup-'),
+ );
+ expect(backup).toBeDefined();
+ expect(
+ await readFile(
+ join(appPath, '.twenty/cli', backup ?? '', 'app.ts'),
+ 'utf8',
+ ),
+ ).toBe(original);
+ }, 15000);
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts
new file mode 100644
index 00000000000..e7a7055f9da
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts
@@ -0,0 +1,393 @@
+import { existsSync } from 'node:fs';
+import {
+ cp,
+ mkdir,
+ mkdtemp,
+ readFile,
+ readdir,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { basename, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';
+import { isArray } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+import { installTestClientSdk } from '@/app/__tests__/utils/install-test-client-sdk';
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+
+const buildMode = vi.hoisted(() => ({
+ launch: { modulePath: '', execArgv: [] as string[] },
+}));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => buildMode.launch,
+}));
+
+const REPOSITORY_ROOT = fileURLToPath(
+ new URL('../../../../../../', import.meta.url),
+);
+
+const APP_PATH = join(
+ REPOSITORY_ROOT,
+ 'packages/twenty-apps/fixtures/minimal-app',
+);
+
+const snapshotsPath = (appPath: string) =>
+ join(appPath, '.twenty', 'cli', 'snapshots');
+
+const listSnapshots = async () =>
+ existsSync(snapshotsPath(APP_PATH))
+ ? await readdir(snapshotsPath(APP_PATH))
+ : [];
+
+const readManifestIdentifier = (variables: Record<string, unknown>) => {
+ const manifest = isPlainObject(variables.manifest)
+ ? variables.manifest
+ : undefined;
+
+ return isPlainObject(manifest?.application)
+ ? manifest.application.universalIdentifier
+ : undefined;
+};
+
+let syncedManifest: unknown;
+
+const server = await startTestServer((request, response) => {
+ if (request.method === 'PUT') {
+ return sendJson(response, 200, {});
+ }
+
+ const { query, arguments: variables } = readGraphqlRequest(request);
+
+ if (query.includes('syncApplication')) {
+ if (!(variables.dryRun === true)) {
+ syncedManifest = variables.manifest;
+ }
+ return sendJson(response, 200, {
+ data: {
+ syncApplication: {
+ applicationUniversalIdentifier: readManifestIdentifier(variables),
+ actions: [],
+ },
+ },
+ });
+ }
+
+ if (query.includes('findOneApplication')) {
+ return sendJson(response, 200, {
+ data: {
+ findOneApplication: {
+ name: 'Root App',
+ universalIdentifier: variables.universalIdentifier,
+ canBeUninstalled: true,
+ },
+ },
+ });
+ }
+
+ if (query.includes('uninstallApplication')) {
+ return sendJson(response, 200, { data: { uninstallApplication: true } });
+ }
+
+ if (query.includes('createDevelopmentApplication')) {
+ return sendJson(response, 200, {
+ data: {
+ createDevelopmentApplication: {
+ id: 'application-id',
+ universalIdentifier: variables.universalIdentifier,
+ },
+ },
+ });
+ }
+
+ if (query.includes('createApplicationFileUploads')) {
+ const files = isArray(variables.files) ? variables.files : [];
+
+ return sendJson(response, 200, {
+ data: {
+ createApplicationFileUploads: {
+ targets: files.filter(isPlainObject).map((file, index) => ({
+ fileId: `file-${index}`,
+ filePath: file.filePath,
+ uploadUrl: `${server.url}/upload/file-${index}`,
+ contentType: 'application/octet-stream',
+ })),
+ errors: [],
+ },
+ },
+ });
+ }
+
+ if (query.includes('completeApplicationFileUploads')) {
+ return sendJson(response, 200, {
+ data: { completeApplicationFileUploads: { errors: [] } },
+ });
+ }
+
+ if (query.includes('currentWorkspace')) {
+ return sendJson(response, 200, {
+ data: {
+ currentWorkspace: { id: '48eb6ca1-dbd6-492e-8b53-5785a266c454' },
+ },
+ });
+ }
+
+ if (query.includes('exportApplication')) {
+ return sendJson(response, 200, {
+ data: {
+ exportApplication: {
+ application: {
+ ...(isPlainObject(syncedManifest) &&
+ isPlainObject(syncedManifest.application)
+ ? syncedManifest.application
+ : {}),
+ sourceType: 'LOCAL',
+ },
+ manifest: syncedManifest,
+ coverage: [],
+ files: [],
+ },
+ },
+ });
+ }
+
+ if (query.includes('applicationCoreGraphqlSchema')) {
+ return sendJson(response, 200, {
+ data: {
+ applicationCoreGraphqlSchema: 'type Query { demoGreeting: String }',
+ },
+ });
+ }
+
+ return sendJson(response, 400, { errors: [{ message: 'Unexpected' }] });
+});
+
+const runJson = async (args: string[]) => {
+ const result = await runCliForTest([...args, '--json']);
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+
+let workerDirectory: string;
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-real-apply-worker-'));
+ await buildTestAppWorker(workerDirectory);
+ buildMode.launch.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60000);
+
+afterAll(async () => {
+ await server.close();
+ await rm(workerDirectory, { recursive: true, force: true });
+});
+
+describe('app commands with CLI snapshots', () => {
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'real-sdk-test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('CI', '');
+ server.requests.length = 0;
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+
+ it('builds a real app', async () => {
+ const snapshotsBefore = await listSnapshots();
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'build',
+ '--path',
+ APP_PATH,
+ ]);
+
+ expect(exitCode, JSON.stringify(envelope)).toBe(0);
+ expect(envelope.data.sdk).not.toHaveProperty('protocolVersion');
+ expect(envelope.data.files).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ role: 'built-logic-function' }),
+ ]),
+ );
+ expect(await listSnapshots()).toEqual(snapshotsBefore);
+ }, 120_000);
+
+ it('produces the same artifacts when invoked outside the app root', async () => {
+ const originalDirectory = process.cwd();
+ const builds = [];
+
+ try {
+ for (const directory of [
+ APP_PATH,
+ dirname(APP_PATH),
+ join(APP_PATH, '.twenty'),
+ ]) {
+ process.chdir(directory);
+ const result = await runJson(['app', 'build', '--path', APP_PATH]);
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ builds.push(result.envelope.data);
+ }
+ } finally {
+ process.chdir(originalDirectory);
+ }
+
+ for (const build of builds.slice(1)) {
+ expect(build.contentHash).toBe(builds[0].contentHash);
+ expect(build.files).toEqual(builds[0].files);
+ expect(build.manifest).toEqual(builds[0].manifest);
+ }
+ }, 120_000);
+
+ it('builds, typechecks, previews, applies and uninstalls through the public pipeline', async () => {
+ const appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-real-apply-'));
+
+ try {
+ await cp(APP_PATH, appPath, {
+ recursive: true,
+ filter: (source) =>
+ !['node_modules', '.twenty'].includes(basename(source)),
+ });
+ await mkdir(join(appPath, 'node_modules'));
+ for (const name of [
+ 'twenty-sdk',
+ 'twenty-ui',
+ 'react',
+ 'react-dom',
+ 'typescript',
+ '@types',
+ ]) {
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules', name),
+ join(appPath, 'node_modules', name),
+ 'dir',
+ );
+ }
+ {
+ const sdkPath = join(appPath, 'node_modules', 'twenty-sdk');
+ const repositorySdkPath = join(REPOSITORY_ROOT, 'packages/twenty-sdk');
+ await rm(sdkPath);
+ await mkdir(sdkPath);
+ await cp(join(repositorySdkPath, 'dist'), join(sdkPath, 'dist'), {
+ recursive: true,
+ dereference: true,
+ });
+ await symlink(
+ join(REPOSITORY_ROOT, 'node_modules'),
+ join(sdkPath, 'node_modules'),
+ 'dir',
+ );
+ const sdkPackage = JSON.parse(
+ await readFile(join(repositorySdkPath, 'package.json'), 'utf8'),
+ );
+ delete sdkPackage.exports['./build'];
+ delete sdkPackage.exports['./build/descriptor.json'];
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify(sdkPackage),
+ );
+ }
+ const clientPath = join(appPath, 'node_modules', 'twenty-client-sdk');
+
+ await installTestClientSdk(clientPath);
+ await writeFile(
+ join(clientPath, 'dist', 'metadata.cjs'),
+ 'metadata client',
+ );
+ for (const command of ['build', 'typecheck', 'plan']) {
+ const result = await runJson(['app', command, '--path', appPath]);
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ expect(await readdir(snapshotsPath(appPath))).toEqual([]);
+ }
+ const { envelope, exitCode } = await runJson([
+ 'app',
+ 'apply',
+ '--path',
+ appPath,
+ ]);
+ const uploadTargets = server.requests.find(({ body, method }) =>
+ method === 'POST'
+ ? readGraphqlRequest({ body }).query.includes(
+ 'createApplicationFileUploads',
+ )
+ : false,
+ );
+ const puts = server.requests.filter(({ method }) => method === 'PUT');
+
+ expect(exitCode, JSON.stringify(envelope)).toBe(0);
+ expect(envelope.data.clientGeneration).toBe('generated');
+ expect(envelope.data.pullBase).toBe('recorded');
+ expect(
+ JSON.parse(
+ await readFile(join(appPath, '.twenty/cli/pull-base.json'), 'utf8'),
+ ).manifest,
+ ).toEqual(syncedManifest);
+ expect(envelope.data.completedPhases.slice(-3)).toEqual([
+ 'sync',
+ 'pullBase',
+ 'clientGeneration',
+ ]);
+ expect(envelope.data.upload.fileCount).toBeGreaterThan(0);
+ expect(puts).toHaveLength(envelope.data.upload.fileCount);
+ expect(puts.every(({ body }) => body.length > 0)).toBe(true);
+ expect(
+ isDefined(uploadTargets) && readGraphqlRequest(uploadTargets).arguments,
+ ).toMatchObject({
+ files: expect.arrayContaining([
+ expect.objectContaining({ fileFolder: 'BuiltLogicFunction' }),
+ ]),
+ });
+ expect(await readdir(snapshotsPath(appPath))).toEqual([]);
+ const uninstalled = await runJson([
+ 'app',
+ 'uninstall',
+ '--path',
+ appPath,
+ '--yes',
+ ]);
+ expect(uninstalled.exitCode, JSON.stringify(uninstalled.envelope)).toBe(
+ 0,
+ );
+ expect(uninstalled.envelope.data.completedPhases).toEqual([
+ 'build',
+ 'check',
+ 'uninstall',
+ ]);
+ expect(await readdir(snapshotsPath(appPath))).toEqual([]);
+ expect(
+ await readFile(
+ join(clientPath, 'dist', 'core/generated/schema.graphql'),
+ 'utf8',
+ ),
+ ).toContain('demoGreeting: String');
+ expect(
+ createRequire(import.meta.url)(join(clientPath, 'dist', 'core.cjs')),
+ ).toHaveProperty('CoreApiClient');
+ expect(
+ await readFile(join(clientPath, 'dist', 'metadata.cjs'), 'utf8'),
+ ).toBe('metadata client');
+ } finally {
+ await rm(appPath, { recursive: true, force: true });
+ }
+ }, 120_000);
+});
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts
new file mode 100644
index 00000000000..87d0b788d08
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts
@@ -0,0 +1,462 @@
+import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';
+import { writeTestSourceSdk } from '@/app/__tests__/utils/write-test-source-sdk';
+import { existsSync } from 'node:fs';
+import { rm, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { type ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ afterAll,
+ beforeAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import {
+ type RecordedRequest,
+ sendJson,
+ startTestServer,
+} from '@/__tests__/utils/start-test-server';
+
+const worker = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => worker,
+}));
+
+let workerDirectory: string;
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-command-worker-'));
+ await buildTestAppWorker(workerDirectory, { useToolingFixture: true });
+ worker.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60_000);
+
+afterAll(() => rm(workerDirectory, { recursive: true, force: true }));
+
+const APPLICATION = {
+ universalIdentifier: '0f3a1c52-7d6e-4b8a-9c21-5e4d3b2a1f00',
+ name: 'uninstall-app',
+ displayName: 'Uninstall App',
+};
+
+type ServerState = {
+ isInstalled: boolean;
+ canBeUninstalled: boolean;
+ uninstallError?: { code: string; subCode?: string };
+ uninstallResult: unknown;
+ isUninstallHeld: boolean;
+ heldUninstallResponse?: ServerResponse;
+};
+
+const state: ServerState = {
+ isInstalled: true,
+ canBeUninstalled: true,
+ uninstallResult: true,
+ isUninstallHeld: false,
+};
+
+const graphqlError = ({
+ code,
+ subCode,
+ field,
+}: {
+ code: string;
+ subCode?: string;
+ field?: string;
+}) => ({
+ data: null,
+ errors: [
+ {
+ message: 'The server refused the request.',
+ ...(isDefined(field) ? { path: [field] } : {}),
+ extensions: { code, subCode },
+ },
+ ],
+});
+
+const getOperation = (request: RecordedRequest) => {
+ const { query } = readGraphqlRequest(request);
+
+ if (query.includes('findOneApplication')) {
+ return 'check';
+ }
+
+ return query.includes('uninstallApplication') ? 'uninstall' : 'unknown';
+};
+
+const server = await startTestServer((request, response) => {
+ const operation = getOperation(request);
+ const { arguments: variables } = readGraphqlRequest(request);
+
+ if (operation === 'check') {
+ return sendJson(
+ response,
+ 200,
+ state.isInstalled
+ ? {
+ data: {
+ findOneApplication: {
+ name: APPLICATION.displayName,
+ universalIdentifier: isString(variables.universalIdentifier)
+ ? variables.universalIdentifier.toLowerCase()
+ : null,
+ canBeUninstalled: state.canBeUninstalled,
+ },
+ },
+ }
+ : graphqlError({
+ code: 'NOT_FOUND',
+ subCode: 'APPLICATION_NOT_FOUND',
+ }),
+ );
+ }
+
+ if (operation === 'uninstall') {
+ if (isDefined(state.uninstallError)) {
+ return sendJson(
+ response,
+ 200,
+ graphqlError({
+ ...state.uninstallError,
+ field: 'uninstallApplication',
+ }),
+ );
+ }
+
+ if (state.isUninstallHeld) {
+ state.heldUninstallResponse = response;
+
+ return;
+ }
+
+ return sendJson(response, 200, {
+ data: { uninstallApplication: state.uninstallResult },
+ });
+ }
+
+ return sendJson(response, 400, { errors: [{ message: 'Unexpected' }] });
+});
+
+describe('app uninstall', () => {
+ let appPath: string;
+
+ const run = (...args: string[]) =>
+ runCliForTest(['app', 'uninstall', '--path', appPath, ...args]);
+ const runJson = async (...args: string[]) => {
+ const result = await run(...args, '--json');
+
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+ };
+ const operations = () => server.requests.map(getOperation);
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-uninstall-'));
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'uninstall-app',
+ devDependencies: { 'twenty-sdk': '9.9.9' },
+ }),
+ );
+ await writeTestSourceSdk({ appPath });
+ await writeFile(
+ join(appPath, 'test-tooling.cjs'),
+ `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ exports.buildSourceSnapshot = async () => {
+ fs.writeFileSync(path.join(__dirname, 'built.txt'), 'built');
+ return {
+ success: true,
+ data: {
+ buildId: 'build-id',
+ contentHash: 'a'.repeat(64),
+ application: ${JSON.stringify(APPLICATION)},
+ manifestFormat: 'twenty-application',
+ manifest: { application: ${JSON.stringify(APPLICATION)} },
+ files: [],
+ },
+ diagnostics: [],
+ };
+ };
+ exports.releaseSourceSnapshot = async ({ buildId }) => {
+ fs.writeFileSync(path.join(__dirname, 'released.txt'), buildId);
+ return { success: true, data: null, diagnostics: [] };
+ };
+ `,
+ );
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'uninstall-test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('CI', '');
+ Object.assign(state, {
+ isInstalled: true,
+ canBeUninstalled: true,
+ uninstallError: undefined,
+ uninstallResult: true,
+ isUninstallHeld: false,
+ heldUninstallResponse: undefined,
+ });
+ server.requests.length = 0;
+ });
+
+ afterEach(() => {
+ state.heldUninstallResponse?.end();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ afterAll(() => server.close());
+
+ it('finds the app from its build, checks it, then uninstalls it', async () => {
+ const { envelope, exitCode } = await runJson('--yes');
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toEqual({
+ application: {
+ universalIdentifier: APPLICATION.universalIdentifier,
+ name: APPLICATION.displayName,
+ },
+ uninstalled: true,
+ completedPhases: ['build', 'check', 'uninstall'],
+ });
+ expect(operations()).toEqual(['check', 'uninstall']);
+ expect(readGraphqlRequest(server.requests[1]).arguments).toEqual({
+ universalIdentifier: APPLICATION.universalIdentifier,
+ });
+ expect(await readFile(join(appPath, 'released.txt'), 'utf8')).toBe(
+ 'build-id',
+ );
+ });
+
+ it('uninstalls by universal identifier without building the project', async () => {
+ const { envelope, exitCode } = await runJson(
+ '--universal-identifier',
+ APPLICATION.universalIdentifier,
+ '--yes',
+ );
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.completedPhases).toEqual(['check', 'uninstall']);
+ expect(existsSync(join(appPath, 'built.txt'))).toBe(false);
+ });
+
+ it('sends the canonical form of an uppercase universal identifier', async () => {
+ const { envelope, exitCode } = await runJson(
+ '--universal-identifier',
+ APPLICATION.universalIdentifier.toUpperCase(),
+ '--yes',
+ );
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.application.universalIdentifier).toBe(
+ APPLICATION.universalIdentifier,
+ );
+ expect(
+ server.requests.map(
+ (request) => readGraphqlRequest(request).arguments.universalIdentifier,
+ ),
+ ).toEqual([
+ APPLICATION.universalIdentifier,
+ APPLICATION.universalIdentifier,
+ ]);
+ });
+
+ it('rejects a universal identifier that is not a UUID', async () => {
+ const { envelope, exitCode } = await runJson(
+ '--universal-identifier',
+ 'not-a-uuid',
+ '--yes',
+ );
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('INVALID_INPUT');
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it('reports an app that is not installed without trying to uninstall it', async () => {
+ state.isInstalled = false;
+
+ const { envelope, exitCode } = await runJson('--yes');
+
+ expect(exitCode).toBe(4);
+ expect(envelope.error).toMatchObject({
+ code: 'APP_NOT_INSTALLED',
+ hint: 'Nothing was uninstalled. Check the target workspace and the universal identifier.',
+ details: {
+ phase: 'check',
+ outcome: 'not-started',
+ completedPhases: ['build'],
+ },
+ });
+ expect(operations()).toEqual(['check']);
+ });
+
+ it('refuses an app the workspace does not allow to uninstall', async () => {
+ state.canBeUninstalled = false;
+
+ const { envelope, exitCode } = await runJson('--yes');
+
+ expect(exitCode).toBe(6);
+ expect(envelope.error).toMatchObject({
+ code: 'APP_NOT_UNINSTALLABLE',
+ details: { phase: 'check', outcome: 'not-started' },
+ });
+ expect(operations()).toEqual(['check']);
+ });
+
+ it('requires --yes in automation', async () => {
+ const { envelope, exitCode } = await runJson();
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error).toMatchObject({
+ code: 'CONFIRMATION_REQUIRED',
+ hint: expect.stringContaining('--yes'),
+ details: {
+ phase: 'confirmation',
+ outcome: 'not-started',
+ completedPhases: ['build', 'check'],
+ },
+ });
+ expect(operations()).toEqual(['check']);
+ });
+
+ it.each([
+ ['y\n', 0, 'uninstall'],
+ ['n\n', 2, 'check'],
+ ])(
+ 'asks before uninstalling in an interactive terminal (answer %j)',
+ async (answer, expectedExitCode, lastOperation) => {
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ content: answer, isTerminal: true }),
+ );
+
+ const { exitCode, stderr } = await run();
+
+ expect(exitCode).toBe(expectedExitCode);
+ expect(stderr).toContain('permanently deleted');
+ expect(operations().at(-1)).toBe(lastOperation);
+ },
+ );
+
+ it.each([
+ [
+ 'an internal error',
+ { code: 'INTERNAL_SERVER_ERROR' },
+ 'GRAPHQL_ERROR',
+ 1,
+ 'unknown',
+ ],
+ ['a refusal', { code: 'FORBIDDEN' }, 'PERMISSION_DENIED', 3, 'not-started'],
+ [
+ 'a missing app',
+ { code: 'NOT_FOUND', subCode: 'APPLICATION_NOT_FOUND' },
+ 'APP_NOT_INSTALLED',
+ 4,
+ 'unknown',
+ ],
+ ])(
+ 'reports the uninstall outcome for %s',
+ async (_description, uninstallError, code, exitCode, outcome) => {
+ state.uninstallError = uninstallError;
+
+ const result = await runJson('--yes');
+
+ expect(result.exitCode).toBe(exitCode);
+ expect(result.envelope.error).toMatchObject({
+ code,
+ details: {
+ phase: 'uninstall',
+ outcome,
+ completedPhases: ['build', 'check'],
+ },
+ });
+ },
+ );
+
+ it('keeps the partial-run hint when the app disappears during the uninstall', async () => {
+ state.uninstallError = {
+ code: 'NOT_FOUND',
+ subCode: 'APPLICATION_NOT_FOUND',
+ };
+
+ const { envelope, exitCode } = await runJson('--yes');
+
+ expect(exitCode).toBe(4);
+ expect(envelope.error).toMatchObject({
+ code: 'APP_NOT_INSTALLED',
+ hint: expect.stringContaining('The uninstall may have partly run.'),
+ details: { phase: 'uninstall', outcome: 'unknown' },
+ });
+ });
+
+ it('does not report success when the server does not confirm the uninstall', async () => {
+ state.uninstallResult = false;
+
+ const { envelope, exitCode, stdout } = await runJson('--yes');
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({
+ code: 'INVALID_RESPONSE',
+ details: { phase: 'uninstall', outcome: 'unknown' },
+ });
+ expect(stdout).not.toContain('"uninstalled":true');
+ });
+
+ it('exits with 130 and an unknown outcome when cancelled during the uninstall', async () => {
+ state.isUninstallHeld = true;
+
+ const pending = runJson('--yes');
+
+ await vi.waitFor(() => expect(operations()).toContain('uninstall'), {
+ timeout: 10_000,
+ });
+ process.emit('SIGINT');
+
+ const { envelope, exitCode } = await pending;
+
+ expect(exitCode).toBe(130);
+ expect(envelope.error).toMatchObject({
+ code: 'CANCELLED',
+ details: { phase: 'uninstall', outcome: 'unknown' },
+ });
+ });
+
+ it('names the app and says its registration is kept', async () => {
+ const { stdout, exitCode } = await run('--yes');
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toContain(`Uninstalled Uninstall App from ${server.url}`);
+ expect(stdout).toContain('registration is kept');
+ });
+
+ it('lists the command as a write with its permission', async () => {
+ const { stdout } = await runCliForTest(['commands', '--json']);
+ const commands: unknown = parseSingleJsonLine(stdout).data.commands;
+
+ expect(commands).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: 'app uninstall',
+ writes: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS'],
+ }),
+ ]),
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts b/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts
new file mode 100644
index 00000000000..97c07d32dd4
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts
@@ -0,0 +1,78 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_ADD_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['app', 'add'],
+ description:
+ 'Add an object, field, logic function or front component to an app',
+ arguments: [
+ {
+ name: 'entity',
+ description:
+ 'object, field, logic-function or front-component (prompted when omitted)',
+ required: false,
+ },
+ ],
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--name <name>',
+ description: 'Definition name; also determines the generated filename',
+ },
+ { flags: '--name-plural <name>', description: 'Plural API name (object)' },
+ {
+ flags: '--label <label>',
+ description:
+ 'Display label (object or field; default: derived from name)',
+ },
+ {
+ flags: '--label-plural <label>',
+ description:
+ 'Plural display label (object; default: derived from plural name)',
+ },
+ {
+ flags: '--type <type>',
+ description:
+ 'Field type, for example TEXT, NUMBER or RELATION (default: TEXT)',
+ },
+ {
+ flags: '--object <uuid>',
+ description: 'Parent object universal identifier (field)',
+ },
+ { flags: '--description <text>', description: 'Field description' },
+ {
+ flags: '--target-object <uuid>',
+ description: 'Target object universal identifier (relation field)',
+ },
+ {
+ flags: '--target-field <uuid>',
+ description: 'Target field universal identifier (relation field)',
+ },
+ {
+ flags: '--relation-type <type>',
+ description:
+ 'ONE_TO_MANY or MANY_TO_ONE (relation field; default: ONE_TO_MANY)',
+ },
+ {
+ flags: '--on-delete <action>',
+ description:
+ 'CASCADE, RESTRICT, SET_NULL, NO_ACTION or None (relation field; default: CASCADE)',
+ },
+ ],
+ examples: [
+ 'twenty app add',
+ 'twenty app add object --name invoice --name-plural invoices --no-input',
+ 'twenty app add field --name amount --type NUMBER --object <object-universal-identifier> --json',
+ 'twenty app add logic-function --name send-invoice --no-input',
+ 'twenty app add front-component --name invoice-panel --no-input',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/app/add/run-app-add-command')).runAppAddCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts b/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts
new file mode 100644
index 00000000000..78f2446de69
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts
@@ -0,0 +1,66 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { prepareAppAddFile } from '@/app/add/prepare-app-add-file';
+import { writeAppAddFile } from '@/app/add/write-app-add-file';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { CliError } from '@/output/cli-error';
+import { formatSuccessLine } from '@/output/style';
+
+export const runAppAddCommand: CommandRun = async (context) => {
+ const { options, signal, output } = context;
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const identity = await readAppIdentity({ appPath: project.path, signal });
+
+ if (!isDefined(identity.application)) {
+ throw new CliError({
+ code: 'IDENTITY_READ_FAILED',
+ message: 'No application definition found in this app.',
+ hint: 'Start with twenty app init, or add a defineApplication definition.',
+ });
+ }
+
+ for (const diagnostic of identity.diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+
+ const file = await prepareAppAddFile(context);
+ const cleanupPath = await writeAppAddFile({
+ appPath: project.path,
+ file,
+ signal,
+ });
+
+ if (isDefined(cleanupPath)) {
+ output.warn({
+ code: 'APP_ADD_CLEANUP_FAILED',
+ message: `Created ${file.path}, but could not remove temporary directory ${cleanupPath}.`,
+ });
+ }
+
+ return {
+ data: {
+ app: project,
+ entity: file.entity,
+ name: file.name,
+ createdPaths: [file.path],
+ diagnostics: identity.diagnostics,
+ },
+ human: [
+ formatSuccessLine(`Created ${file.path}`),
+ ...(file.entity === 'object'
+ ? [
+ 'Add views, navigation and record-page layouts separately to expose the object in the UI.',
+ ]
+ : []),
+ '',
+ 'Review the definition, then run twenty app build.',
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/apply/app-apply.command-definition.ts b/packages/twenty-cli/src/commands/app/apply/app-apply.command-definition.ts
new file mode 100644
index 00000000000..b13d655ec78
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/apply/app-apply.command-definition.ts
@@ -0,0 +1,41 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_APPLY_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'apply'],
+ description:
+ 'Build the app, preview the changes, then upload and sync it to the workspace',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--no-delete',
+ description: 'Keep remote entities missing from the app source',
+ },
+ {
+ flags: '--create',
+ description:
+ 'Register the app and install it in the workspace if it has no registration yet',
+ },
+ {
+ flags: '--yes',
+ description:
+ 'Apply object and field deletions without asking; does not change which entities are deleted',
+ },
+ ],
+ examples: [
+ 'twenty app apply --remote dev',
+ 'twenty app apply --create --json',
+ 'twenty app apply --no-delete',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS', 'UPLOAD_FILE'],
+ load: async () =>
+ (await import('@/commands/app/apply/run-app-apply-command'))
+ .runAppApplyCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/apply/run-app-apply-command.ts b/packages/twenty-cli/src/commands/app/apply/run-app-apply-command.ts
new file mode 100644
index 00000000000..feca4c40257
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/apply/run-app-apply-command.ts
@@ -0,0 +1,167 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ type AppApplyResult,
+ applyAppBuild,
+} from '@/app/deployment/apply-app-build';
+import { createPostSyncFailure } from '@/app/deployment/create-post-sync-failure';
+import { formatApplySummary } from '@/app/deployment/format-apply-summary';
+import { generateAppClient } from '@/app/generate-app-client';
+import { getAppPlanSummary } from '@/app/deployment/get-app-plan-summary';
+import { getClientGenerationSkipReason } from '@/app/get-client-generation-skip-reason';
+import { collectSourceFingerprints } from '@/app/pull/collect-source-fingerprints';
+import { type PullBaseRecording, recordPullBase } from '@/app/record-pull-base';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { runAppBuild } from '@/app/run-app-operation';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { CliError } from '@/output/cli-error';
+
+export const runAppApplyCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const startedAt = performance.now();
+ const inferDeletionFromMissingEntities = context.options.delete !== false;
+ let applyResult: AppApplyResult | undefined;
+ const appProject = await resolveAppProject({
+ explicitPath: readStringOption(context.options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const sourceFingerprints = await collectSourceFingerprints(
+ appProject.path,
+ ).catch(() => undefined);
+
+ const {
+ project,
+ sdk,
+ data: build,
+ diagnostics,
+ } = await runAppBuild({
+ context,
+ useHeldBuild: async (heldBuild) => {
+ applyResult = await applyAppBuild({
+ build: heldBuild.data,
+ appPath: heldBuild.project.path,
+ context,
+ inferDeletionFromMissingEntities,
+ isCreationApproved: readBooleanOption(context.options, 'create'),
+ isDeletionApproved: readBooleanOption(context.options, 'yes'),
+ });
+ },
+ });
+
+ if (!isDefined(applyResult)) {
+ throw new CliError({
+ code: 'TOOLING_UNSUPPORTED',
+ message:
+ 'The app worker did not keep its build snapshot for upload, so nothing was applied.',
+ });
+ }
+
+ const summary = isDefined(applyResult.appliedActions)
+ ? getAppPlanSummary(applyResult.appliedActions)
+ : undefined;
+
+ if (!isDefined(summary)) {
+ context.output.warn({
+ code: 'SYNC_REPORT_UNAVAILABLE',
+ message:
+ 'The sync succeeded, but the server did not return a readable list of its changes.',
+ });
+ }
+
+ let pullBase: PullBaseRecording;
+
+ try {
+ pullBase = await recordPullBase({
+ appPath: project.path,
+ universalIdentifier: applyResult.acknowledgedUniversalIdentifier,
+ sourceFingerprints,
+ context,
+ });
+ if (pullBase === 'recorded') {
+ applyResult.completedPhases.push('pullBase');
+ }
+ } catch (error) {
+ throw createPostSyncFailure({
+ error,
+ phase: 'pullBase',
+ applicationName: build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ completedPhases: applyResult.completedPhases,
+ signal: context.signal,
+ });
+ }
+
+ const clientGenerationSkipReason = await getClientGenerationSkipReason({
+ appPath: project.path,
+ });
+ let clientGeneration: 'generated' | 'skipped' = 'skipped';
+
+ if (isDefined(clientGenerationSkipReason)) {
+ context.output.warn({
+ code: 'CLIENT_NOT_GENERATED',
+ message: `The app's typed API client was not regenerated: ${clientGenerationSkipReason}`,
+ });
+ } else {
+ try {
+ diagnostics.push(
+ ...(await generateAppClient({
+ appPath: project.path,
+ applicationUniversalIdentifier:
+ applyResult.acknowledgedUniversalIdentifier,
+ sdk,
+ context,
+ })),
+ );
+ clientGeneration = 'generated';
+ applyResult.completedPhases.push('clientGeneration');
+ } catch (error) {
+ throw createPostSyncFailure({
+ error,
+ phase: 'clientGeneration',
+ applicationName: build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ completedPhases: applyResult.completedPhases,
+ signal: context.signal,
+ });
+ }
+ }
+
+ const durationMilliseconds = Math.round(performance.now() - startedAt);
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ sdk: { version: sdk.version },
+ application: build.application,
+ contentHash: build.contentHash,
+ inferDeletionFromMissingEntities,
+ registrationCreated: applyResult.isRegistrationCreated,
+ completedPhases: applyResult.completedPhases,
+ actions: applyResult.appliedActions ?? null,
+ summary: summary ?? null,
+ upload: {
+ fileCount: applyResult.upload.fileCount,
+ byteCount: applyResult.upload.byteCount,
+ },
+ clientGeneration,
+ pullBase,
+ diagnostics,
+ durationMilliseconds,
+ },
+ human: formatApplySummary({
+ applicationName: build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ summary,
+ upload: applyResult.upload,
+ isRegistrationCreated: applyResult.isRegistrationCreated,
+ clientGeneration,
+ durationMilliseconds,
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/build/app-build.command-definition.ts b/packages/twenty-cli/src/commands/app/build/app-build.command-definition.ts
new file mode 100644
index 00000000000..120762ee445
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/build/app-build.command-definition.ts
@@ -0,0 +1,24 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_BUILD_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['app', 'build'],
+ description: 'Build the app with the CLI and report the artifacts',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ ],
+ examples: [
+ 'twenty app build',
+ 'twenty app build --path ./apps/billing --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: true,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/app/build/run-app-build-command'))
+ .runAppBuildCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/build/run-app-build-command.ts b/packages/twenty-cli/src/commands/app/build/run-app-build-command.ts
new file mode 100644
index 00000000000..72de9fff8cd
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/build/run-app-build-command.ts
@@ -0,0 +1,26 @@
+import { formatBuildSummary } from '@/app/format-build-summary';
+import { runAppBuild } from '@/app/run-app-operation';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+
+export const runAppBuildCommand: CommandRun = async (context) => {
+ const { project, sdk, data, diagnostics, durationMilliseconds } =
+ await runAppBuild({ context });
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ sdk: { version: sdk.version },
+ application: data.application,
+ contentHash: data.contentHash,
+ files: data.files,
+ manifestFormat: data.manifestFormat,
+ manifest: data.manifest,
+ diagnostics,
+ durationMilliseconds,
+ },
+ human: formatBuildSummary({
+ build: data,
+ durationMilliseconds,
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/dev/app-dev.command-definition.ts b/packages/twenty-cli/src/commands/app/dev/app-dev.command-definition.ts
new file mode 100644
index 00000000000..e6432441ed6
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/dev/app-dev.command-definition.ts
@@ -0,0 +1,39 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_DEV_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'dev'],
+ description:
+ 'Watch app source, build complete snapshots and sync changes to the workspace',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--no-delete',
+ description: 'Keep remote entities missing from the app source',
+ },
+ {
+ flags: '--create',
+ description:
+ 'Allow registering and installing an app with no registration',
+ },
+ {
+ flags: '--yes',
+ description: 'Allow object and field deletions without asking',
+ },
+ ],
+ examples: [
+ 'twenty app dev --remote dev',
+ 'twenty app dev --create --no-delete',
+ 'twenty app dev --format ndjson --no-delete',
+ ],
+ outputModes: ['human', 'ndjson'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS', 'UPLOAD_FILE'],
+ load: async () =>
+ (await import('@/commands/app/dev/run-app-dev-command')).runAppDevCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts b/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts
new file mode 100644
index 00000000000..e228277683e
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts
@@ -0,0 +1,294 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { applyAppBuild } from '@/app/deployment/apply-app-build';
+import { createPostSyncFailure } from '@/app/deployment/create-post-sync-failure';
+import {
+ buildDevSnapshot,
+ type BuiltDevSnapshot,
+} from '@/app/dev/build-dev-snapshot';
+import { createDevClientGenerator } from '@/app/dev/generate-dev-client';
+import { createDevOutput } from '@/app/dev/create-dev-output';
+import { runDevLoop } from '@/app/dev/run-dev-loop';
+import { watchAppInputs } from '@/app/dev/watch-app-inputs';
+import { isToolingDiagnostic } from '@/app/parse-tooling-result';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { recordPullBase } from '@/app/record-pull-base';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { CliError } from '@/output/cli-error';
+import { toCliError } from '@/output/to-cli-error';
+
+export const runAppDevCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(context.options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const { output, emit } = createDevOutput(context);
+ const generateClient = createDevClientGenerator({ appPath: project.path });
+ let watcher: Awaited<ReturnType<typeof watchAppInputs>>;
+
+ await runDevLoop<BuiltDevSnapshot>({
+ signal: context.signal,
+ subscribe: async (invalidate, fail) => {
+ watcher = await watchAppInputs({
+ appPath: project.path,
+ signal: context.signal,
+ onChange: invalidate,
+ onError: fail,
+ });
+ try {
+ await emit(
+ {
+ kind: 'watch-ready',
+ message: `Watching ${project.path}. Syncing to ${context.target.apiUrl}. Press Ctrl+C to stop.`,
+ appPath: project.path,
+ },
+ context.signal,
+ );
+ } catch (error) {
+ await watcher.close();
+
+ throw error;
+ }
+
+ return watcher.close;
+ },
+ build: async (revision, signal) => {
+ await emit(
+ {
+ kind: 'build-start',
+ message: `Building revision ${revision}…`,
+ revision,
+ },
+ signal,
+ );
+
+ try {
+ const snapshot = await buildDevSnapshot({
+ appPath: project.path,
+ signal,
+ updateWatchInputs: watcher.update,
+ });
+
+ try {
+ await emit(
+ {
+ kind: 'build-success',
+ message: `Built ${snapshot.build.application.displayName}.`,
+ revision,
+ buildId: snapshot.build.buildId,
+ contentHash: snapshot.contentHash,
+ diagnostics: snapshot.diagnostics,
+ },
+ signal,
+ );
+
+ return snapshot;
+ } catch (error) {
+ await snapshot.release();
+
+ throw error;
+ }
+ } catch (error) {
+ signal.throwIfAborted();
+ const failure = toCliError(error);
+
+ if (failure.code === 'WORKER_FAILED') {
+ throw new CliError({
+ code: failure.code,
+ message: failure.message,
+ details: failure.details,
+ hint: 'Fix the worker failure, then restart twenty app dev. A worker killed while building may leave folders in .twenty/cli/snapshots; remove abandoned snapshots only after stopping all dev/apply sessions for this app.',
+ });
+ }
+
+ if (
+ ![
+ 'TYPECHECK_FAILED',
+ 'BUILD_FAILED',
+ 'SDK_NOT_INSTALLED',
+ 'SDK_SOURCE_UNSUPPORTED',
+ 'TYPESCRIPT_NOT_INSTALLED',
+ ].includes(failure.code)
+ ) {
+ throw error;
+ }
+
+ const diagnostics = failure.details?.diagnostics;
+
+ if (context.outputMode === 'human' && Array.isArray(diagnostics)) {
+ for (const diagnostic of diagnostics.filter(isToolingDiagnostic)) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+
+ await emit(
+ {
+ kind: 'build-failure',
+ message: `${failure.message} Waiting for source changes.`,
+ revision,
+ error: {
+ code: failure.code,
+ message: failure.message,
+ details: failure.details,
+ },
+ },
+ signal,
+ );
+
+ return undefined;
+ }
+ },
+ apply: async (snapshot, controls) => {
+ const { revision, signal } = controls;
+ const currentContext = { ...context, output, signal };
+ let hasStartedWriting = false;
+
+ await emit(
+ {
+ kind: 'sync-start',
+ message: `Previewing revision ${revision}…`,
+ revision,
+ buildId: snapshot.build.buildId,
+ },
+ signal,
+ );
+
+ let applied;
+
+ try {
+ applied = await applyAppBuild({
+ build: snapshot.build,
+ appPath: project.path,
+ context: currentContext,
+ inferDeletionFromMissingEntities: context.options.delete !== false,
+ isCreationApproved: readBooleanOption(context.options, 'create'),
+ isDeletionApproved: readBooleanOption(context.options, 'yes'),
+ approvalSignal: controls.revisionSignal,
+ flushProgress: () =>
+ emit({ kind: 'sync-progress', message: '', revision }, signal),
+ beforeWrite: () => {
+ if (!hasStartedWriting) controls.revisionSignal.throwIfAborted();
+ hasStartedWriting = true;
+ },
+ });
+ } catch (error) {
+ if (signal.aborted) throw error;
+ const failure = toCliError(error);
+
+ if (
+ controls.revisionSignal.aborted &&
+ failure.details?.phase === 'confirmation'
+ ) {
+ await emit(
+ {
+ kind: 'sync-superseded',
+ message: 'Source changed; a fresh preview is queued.',
+ revision,
+ details: failure.details,
+ },
+ signal,
+ );
+
+ return false;
+ }
+
+ if (['AUTH_REQUIRED', 'PERMISSION_DENIED'].includes(failure.code))
+ throw error;
+
+ await emit(
+ {
+ kind: 'sync-failure',
+ message: `${failure.message} A new source edit will request a fresh preview.`,
+ revision,
+ error: {
+ code: failure.code,
+ message: failure.message,
+ hint: failure.hint,
+ details: failure.details,
+ },
+ },
+ signal,
+ );
+
+ return false;
+ }
+
+ try {
+ const pullBase = await recordPullBase({
+ appPath: project.path,
+ universalIdentifier: applied.acknowledgedUniversalIdentifier,
+ sourceFingerprints: snapshot.sourceFingerprints,
+ context: currentContext,
+ });
+
+ if (pullBase === 'recorded') applied.completedPhases.push('pullBase');
+ } catch (error) {
+ throw createPostSyncFailure({
+ error,
+ phase: 'pullBase',
+ applicationName: snapshot.build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ completedPhases: applied.completedPhases,
+ signal,
+ });
+ }
+
+ const clientGeneration = await generateClient({
+ snapshot,
+ applied,
+ context: currentContext,
+ withBuildsPaused: controls.withBuildsPaused,
+ invalidate: controls.invalidate,
+ });
+
+ if (!isDefined(applied.appliedActions))
+ output.warn({
+ code: 'SYNC_REPORT_UNAVAILABLE',
+ message:
+ 'The sync succeeded, but the server did not return a readable list of changes.',
+ });
+
+ await emit(
+ {
+ kind: 'sync-success',
+ message: `Synced ${snapshot.build.application.displayName}. Watching for changes…`,
+ revision,
+ buildId: snapshot.build.buildId,
+ contentHash: snapshot.contentHash,
+ completedPhases: applied.completedPhases,
+ clientGeneration,
+ actions: applied.appliedActions ?? null,
+ },
+ signal,
+ );
+
+ return true;
+ },
+ onSkipped: (revision, reason) =>
+ emit(
+ {
+ kind: 'build-skipped',
+ message:
+ reason === 'unchanged'
+ ? 'Build unchanged since the last acknowledged sync.'
+ : 'Source changed during the build; rebuilding the latest revision.',
+ revision,
+ reason,
+ },
+ context.signal,
+ ),
+ });
+
+ throw new CliError({
+ code: 'INTERNAL_ERROR',
+ message: 'The dev session stopped unexpectedly.',
+ });
+};
diff --git a/packages/twenty-cli/src/commands/app/exec/app-exec.command-definition.ts b/packages/twenty-cli/src/commands/app/exec/app-exec.command-definition.ts
new file mode 100644
index 00000000000..f7a4e82c03b
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/exec/app-exec.command-definition.ts
@@ -0,0 +1,47 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_EXEC_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'exec'],
+ description: 'Execute a deployed app logic function as the signed-in user',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ { flags: '--name <name>', description: 'Exact deployed function name' },
+ {
+ flags: '--universal-identifier <id>',
+ description: 'Function universal identifier',
+ },
+ {
+ flags: '--post-install',
+ description: 'Execute the post-install hook without installing the app',
+ },
+ {
+ flags: '--pre-install',
+ description: 'Execute the pre-install hook without installing the app',
+ },
+ {
+ flags: '--uninstall-hook',
+ description: 'Execute the uninstall hook without uninstalling the app',
+ },
+ {
+ flags: '--payload <json>',
+ description: 'JSON object, @file or - for stdin (default: {})',
+ },
+ ],
+ examples: [
+ 'twenty app exec --name add-numbers --remote dev',
+ 'twenty app exec --name add-numbers --payload @payload.json --json',
+ "twenty app exec --post-install --payload '{}'",
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS', 'WORKFLOWS'],
+ load: async () =>
+ (await import('@/commands/app/exec/run-app-exec-command'))
+ .runAppExecCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts
new file mode 100644
index 00000000000..864c7b96df0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts
@@ -0,0 +1,74 @@
+import { executeAppFunction } from '@/app/exec/execute-app-function';
+import { formatFunctionExecution } from '@/app/exec/format-function-execution';
+import { readExecManifest } from '@/app/exec/read-exec-manifest';
+import { readFunctionSelector } from '@/app/exec/read-function-selector';
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { parseJsonObjectInput } from '@/input/parse-json-input';
+import { readInputValue } from '@/input/read-input-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const runAppExecCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const { options, target, signal, output, outputMode } = context;
+ const selector = readFunctionSelector(options);
+
+ if (target.credentialKind !== 'oauth') {
+ throw new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message:
+ 'Running logic functions requires a signed-in user. API keys cannot execute them.',
+ hint: `Sign in with twenty auth login --url ${target.apiUrl} --name dev, then use --remote dev.`,
+ details: { credentialKind: target.credentialKind },
+ });
+ }
+
+ const payload = parseJsonObjectInput({
+ text: await readInputValue({
+ value: readStringOption(options, 'payload') ?? '{}',
+ optionName: '--payload',
+ signal,
+ }),
+ optionName: '--payload',
+ });
+ const manifest = await readExecManifest(context);
+ if (selector.kind === 'hook') {
+ output.progress(
+ 'Executing the hook only; this does not install or uninstall the app.',
+ );
+ }
+ const result = await executeAppFunction({
+ manifest,
+ selector,
+ payload,
+ target,
+ signal,
+ onExecuting: (name) =>
+ output.progress(
+ `Executing ${formatDataValue(name)} on ${target.apiUrl}…`,
+ ),
+ });
+ const human = formatFunctionExecution(result);
+
+ if (result.status !== 'SUCCESS') {
+ if (outputMode === 'human') {
+ output.progress(human);
+ }
+ throw new CliError({
+ code: 'EXECUTION_FAILED',
+ message: `Function ${formatDataValue(result.functionName)} returned ${formatDataValue(result.status)}.`,
+ details: {
+ ...result,
+ outcome: 'completed',
+ diagnostics: manifest.diagnostics,
+ },
+ });
+ }
+
+ return { data: { ...result, diagnostics: manifest.diagnostics }, human };
+};
diff --git a/packages/twenty-cli/src/commands/app/function-logs/app-logs.command-definition.ts b/packages/twenty-cli/src/commands/app/function-logs/app-logs.command-definition.ts
new file mode 100644
index 00000000000..d6e09785010
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/function-logs/app-logs.command-definition.ts
@@ -0,0 +1,34 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_LOGS_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'logs'],
+ description: 'Watch new logic-function logs from this app',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--name <name>',
+ description: 'Filter all functions with this exact name within the app',
+ },
+ {
+ flags: '--universal-identifier <id>',
+ description: 'Filter one function by universal identifier',
+ },
+ ],
+ examples: [
+ 'twenty app logs --remote dev',
+ 'twenty app logs --name add-numbers --remote dev',
+ 'twenty app logs --format ndjson',
+ ],
+ outputModes: ['human', 'ndjson'],
+ writes: false,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['WORKFLOWS'],
+ load: async () =>
+ (await import('@/commands/app/function-logs/run-app-logs-command'))
+ .runAppLogsCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts b/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts
new file mode 100644
index 00000000000..f8fc86e7370
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts
@@ -0,0 +1,128 @@
+import { once } from 'node:events';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { readLogsFilter } from '@/app/function-logs/read-logs-filter';
+import { subscribeToAppLogs } from '@/app/function-logs/subscribe-to-app-logs';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { colorText, dimText, formatWarningLine } from '@/output/style';
+import { toCliError } from '@/output/to-cli-error';
+import { toPublicTarget } from '@/target/to-public-target';
+
+export const runAppLogsCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const { options, output, outputMode, signal, target } = context;
+ const filter = readLogsFilter(options);
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const identity = await readAppIdentity({ appPath: project.path, signal });
+ if (!isDefined(identity.application)) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'This project has no application definition.',
+ });
+ }
+ const applicationUniversalIdentifier =
+ identity.application.universalIdentifier.toLowerCase();
+ let recordCount = 0;
+
+ await output.event(
+ 'start',
+ {
+ target: toPublicTarget(target),
+ applicationUniversalIdentifier,
+ filter,
+ diagnostics: identity.diagnostics,
+ },
+ signal,
+ );
+ if (outputMode === 'human') {
+ for (const diagnostic of identity.diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ output.progress(
+ `Watching ${formatDataValue(identity.application.displayName ?? applicationUniversalIdentifier)} logs on ${target.apiUrl}. New executions only. Press Ctrl+C to stop.`,
+ );
+ }
+
+ try {
+ await subscribeToAppLogs({
+ applicationUniversalIdentifier,
+ filter,
+ target,
+ signal,
+ onConnected: () =>
+ output.event('progress', { kind: 'connected' }, signal),
+ onIdentityUnavailable: async () => {
+ const warning = {
+ code: 'LOG_IDENTITY_UNAVAILABLE',
+ message:
+ 'This server returns log text without function identities. Mixed logs cannot be attributed to individual functions; use --universal-identifier to isolate one, or upgrade the server.',
+ };
+ if (outputMode === 'human') {
+ output.progress(formatWarningLine(warning.message));
+ } else {
+ output.warn(warning);
+ }
+ },
+ onRecord: async (record) => {
+ if (outputMode === 'ndjson') {
+ await output.event('record', record, signal);
+ } else {
+ const label = [
+ ...(isDefined(record.functionName)
+ ? [colorText('cyan', formatDataValue(record.functionName))]
+ : []),
+ ...(isDefined(record.functionUniversalIdentifier)
+ ? [dimText(formatDataValue(record.functionUniversalIdentifier))]
+ : []),
+ ].join(' · ');
+ const text = [
+ ...(label.length > 0 ? [`[${label}]`] : []),
+ ...record.logs.replace(/\n$/, '').split('\n').map(formatDataValue),
+ ].join('\n');
+ signal.throwIfAborted();
+ if (!process.stdout.write(`${text}\n`)) {
+ await once(process.stdout, 'drain', { signal });
+ }
+ signal.throwIfAborted();
+ }
+ recordCount += 1;
+ },
+ });
+ } catch (error) {
+ const failure = toCliError(error, signal);
+ throw new CliError({
+ code: failure.code,
+ exitCode: failure.exitCode,
+ message: failure.message,
+ hint:
+ failure.code === 'NETWORK_ERROR'
+ ? 'Restart twenty app logs to resume watching. Logs produced while disconnected cannot be replayed.'
+ : failure.hint,
+ details: {
+ ...failure.details,
+ applicationUniversalIdentifier,
+ filter,
+ recordCount,
+ },
+ });
+ }
+
+ return {
+ data: { applicationUniversalIdentifier, filter, recordCount },
+ human: 'Log stream completed.',
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/init/app-init.command-definition.ts b/packages/twenty-cli/src/commands/app/init/app-init.command-definition.ts
new file mode 100644
index 00000000000..90f27088831
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/init/app-init.command-definition.ts
@@ -0,0 +1,40 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_INIT_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['app', 'init'],
+ description:
+ 'Create an app from the template bundled with this CLI, without installing anything',
+ arguments: [
+ {
+ name: 'name',
+ description: 'Package name of the app, for example my-app',
+ required: true,
+ },
+ ],
+ options: [
+ {
+ flags: '--path <directory>',
+ description: 'Directory to create (default: ./<name>)',
+ },
+ {
+ flags: '--display-name <name>',
+ description:
+ 'Name shown in Twenty (default: derived from the package name)',
+ },
+ {
+ flags: '--description <text>',
+ description: 'Description shown in Twenty',
+ },
+ ],
+ examples: [
+ 'twenty app init my-app',
+ 'twenty app init billing --path ./apps/billing --display-name Billing --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/app/init/run-app-init-command'))
+ .runAppInitCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts b/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts
new file mode 100644
index 00000000000..70ec82a6a7f
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts
@@ -0,0 +1,112 @@
+import { basename, isAbsolute, relative, resolve } from 'node:path';
+
+import { TEMPLATE_PACKAGE_VERSION } from '@create-twenty-app/constants/template-package-version';
+import { TEMPLATE_FIRST_PARTY_PACKAGES } from '@create-twenty-app/constants/template-packages';
+import { convertToLabel } from '@create-twenty-app/utils/convert-to-label';
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { createAppProject } from '@/app/create-app-project';
+import { formatAppInitSummary } from '@/app/format-app-init-summary';
+import { getAppInitNextSteps } from '@/app/get-app-init-next-steps';
+import { isValidPackageName } from '@/app/is-valid-package-name';
+import {
+ readStringArgument,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { hasConfiguredTarget } from '@/target/has-configured-target';
+
+const toDisplayPath = ({
+ workingDirectory,
+ appDirectory,
+}: {
+ workingDirectory: string;
+ appDirectory: string;
+}) => {
+ const relativePath = relative(workingDirectory, appDirectory);
+
+ if (relativePath === '') {
+ return '.';
+ }
+
+ return relativePath.startsWith('..') || isAbsolute(relativePath)
+ ? appDirectory
+ : relativePath;
+};
+
+export const runAppInitCommand: CommandRun = async ({
+ arguments: commandArguments,
+ options,
+ output,
+ signal,
+}) => {
+ const appName = readStringArgument(commandArguments, 0)?.trim() ?? '';
+
+ if (!isValidPackageName(appName)) {
+ throw new CliError({
+ code: 'INVALID_APP_NAME',
+ exitCode: EXIT_CODE.USAGE,
+ message: `"${appName}" is not a valid package name.`,
+ hint: 'Use lowercase letters, digits, hyphens, dots or underscores, for example my-app.',
+ });
+ }
+
+ const workingDirectory = process.cwd();
+ const appDirectory = resolve(
+ workingDirectory,
+ readStringOption(options, 'path') ?? basename(appName),
+ );
+ const displayName = readStringOption(options, 'displayName')?.trim();
+ const appDisplayName = isNonEmptyString(displayName)
+ ? displayName
+ : convertToLabel(appName);
+ const appDescription = readStringOption(options, 'description')?.trim() ?? '';
+ const displayPath = toDisplayPath({ workingDirectory, appDirectory });
+ const location = displayPath === '.' ? 'the current directory' : displayPath;
+
+ output.progress(`Creating ${appName} in ${location}…`);
+
+ await createAppProject({
+ appDirectory,
+ appName,
+ appDisplayName,
+ appDescription,
+ signal,
+ });
+
+ const remoteName = readStringOption(options, 'remote');
+ const nextSteps = getAppInitNextSteps({
+ displayPath,
+ isTargetConfigured: await hasConfiguredTarget({
+ environment: process.env,
+ remoteFlag: remoteName,
+ }),
+ remoteName,
+ });
+ const packageNames = [...TEMPLATE_FIRST_PARTY_PACKAGES];
+
+ return {
+ data: {
+ app: {
+ name: appName,
+ displayName: appDisplayName,
+ description: appDescription,
+ path: appDirectory,
+ },
+ packages: packageNames.map((name) => ({
+ name,
+ version: TEMPLATE_PACKAGE_VERSION,
+ })),
+ nextSteps,
+ },
+ human: formatAppInitSummary({
+ appName,
+ location,
+ packageNames,
+ packageVersion: TEMPLATE_PACKAGE_VERSION,
+ nextSteps,
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/plan/app-plan.command-definition.ts b/packages/twenty-cli/src/commands/app/plan/app-plan.command-definition.ts
new file mode 100644
index 00000000000..ce98e3e6069
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/plan/app-plan.command-definition.ts
@@ -0,0 +1,30 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_PLAN_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'plan'],
+ description:
+ 'Build the app and preview metadata changes without applying them',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--no-delete',
+ description: 'Keep remote entities missing from the app source',
+ },
+ ],
+ examples: [
+ 'twenty app plan --remote dev',
+ 'twenty app plan --path ./apps/billing --no-delete --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS'],
+ load: async () =>
+ (await import('@/commands/app/plan/run-app-plan-command'))
+ .runAppPlanCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts b/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts
new file mode 100644
index 00000000000..d519b6654e3
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts
@@ -0,0 +1,53 @@
+import { fetchAppPlan } from '@/app/deployment/fetch-app-plan';
+import { formatAppPlan } from '@/app/deployment/format-app-plan';
+import { getAppPlanSummary } from '@/app/deployment/get-app-plan-summary';
+import { runAppBuild } from '@/app/run-app-operation';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+
+export const runAppPlanCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const startedAt = performance.now();
+ const {
+ project,
+ sdk,
+ data: build,
+ diagnostics,
+ } = await runAppBuild({ context });
+ const inferDeletionFromMissingEntities = context.options.delete !== false;
+
+ context.output.progress(
+ 'Computing metadata plan (read-only, nothing will be applied)…',
+ );
+
+ const actions = await fetchAppPlan({
+ build,
+ inferDeletionFromMissingEntities,
+ target: context.target,
+ signal: context.signal,
+ });
+ const summary = getAppPlanSummary(actions);
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ sdk: { version: sdk.version },
+ application: build.application,
+ contentHash: build.contentHash,
+ plan: true,
+ inferDeletionFromMissingEntities,
+ actions,
+ summary,
+ diagnostics,
+ durationMilliseconds: Math.round(performance.now() - startedAt),
+ },
+ human: formatAppPlan({
+ applicationName: build.application.displayName,
+ apiUrl: context.target.apiUrl,
+ actions,
+ summary,
+ inferDeletionFromMissingEntities,
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts b/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts
new file mode 100644
index 00000000000..afe37ec313c
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts
@@ -0,0 +1,31 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_PULL_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'pull'],
+ description: 'Pull workspace metadata into an existing app project',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--universal-identifier <uuid>',
+ description:
+ 'Application to pull when this project has no application definition',
+ },
+ { flags: '--verbose', description: 'List coverage details' },
+ ],
+ examples: [
+ 'twenty app pull --remote dev',
+ 'twenty app pull --path ./apps/billing --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS'],
+ load: async () =>
+ (await import('@/commands/app/pull/run-app-pull-command'))
+ .runAppPullCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts
new file mode 100644
index 00000000000..a364c972e4b
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts
@@ -0,0 +1,243 @@
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { fetchAppExport } from '@/app/fetch-app-export';
+import { fetchWorkspaceId } from '@/app/fetch-workspace-id';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { parseToolingResult } from '@/app/parse-tooling-result';
+import { formatPullReport } from '@/app/pull/format-pull-report';
+import { parsePullData } from '@/app/pull/parse-pull-data';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { runAppWorker } from '@/app/run-app-worker';
+import { toWorkerOutputDiagnostics } from '@/app/to-worker-output-diagnostics';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatSuccessLine } from '@/output/style';
+
+export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({
+ options,
+ target,
+ signal,
+ output,
+ outputMode,
+}) => {
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+
+ const explicitIdentifier = readStringOption(options, 'universalIdentifier');
+
+ if (
+ isDefined(explicitIdentifier) &&
+ !isValidUniversalIdentifier(explicitIdentifier)
+ ) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: '--universal-identifier must be a UUID of version 4 or later.',
+ });
+ }
+
+ const identity = await readAppIdentity({ appPath: project.path, signal });
+
+ const universalIdentifier = (
+ explicitIdentifier ?? identity.application?.universalIdentifier
+ )?.toLowerCase();
+
+ if (!isDefined(universalIdentifier)) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'This project has no application definition.',
+ hint: 'Pass --universal-identifier <uuid> to pull an app into this project.',
+ });
+ }
+
+ if (
+ isDefined(identity.application) &&
+ identity.application.universalIdentifier.toLowerCase() !==
+ universalIdentifier
+ ) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `This project declares application ${identity.application.universalIdentifier}, not ${universalIdentifier}. Pull it into a different directory.`,
+ });
+ }
+ output.progress(`Exporting the app from ${target.apiUrl}…`);
+
+ const [workspaceId, applicationExport] = await Promise.all([
+ fetchWorkspaceId({ target, signal }),
+ fetchAppExport({ universalIdentifier, target, signal }),
+ ]);
+ output.progress(
+ 'Reconciling local definitions. Changed workspace entities replace local edits…',
+ );
+
+ const worker = await runAppWorker({
+ request: {
+ type: 'pull',
+ appPath: project.path,
+ target: { apiUrl: target.apiUrl, workspaceId },
+ applicationExport,
+ },
+ signal,
+ }).catch((error: unknown) => {
+ throw new CliError({
+ code: error instanceof CliError ? error.code : 'PULL_FAILED',
+ exitCode: error instanceof CliError ? error.exitCode : EXIT_CODE.FAILURE,
+ message: error instanceof Error ? error.message : String(error),
+ hint: 'The worker did not acknowledge completion. Inspect local changes and any backups in .twenty/cli/pull-backup-* before retrying.',
+ details: {
+ ...(error instanceof CliError ? error.details : {}),
+ outcome: 'unknown',
+ },
+ });
+ });
+
+ const result = parseToolingResult({
+ value: worker.result,
+ parseData: parsePullData,
+ });
+
+ const diagnostics = [
+ ...identity.diagnostics,
+ ...result.diagnostics,
+ ...toWorkerOutputDiagnostics(worker.output),
+ ];
+
+ if (outputMode === 'human') {
+ for (const diagnostic of diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+
+ if (!result.success) {
+ throw new CliError({
+ code:
+ result.error.code === 'CANCELLED'
+ ? 'CANCELLED'
+ : result.error.code === 'SDK_SOURCE_UNSUPPORTED'
+ ? 'SDK_SOURCE_UNSUPPORTED'
+ : 'PULL_FAILED',
+ exitCode:
+ result.error.code === 'CANCELLED'
+ ? EXIT_CODE.CANCELLED
+ : EXIT_CODE.FAILURE,
+ message: result.error.message,
+ hint:
+ result.error.hint ??
+ (result.error.code === 'SDK_SOURCE_UNSUPPORTED'
+ ? 'Upgrade the app to a compatible twenty-sdk version (2.40.0 or later).'
+ : undefined),
+ details: { ...result.error.details, diagnostics },
+ });
+ }
+
+ const data = result.data;
+
+ if (
+ data.skipped.length > 0 ||
+ data.unreadableRelativePaths.length > 0 ||
+ applicationExport.coverage.some(
+ (entry) => !['EXPORTED', 'ENGINE_DERIVED'].includes(entry.status),
+ )
+ ) {
+ output.warn({
+ code: 'PULL_INCOMPLETE',
+ message:
+ 'Some entities could not be written. See coverage, skipped entities and unreadable files in the pull report.',
+ });
+ }
+
+ const report = formatPullReport({
+ ...data,
+ writes: data.writes.map((entry) => ({
+ ...entry,
+ relativePath: formatDataValue(entry.relativePath),
+ })),
+ deletions: data.deletions.map((entry) => ({
+ ...entry,
+ relativePath: formatDataValue(entry.relativePath),
+ })),
+ skipped: data.skipped.map((entry) => ({
+ ...entry,
+ reason: formatDataValue(entry.reason),
+ })),
+ localOnlyRelativePaths: data.localOnlyRelativePaths.map(formatDataValue),
+ unreadableRelativePaths: data.unreadableRelativePaths.map(formatDataValue),
+ entityLabelByUniversalIdentifier: Object.fromEntries(
+ Object.entries(data.entityLabelByUniversalIdentifier).map(
+ ([identifier, label]) => [identifier, formatDataValue(label)],
+ ),
+ ),
+ coverage: applicationExport.coverage.map((entry) => ({
+ ...entry,
+ metadataName: formatDataValue(entry.metadataName),
+ universalIdentifier: formatDataValue(entry.universalIdentifier),
+ reason: entry.reason === null ? null : formatDataValue(entry.reason),
+ })),
+ verbose: readBooleanOption(options, 'verbose'),
+ });
+
+ const unknownCoverage = applicationExport.coverage.filter(
+ (entry) =>
+ ![
+ 'EXPORTED',
+ 'UNSUPPORTED',
+ 'FOREIGN_OWNED',
+ 'EXCLUDED',
+ 'ENGINE_DERIVED',
+ ].includes(entry.status),
+ );
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ ...data,
+ pulled: true,
+ coverage: applicationExport.coverage,
+ diagnostics,
+ },
+ human: [
+ formatSuccessLine(
+ `Pulled ${formatDataValue(data.application.displayName)} into ${formatDataValue(project.path)}`,
+ ),
+ report,
+ ...(data.base.status !== 'used'
+ ? [
+ `No matching pull base (${data.base.status}); local-only definitions were kept.`,
+ ]
+ : []),
+ ...(data.overwrittenLocalChanges.length > 0
+ ? [
+ 'Local edits replaced by workspace changes:',
+ ...data.overwrittenLocalChanges.map(
+ (entry) => ` ${formatDataValue(entry.relativePath)}`,
+ ),
+ ]
+ : []),
+ ...(unknownCoverage.length > 0
+ ? [
+ 'Unrecognized coverage, not written:',
+ ...unknownCoverage.map(
+ (entry) =>
+ ` ${formatDataValue(entry.metadataName)} ${formatDataValue(entry.status)}: ${formatDataValue(entry.reason)}`,
+ ),
+ ]
+ : []),
+ 'Run twenty app typecheck to check the generated definitions.',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/typecheck/app-typecheck.command-definition.ts b/packages/twenty-cli/src/commands/app/typecheck/app-typecheck.command-definition.ts
new file mode 100644
index 00000000000..a7fe99eecb5
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/typecheck/app-typecheck.command-definition.ts
@@ -0,0 +1,22 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_TYPECHECK_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['app', 'typecheck'],
+ description:
+ 'Typecheck the app with its project TypeScript, without building',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ ],
+ examples: ['twenty app typecheck', 'twenty app typecheck --json'],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: true,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/app/typecheck/run-app-typecheck-command'))
+ .runAppTypecheckCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/typecheck/run-app-typecheck-command.ts b/packages/twenty-cli/src/commands/app/typecheck/run-app-typecheck-command.ts
new file mode 100644
index 00000000000..d130363a9b1
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/typecheck/run-app-typecheck-command.ts
@@ -0,0 +1,21 @@
+import { formatAppDuration } from '@/app/format-app-duration';
+import { runAppTypecheck } from '@/app/run-app-operation';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { dimText, formatSuccessLine } from '@/output/style';
+
+export const runAppTypecheckCommand: CommandRun = async (context) => {
+ const { project, sdk, diagnostics, durationMilliseconds } =
+ await runAppTypecheck({ context });
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ sdk: { version: sdk.version },
+ diagnostics,
+ durationMilliseconds,
+ },
+ human: formatSuccessLine(
+ `No type errors in ${project.name} ${dimText(`· project TypeScript · ${formatAppDuration(durationMilliseconds)}`)}`,
+ ),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts b/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts
new file mode 100644
index 00000000000..5cfd7b8bfbe
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts
@@ -0,0 +1,36 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_UNINSTALL_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'uninstall'],
+ description:
+ 'Uninstall the app from the workspace, deleting its objects, fields and their data',
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ {
+ flags: '--universal-identifier <id>',
+ description:
+ 'Uninstall the app with this universal identifier without building the project, for example when the build is broken',
+ },
+ {
+ flags: '--yes',
+ description: 'Uninstall without asking',
+ },
+ ],
+ examples: [
+ 'twenty app uninstall --remote dev',
+ 'twenty app uninstall --yes --json',
+ 'twenty app uninstall --universal-identifier <id> --yes',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ requiredPermissions: ['APPLICATIONS'],
+ load: async () =>
+ (await import('@/commands/app/uninstall/run-app-uninstall-command'))
+ .runAppUninstallCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts
new file mode 100644
index 00000000000..2f42445d838
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts
@@ -0,0 +1,123 @@
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { createUninstallFailure } from '@/app/deployment/create-uninstall-failure';
+import { fetchInstalledApp } from '@/app/fetch-installed-app';
+import { requireApproval } from '@/app/deployment/require-approval';
+import { runAppBuild } from '@/app/run-app-operation';
+import { type AppUninstallPhase } from '@/app/deployment/types/app-uninstall-phase.type';
+import { uninstallApp } from '@/app/deployment/uninstall-app';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { dimText, formatSuccessLine } from '@/output/style';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+
+const readUniversalIdentifierOption = (options: Record<string, unknown>) => {
+ const universalIdentifier = readStringOption(options, 'universalIdentifier');
+
+ if (
+ isDefined(universalIdentifier) &&
+ !isValidUniversalIdentifier(universalIdentifier)
+ ) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `--universal-identifier must be a UUID of version 4 or later, not ${universalIdentifier}.`,
+ });
+ }
+
+ return universalIdentifier;
+};
+
+export const runAppUninstallCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const { options, target, signal, output, outputMode } = context;
+ const completedPhases: AppUninstallPhase[] = [];
+ const fail = (error: unknown, phase: AppUninstallPhase) =>
+ createUninstallFailure({ error, phase, completedPhases, signal });
+
+ const readApplicationIdentifier = async () => {
+ const explicitIdentifier = readUniversalIdentifierOption(options);
+
+ if (isDefined(explicitIdentifier)) {
+ return explicitIdentifier;
+ }
+
+ const { data: build } = await runAppBuild({ context });
+
+ completedPhases.push('build');
+
+ return build.application.universalIdentifier;
+ };
+
+ const universalIdentifier = (await readApplicationIdentifier()).toLowerCase();
+
+ output.progress(`Checking the app on ${target.apiUrl}…`);
+
+ const installedApp = await fetchInstalledApp({
+ universalIdentifier,
+ target,
+ signal,
+ }).catch((error: unknown) => {
+ throw fail(error, 'check');
+ });
+ const appName = formatDataValue(installedApp.name);
+
+ if (!installedApp.canBeUninstalled) {
+ throw fail(
+ new CliError({
+ code: 'APP_NOT_UNINSTALLABLE',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `${appName} cannot be uninstalled from ${target.apiUrl}.`,
+ }),
+ 'check',
+ );
+ }
+
+ completedPhases.push('check');
+
+ await requireApproval({
+ isApproved: readBooleanOption(options, 'yes'),
+ canPrompt: isInteractionAllowed({ options, outputMode }),
+ question: `Uninstall ${appName} from ${target.apiUrl}? Its objects, fields and their data are permanently deleted.`,
+ code: 'CONFIRMATION_REQUIRED',
+ message: `Uninstalling ${appName} permanently deletes its objects, fields and their data.`,
+ hint: 'Pass --yes to uninstall it.',
+ declinedMessage: 'Uninstall stopped at the confirmation prompt.',
+ signal,
+ }).catch((error: unknown) => {
+ throw fail(error, 'confirmation');
+ });
+
+ output.progress(`Uninstalling ${appName}…`);
+
+ await uninstallApp({ universalIdentifier, target, signal }).catch(
+ (error: unknown) => {
+ throw fail(error, 'uninstall');
+ },
+ );
+
+ completedPhases.push('uninstall');
+
+ return {
+ data: {
+ application: { universalIdentifier, name: installedApp.name },
+ uninstalled: true,
+ completedPhases,
+ },
+ human: [
+ formatSuccessLine(`Uninstalled ${appName} from ${target.apiUrl}`),
+ dimText(
+ ' Its registration is kept, so twenty app apply can install it again.',
+ ),
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/auth/__tests__/auth-and-remote-commands.spec.ts b/packages/twenty-cli/src/commands/auth/__tests__/auth-and-remote-commands.spec.ts
new file mode 100644
index 00000000000..38378d92815
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/__tests__/auth-and-remote-commands.spec.ts
@@ -0,0 +1,249 @@
+import { mkdtemp, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+const VALID_KEY = 'valid-key';
+
+const server = await startTestServer((request, response) => {
+ if (request.headers.authorization !== `Bearer ${VALID_KEY}`) {
+ return sendJson(response, 200, {
+ errors: [
+ { message: 'Token invalid.', extensions: { code: 'UNAUTHENTICATED' } },
+ ],
+ data: null,
+ });
+ }
+
+ return sendJson(response, 200, {
+ data: { currentWorkspace: { displayName: 'Acme' } },
+ });
+});
+
+const secondServerUrl = server.url.replace('127.0.0.1', 'localhost');
+
+const runJson = async (args: string[]) => {
+ const { stdout, exitCode } = await runCliForTest([...args, '--json']);
+
+ return { envelope: parseSingleJsonLine(stdout), exitCode };
+};
+
+const login = (args: string[], apiKey = VALID_KEY) => {
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ content: `${apiKey}\n` }),
+ );
+
+ return runJson(['auth', 'login', '--with-token', ...args]);
+};
+
+describe('auth and remote commands', () => {
+ let configPath: string;
+
+ const readConfigFile = async () =>
+ JSON.parse(await readFile(configPath, 'utf8'));
+
+ beforeEach(async () => {
+ const home = await mkdtemp(join(tmpdir(), 'twenty-cli-home-'));
+
+ configPath = join(home, '.twenty', 'config.json');
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ it('checks an API key read from stdin and saves the first remote as default', async () => {
+ const { envelope, exitCode } = await login([
+ '--url',
+ server.url,
+ '--name',
+ 'prod',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toEqual({
+ remote: 'prod',
+ apiUrl: server.url,
+ credentials: 'apiKey',
+ workspaceName: 'Acme',
+ email: null,
+ isDefault: true,
+ });
+ expect(await readConfigFile()).toEqual({
+ version: 1,
+ defaultRemote: 'prod',
+ remotes: {
+ prod: { apiUrl: server.url, apiKey: VALID_KEY, workspaceName: 'Acme' },
+ },
+ });
+ });
+
+ it('saves nothing when the server rejects the key', async () => {
+ const { envelope, exitCode } = await login(
+ ['--url', server.url, '--name', 'prod'],
+ 'wrong-key',
+ );
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error.code).toBe('AUTH_REQUIRED');
+ expect(envelope.error.message).toContain('Nothing was saved');
+ await expect(readFile(configPath, 'utf8')).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ });
+
+ it('asks for --replace before pointing a remote at another URL', async () => {
+ await login(['--url', server.url, '--name', 'prod']);
+
+ const refused = await login(['--url', secondServerUrl, '--name', 'prod']);
+ const replaced = await login([
+ '--url',
+ secondServerUrl,
+ '--name',
+ 'prod',
+ '--replace',
+ ]);
+
+ expect(refused.exitCode).toBe(2);
+ expect(refused.envelope.error.code).toBe('CONFIRMATION_REQUIRED');
+ expect(replaced.exitCode).toBe(0);
+ expect((await readConfigFile()).remotes.prod.apiUrl).toBe(secondServerUrl);
+ });
+
+ it('lists, switches, renames and removes remotes', async () => {
+ await login(['--url', server.url, '--name', 'prod']);
+ await login(['--url', server.url, '--name', 'staging']);
+
+ const listed = await runJson(['remote', 'list']);
+
+ expect(listed.envelope.data).toEqual({
+ defaultRemote: 'prod',
+ remotes: [
+ {
+ name: 'prod',
+ apiUrl: server.url,
+ credentials: 'apiKey',
+ workspaceName: 'Acme',
+ isDefault: true,
+ },
+ {
+ name: 'staging',
+ apiUrl: server.url,
+ credentials: 'apiKey',
+ workspaceName: 'Acme',
+ isDefault: false,
+ },
+ ],
+ });
+
+ await runJson(['remote', 'use', 'staging']);
+ await runJson(['remote', 'rename', 'staging', 'preprod']);
+ expect((await readConfigFile()).defaultRemote).toBe('preprod');
+
+ const clash = await runJson(['remote', 'rename', 'preprod', 'prod']);
+
+ expect(clash.envelope.error.code).toBe('REMOTE_EXISTS');
+
+ const removed = await runJson(['remote', 'remove', 'preprod']);
+
+ expect(removed.envelope.data).toEqual({
+ removed: 'preprod',
+ wasDefault: true,
+ });
+ expect(await readConfigFile()).not.toHaveProperty('defaultRemote');
+
+ const unknown = await runJson(['remote', 'use', 'preprod']);
+
+ expect(unknown.exitCode).toBe(2);
+ expect(unknown.envelope.error.code).toBe('UNKNOWN_REMOTE');
+ });
+
+ it('reports status and prints the token of the default remote', async () => {
+ await login(['--url', server.url, '--name', 'prod']);
+
+ const status = await runJson(['auth', 'status']);
+ const token = await runJson(['auth', 'token']);
+
+ expect(status.envelope).toMatchObject({
+ target: { remote: 'prod', apiUrl: server.url, source: 'remote' },
+ data: {
+ remote: 'prod',
+ isDefaultRemote: true,
+ credentials: 'apiKey',
+ workspaceName: 'Acme',
+ },
+ });
+ expect(token.envelope.data).toEqual({
+ token: VALID_KEY,
+ credentials: 'apiKey',
+ });
+ });
+
+ it('lets --remote win over environment credentials with a warning', async () => {
+ await login(['--url', server.url, '--name', 'prod']);
+ vi.stubEnv('TWENTY_API_URL', 'https://other.example.com');
+ vi.stubEnv('TWENTY_API_KEY', 'other-key');
+
+ const { envelope } = await runJson(['auth', 'status', '--remote', 'prod']);
+
+ expect(envelope.target.remote).toBe('prod');
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'ENVIRONMENT_TARGET_IGNORED' }),
+ ]);
+ });
+
+ it('signs out of a remote and keeps it', async () => {
+ await login(['--url', server.url, '--name', 'prod']);
+
+ const loggedOut = await runJson(['auth', 'logout']);
+ const status = await runJson(['auth', 'status']);
+ const loggedOutAgain = await runJson(['auth', 'logout']);
+
+ expect(loggedOut.envelope.data).toEqual({
+ remote: 'prod',
+ wasSignedIn: true,
+ });
+ expect(status.exitCode).toBe(3);
+ expect(status.envelope.error.code).toBe('AUTH_REQUIRED');
+ expect(loggedOutAgain.envelope.data.wasSignedIn).toBe(false);
+ expect((await readConfigFile()).remotes.prod).toEqual({
+ apiUrl: server.url,
+ workspaceName: 'Acme',
+ });
+ });
+
+ it('refuses to sign out of environment credentials', async () => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', VALID_KEY);
+
+ const { envelope, exitCode } = await runJson(['auth', 'logout']);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('USAGE');
+ });
+});
diff --git a/packages/twenty-cli/src/commands/auth/login/auth-login.command-definition.ts b/packages/twenty-cli/src/commands/auth/login/auth-login.command-definition.ts
new file mode 100644
index 00000000000..a8217712f8b
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/login/auth-login.command-definition.ts
@@ -0,0 +1,34 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const AUTH_LOGIN_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['auth', 'login'],
+ description: 'Sign in with your browser or an API key, and save the remote',
+ options: [
+ {
+ flags: '--with-token',
+ description: 'Read an API key from standard input',
+ },
+ {
+ flags: '--url <url>',
+ description: 'Twenty server URL, for example https://acme.twenty.com',
+ },
+ { flags: '--name <name>', description: 'Name of the remote to save' },
+ { flags: '--use', description: 'Make this remote the default' },
+ {
+ flags: '--replace',
+ description: 'Point an existing remote at a different URL',
+ },
+ ],
+ examples: [
+ 'twenty auth login --url https://acme.twenty.com --name prod',
+ 'printf \'%s\' "$TWENTY_API_KEY" | twenty auth login --with-token --url https://acme.twenty.com --name prod',
+ 'twenty auth login --with-token --remote prod < api-key.txt',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/auth/login/run-auth-login-command'))
+ .runAuthLoginCommand,
+};
diff --git a/packages/twenty-cli/src/commands/auth/login/read-api-key-from-standard-input.ts b/packages/twenty-cli/src/commands/auth/login/read-api-key-from-standard-input.ts
new file mode 100644
index 00000000000..0e382b72575
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/login/read-api-key-from-standard-input.ts
@@ -0,0 +1,35 @@
+import { readInputValue } from '@/input/read-input-value';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const PIPE_HINT =
+ 'Pipe it in, for example: printf \'%s\' "$TWENTY_API_KEY" | twenty auth login --with-token --url <url> --name <name>';
+
+export const readApiKeyFromStandardInput = async (signal: AbortSignal) => {
+ if (process.stdin.isTTY === true) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'The API key must come from standard input.',
+ hint: PIPE_HINT,
+ });
+ }
+
+ const apiKey = (
+ await readInputValue({ value: '-', optionName: 'the API key', signal })
+ ).trim();
+
+ if (apiKey === '' || /\s/.test(apiKey)) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ apiKey === ''
+ ? 'Standard input is empty.'
+ : 'Standard input must contain only the API key.',
+ hint: PIPE_HINT,
+ });
+ }
+
+ return apiKey;
+};
diff --git a/packages/twenty-cli/src/commands/auth/login/run-auth-login-command.ts b/packages/twenty-cli/src/commands/auth/login/run-auth-login-command.ts
new file mode 100644
index 00000000000..0eff4cdd83a
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/login/run-auth-login-command.ts
@@ -0,0 +1,265 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { readApiKeyFromStandardInput } from '@/commands/auth/login/read-api-key-from-standard-input';
+import { getConfigPath } from '@/config/get-config-path';
+import { readConfig } from '@/config/read-config';
+import { replaceRemoteCredentials } from '@/config/replace-remote-credentials';
+import { type RemoteCredentials } from '@/config/types/remote-credentials.type';
+import {
+ type ConfigFile,
+ type RemoteEntry,
+} from '@/config/types/config-file.type';
+import { updateConfig } from '@/config/update-config';
+import { validateRemoteName } from '@/config/validate-remote-name';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { dimText, formatSuccessLine } from '@/output/style';
+import { parseApiUrl } from '@/target/parse-api-url';
+import { signInWithBrowser } from '@/oauth/sign-in-with-browser';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { type Output } from '@/output/types/output.type';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+import { fetchSignedInIdentity } from '@/transport/metadata/fetch-signed-in-identity';
+
+const findExistingRemote = (config: ConfigFile, remoteName: string) =>
+ Object.hasOwn(config.remotes, remoteName)
+ ? config.remotes[remoteName]
+ : undefined;
+
+const assertSameUrlOrReplace = ({
+ existingRemote,
+ remoteName,
+ apiUrl,
+ replace,
+}: {
+ existingRemote: RemoteEntry | undefined;
+ remoteName: string;
+ apiUrl: string;
+ replace: boolean;
+}) => {
+ if (
+ !isDefined(existingRemote) ||
+ replace ||
+ parseApiUrl({ rawUrl: existingRemote.apiUrl, sourceName: remoteName }) ===
+ apiUrl
+ ) {
+ return;
+ }
+
+ throw new CliError({
+ code: 'CONFIRMATION_REQUIRED',
+ exitCode: EXIT_CODE.USAGE,
+ message: `Remote ${remoteName} points to ${existingRemote.apiUrl}.`,
+ hint: `Pass --replace to point it at ${apiUrl}.`,
+ });
+};
+
+const readRemoteName = (options: Record<string, unknown>) => {
+ const remoteName =
+ readStringOption(options, 'name') ?? readStringOption(options, 'remote');
+
+ if (!isDefined(remoteName)) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'Name the remote with --name.',
+ hint: 'To sign in to a saved remote again, pass --remote <name>.',
+ });
+ }
+
+ return validateRemoteName(remoteName);
+};
+
+const obtainCredentials = async ({
+ options,
+ apiUrl,
+ output,
+ outputMode,
+ signal,
+}: {
+ options: Record<string, unknown>;
+ apiUrl: string;
+ output: Output;
+ outputMode: OutputMode;
+ signal: AbortSignal;
+}): Promise<RemoteCredentials> => {
+ if (readBooleanOption(options, 'withToken')) {
+ return {
+ kind: 'apiKey',
+ apiKey: await readApiKeyFromStandardInput(signal),
+ };
+ }
+
+ if (!isInteractionAllowed({ options, outputMode })) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ 'Browser sign-in only runs in an interactive terminal, not with --no-input, JSON output, redirected stdin or in CI.',
+ hint: `In scripts and CI, pipe an API key: printf '%s' "$TWENTY_API_KEY" | twenty auth login --with-token --url ${apiUrl} --name <name>`,
+ });
+ }
+
+ return {
+ kind: 'oauth',
+ ...(await signInWithBrowser({ apiUrl, output, signal })),
+ };
+};
+
+const formatSignedIn = ({
+ remoteName,
+ apiUrl,
+ credentials,
+ identity,
+}: {
+ remoteName: string;
+ apiUrl: string;
+ credentials: RemoteCredentials;
+ identity: { workspaceName: string | null; email: string | null };
+}) => {
+ const workspace = isDefined(identity.workspaceName)
+ ? ` · workspace ${identity.workspaceName}`
+ : '';
+
+ return credentials.kind === 'apiKey'
+ ? `Saved remote ${remoteName} ${dimText(`(${apiUrl}) · API key${workspace}`)}`
+ : `Signed in to ${remoteName}${isDefined(identity.email) ? ` as ${identity.email}` : ''}${dimText(workspace)}`;
+};
+
+export const runAuthLoginCommand: CommandRun = async ({
+ options,
+ output,
+ outputMode,
+ signal,
+}) => {
+ const remoteName = readRemoteName(options);
+ const replace = readBooleanOption(options, 'replace');
+ const configPath = getConfigPath();
+ const existingRemote = findExistingRemote(
+ await readConfig(configPath),
+ remoteName,
+ );
+ const urlOption = readStringOption(options, 'url');
+
+ if (!isDefined(urlOption) && !isDefined(existingRemote)) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `There is no remote named ${remoteName} yet.`,
+ hint: 'Pass --url to create it.',
+ });
+ }
+
+ const apiUrl = isDefined(urlOption)
+ ? parseApiUrl({ rawUrl: urlOption, sourceName: '--url' })
+ : parseApiUrl({
+ rawUrl: existingRemote?.apiUrl ?? '',
+ sourceName: `The URL of remote ${remoteName}`,
+ });
+
+ assertSameUrlOrReplace({ existingRemote, remoteName, apiUrl, replace });
+
+ const credentials = await obtainCredentials({
+ options,
+ apiUrl,
+ output,
+ outputMode,
+ signal,
+ });
+ const identity = await fetchSignedInIdentity({
+ target: {
+ apiUrl,
+ bearerToken:
+ credentials.kind === 'apiKey'
+ ? credentials.apiKey
+ : credentials.accessToken,
+ credentialKind: credentials.kind,
+ source: 'remote',
+ remoteName,
+ },
+ signal,
+ }).catch((error: unknown) => {
+ if (error instanceof CliError && error.code === 'AUTH_REQUIRED') {
+ throw new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `${apiUrl} rejected ${credentials.kind === 'apiKey' ? 'this API key' : 'the new session'}. Nothing was saved.`,
+ hint:
+ credentials.kind === 'apiKey'
+ ? 'Check the key and that it belongs to a workspace on this server.'
+ : 'Run twenty auth login again.',
+ details: error.details,
+ });
+ }
+
+ throw error;
+ });
+
+ const isDefault = await updateConfig({
+ configPath,
+ signal,
+ update: (config) => {
+ const latestRemote = findExistingRemote(config, remoteName);
+
+ assertSameUrlOrReplace({
+ existingRemote: latestRemote,
+ remoteName,
+ apiUrl,
+ replace,
+ });
+
+ const hasUsableDefault =
+ isDefined(config.defaultRemote) &&
+ Object.hasOwn(config.remotes, config.defaultRemote);
+ const defaultRemote =
+ readBooleanOption(options, 'use') || !hasUsableDefault
+ ? remoteName
+ : config.defaultRemote;
+
+ return {
+ result: defaultRemote === remoteName,
+ config: {
+ ...config,
+ defaultRemote,
+ remotes: {
+ ...config.remotes,
+ [remoteName]: {
+ ...replaceRemoteCredentials({
+ remote: latestRemote ?? { apiUrl },
+ credentials,
+ }),
+ apiUrl,
+ ...(isDefined(identity.workspaceName)
+ ? { workspaceName: identity.workspaceName }
+ : {}),
+ },
+ },
+ },
+ };
+ },
+ });
+
+ return {
+ data: {
+ remote: remoteName,
+ apiUrl,
+ credentials: credentials.kind,
+ workspaceName: identity.workspaceName,
+ email: identity.email,
+ isDefault,
+ },
+ human: [
+ formatSuccessLine(
+ formatSignedIn({ remoteName, apiUrl, credentials, identity }),
+ ),
+ ...(isDefault
+ ? [dimText(` ${remoteName} is your default remote.`)]
+ : []),
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/auth/logout/auth-logout.command-definition.ts b/packages/twenty-cli/src/commands/auth/logout/auth-logout.command-definition.ts
new file mode 100644
index 00000000000..db5d7fc5268
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/logout/auth-logout.command-definition.ts
@@ -0,0 +1,14 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const AUTH_LOGOUT_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['auth', 'logout'],
+ description: 'Forget the credentials of a saved remote, keeping the remote',
+ examples: ['twenty auth logout --remote staging'],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/auth/logout/run-auth-logout-command'))
+ .runAuthLogoutCommand,
+};
diff --git a/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts b/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts
new file mode 100644
index 00000000000..bd5824a52c3
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/logout/run-auth-logout-command.ts
@@ -0,0 +1,73 @@
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { getConfigPath } from '@/config/get-config-path';
+import { getCredentialKind } from '@/config/get-credential-kind';
+import { readConfig } from '@/config/read-config';
+import { updateConfig } from '@/config/update-config';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { dimText, formatSuccessLine } from '@/output/style';
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { findRemote } from '@/target/find-remote';
+import { selectTarget } from '@/target/select-target';
+
+export const runAuthLogoutCommand: CommandRun = async ({
+ options,
+ output,
+ signal,
+}) => {
+ const configPath = getConfigPath();
+ const selection = await selectTarget({
+ environment: process.env,
+ remoteFlag: readStringOption(options, 'remote'),
+ loadConfig: () => readConfig(configPath),
+ warn: output.warn,
+ });
+
+ if (selection.source === 'environment') {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${TARGET_ENVIRONMENT_VARIABLE.API_URL} and ${TARGET_ENVIRONMENT_VARIABLE.API_KEY} are not saved, so there is nothing to sign out of.`,
+ hint: 'Unset them in your shell, or pick a saved remote with --remote.',
+ });
+ }
+
+ const { remoteName } = selection;
+ const hadCredentials = await updateConfig({
+ configPath,
+ signal,
+ update: (config) => {
+ const remote = findRemote(config, remoteName);
+ const {
+ apiKey: _apiKey,
+ twentyCLIAccessToken: _accessToken,
+ twentyCLIRefreshToken: _refreshToken,
+ ...remoteWithoutCredentials
+ } = remote;
+
+ return {
+ result: getCredentialKind(remote) !== 'none',
+ config: {
+ ...config,
+ remotes: {
+ ...config.remotes,
+ [remoteName]: remoteWithoutCredentials,
+ },
+ },
+ };
+ },
+ });
+
+ return {
+ data: { remote: remoteName, wasSignedIn: hadCredentials },
+ human: hadCredentials
+ ? [
+ formatSuccessLine(`Signed out of ${remoteName}.`),
+ dimText(
+ ` The remote stays; sign in with twenty auth login --remote ${remoteName} --with-token`,
+ ),
+ ].join('\n')
+ : `${remoteName} was already signed out.`,
+ };
+};
diff --git a/packages/twenty-cli/src/commands/auth/status/auth-status.command-definition.ts b/packages/twenty-cli/src/commands/auth/status/auth-status.command-definition.ts
new file mode 100644
index 00000000000..46b13d6be69
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/status/auth-status.command-definition.ts
@@ -0,0 +1,13 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const AUTH_STATUS_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['auth', 'status'],
+ description: 'Show which workspace commands use and check its credentials',
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/auth/status/run-auth-status-command'))
+ .runAuthStatusCommand,
+};
diff --git a/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts b/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts
new file mode 100644
index 00000000000..f8ca3101296
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/status/run-auth-status-command.ts
@@ -0,0 +1,74 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { CREDENTIAL_KIND_LABELS } from '@/config/constants/credential-kind-labels.constant';
+import { getConfigPath } from '@/config/get-config-path';
+import { readConfig } from '@/config/read-config';
+import { getAccessTokenExpiry } from '@/oauth/is-access-token-expiring';
+import { formatDetails } from '@/output/format-details';
+import { dimText } from '@/output/style';
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { fetchSignedInIdentity } from '@/transport/metadata/fetch-signed-in-identity';
+
+const MINUTE_MILLISECONDS = 60_000;
+
+const formatTimeLeft = (expiry: number) => {
+ const minutes = Math.max(
+ 0,
+ Math.round((expiry - Date.now()) / MINUTE_MILLISECONDS),
+ );
+
+ return minutes < 120
+ ? `${minutes} minutes`
+ : `${Math.round(minutes / 60)} hours`;
+};
+
+export const runAuthStatusCommand: CommandRun<TargetCommandContext> = async ({
+ target,
+ signal,
+}) => {
+ const identity = await fetchSignedInIdentity({ target, signal });
+ const isDefaultRemote =
+ isDefined(target.remoteName) &&
+ (await readConfig(getConfigPath())).defaultRemote === target.remoteName;
+ const sessionExpiry =
+ target.credentialKind === 'oauth'
+ ? getAccessTokenExpiry(target.bearerToken)
+ : undefined;
+ const remoteLabel = isDefined(target.remoteName)
+ ? `${target.remoteName}${isDefaultRemote ? dimText(' (default)') : ''}`
+ : dimText(
+ `none, using ${TARGET_ENVIRONMENT_VARIABLE.API_URL} and ${TARGET_ENVIRONMENT_VARIABLE.API_KEY}`,
+ );
+ const credentialsLabel = isDefined(identity.email)
+ ? `${identity.email} ${dimText(`via ${CREDENTIAL_KIND_LABELS[target.credentialKind]}`)}`
+ : CREDENTIAL_KIND_LABELS[target.credentialKind];
+
+ return {
+ data: {
+ remote: target.remoteName ?? null,
+ isDefaultRemote,
+ apiUrl: target.apiUrl,
+ source: target.source,
+ credentials: target.credentialKind,
+ email: identity.email,
+ workspaceName: identity.workspaceName,
+ sessionExpiresAt: isDefined(sessionExpiry)
+ ? new Date(sessionExpiry).toISOString()
+ : null,
+ },
+ human: formatDetails([
+ ['Remote', remoteLabel],
+ ['Server', target.apiUrl],
+ ['Workspace', identity.workspaceName ?? dimText('unnamed')],
+ ['Signed in', credentialsLabel],
+ [
+ 'Status',
+ isDefined(sessionExpiry)
+ ? `valid ${dimText(`· renews itself, current token expires in ${formatTimeLeft(sessionExpiry)}`)}`
+ : 'valid',
+ ],
+ ]),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/auth/token/auth-token.command-definition.ts b/packages/twenty-cli/src/commands/auth/token/auth-token.command-definition.ts
new file mode 100644
index 00000000000..c41f1f7c231
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/token/auth-token.command-definition.ts
@@ -0,0 +1,16 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const AUTH_TOKEN_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['auth', 'token'],
+ description: 'Print the credential commands send, for scripts',
+ examples: [
+ 'curl -H "Authorization: Bearer $(twenty auth token)" https://acme.twenty.com/rest/companies',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/auth/token/run-auth-token-command'))
+ .runAuthTokenCommand,
+};
diff --git a/packages/twenty-cli/src/commands/auth/token/run-auth-token-command.ts b/packages/twenty-cli/src/commands/auth/token/run-auth-token-command.ts
new file mode 100644
index 00000000000..5970e7c4316
--- /dev/null
+++ b/packages/twenty-cli/src/commands/auth/token/run-auth-token-command.ts
@@ -0,0 +1,9 @@
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+
+export const runAuthTokenCommand: CommandRun<TargetCommandContext> = async ({
+ target,
+}) => ({
+ data: { token: target.bearerToken, credentials: target.credentialKind },
+ human: target.bearerToken,
+});
diff --git a/packages/twenty-cli/src/commands/commands/commands.command-definition.ts b/packages/twenty-cli/src/commands/commands/commands.command-definition.ts
new file mode 100644
index 00000000000..109b631a939
--- /dev/null
+++ b/packages/twenty-cli/src/commands/commands/commands.command-definition.ts
@@ -0,0 +1,15 @@
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const COMMANDS_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['commands'],
+ description: 'List the available commands',
+ helpGroup: HELP_GROUP.TOOLS,
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/commands/run-commands-command'))
+ .runCommandsCommand,
+};
diff --git a/packages/twenty-cli/src/commands/commands/run-commands-command.ts b/packages/twenty-cli/src/commands/commands/run-commands-command.ts
new file mode 100644
index 00000000000..7a147ab48c9
--- /dev/null
+++ b/packages/twenty-cli/src/commands/commands/run-commands-command.ts
@@ -0,0 +1,43 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { COMMAND_CATALOG } from '@/catalog/command-catalog';
+import { getCommandName } from '@/catalog/get-command-name';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { formatTable } from '@/output/format-table';
+import { dimText } from '@/output/style';
+import { GLOBAL_FLAGS } from '@/program/constants/global-flags.constant';
+
+export const runCommandsCommand: CommandRun = async () => {
+ const commands = COMMAND_CATALOG.map((definition) => ({
+ name: getCommandName(definition),
+ description: definition.description,
+ arguments: (definition.arguments ?? []).map(({ name, required }) => ({
+ name,
+ required,
+ })),
+ flags: (definition.options ?? [])
+ .filter(({ hidden }) => hidden !== true)
+ .map(({ flags }) => flags),
+ outputs: definition.outputModes,
+ writes: definition.writes,
+ needsProject: definition.needsProject,
+ needsTarget: definition.needsTarget,
+ ...(isDefined(definition.requiredPermissions)
+ ? { requiredPermissions: definition.requiredPermissions }
+ : {}),
+ })).sort((first, second) => first.name.localeCompare(second.name));
+
+ return {
+ data: { commands, globalFlags: Object.values(GLOBAL_FLAGS) },
+ human: [
+ formatTable({
+ rows: commands,
+ columns: [
+ { header: 'COMMAND', value: (command) => command.name },
+ { header: 'DESCRIPTION', value: (command) => command.description },
+ ],
+ }),
+ dimText(`${commands.length} commands · details: twenty <command> --help`),
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/data/__tests__/data-inspection.spec.ts b/packages/twenty-cli/src/commands/data/__tests__/data-inspection.spec.ts
new file mode 100644
index 00000000000..a3d3b59c211
--- /dev/null
+++ b/packages/twenty-cli/src/commands/data/__tests__/data-inspection.spec.ts
@@ -0,0 +1,868 @@
+import { setImmediate } from 'node:timers/promises';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ assertIsDefinedOrThrow,
+ isDefined,
+ isNonEmptyArray,
+} from 'twenty-shared/utils';
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { type DataRecord } from '@/data/types/data-page.type';
+import { runCli } from '@/run-cli';
+
+const company = {
+ id: 'company-object',
+ nameSingular: 'company',
+ namePlural: 'companies',
+};
+let objects = [company];
+let records: DataRecord[] = [];
+let record: unknown;
+let status = 200;
+let metadataDenied = false;
+let failPageAfter = false;
+let invalidPayload: unknown;
+let cursorCycle: string[] | undefined;
+let restRequests = 0;
+
+const server = await startTestServer((request, response) => {
+ const url = new URL(request.path, 'http://fixture');
+
+ if (url.pathname === '/metadata') {
+ return sendJson(
+ response,
+ 200,
+ metadataDenied
+ ? {
+ errors: [
+ { message: 'Forbidden', extensions: { code: 'FORBIDDEN' } },
+ ],
+ data: null,
+ }
+ : {
+ data: {
+ objects: {
+ edges: objects.map((object) => ({ node: object })),
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ },
+ },
+ );
+ }
+
+ restRequests += 1;
+ const cursor = url.searchParams.get('starting_after');
+
+ if (status !== 200 || (failPageAfter && isNonEmptyString(cursor))) {
+ return sendJson(response, status !== 200 ? status : 403, {
+ message: 'Request denied',
+ });
+ }
+
+ if (isDefined(invalidPayload)) {
+ return sendJson(response, 200, invalidPayload);
+ }
+
+ const object = objects.find((candidate) =>
+ url.pathname.startsWith(`/rest/${candidate.namePlural}`),
+ );
+
+ if (!isDefined(object)) {
+ return sendJson(response, 404, {});
+ }
+
+ if (url.pathname !== `/rest/${object.namePlural}`) {
+ return sendJson(response, 200, { data: { [object.nameSingular]: record } });
+ }
+
+ const offset = Number(cursor ?? 0);
+ const limit = Number(url.searchParams.get('limit'));
+ const nextOffset = offset + limit;
+ const pageRecords = isDefined(cursorCycle)
+ ? records.slice(0, limit)
+ : records.slice(offset, nextOffset);
+ const getEndCursor = () => {
+ if (isDefined(cursorCycle)) {
+ return cursorCycle[(restRequests - 1) % cursorCycle.length];
+ }
+
+ return isNonEmptyArray(pageRecords)
+ ? String(Math.min(nextOffset, records.length))
+ : null;
+ };
+
+ return sendJson(response, 200, {
+ data: { [object.namePlural]: pageRecords },
+ totalCount: records.length,
+ pageInfo: {
+ hasPreviousPage: offset > 0,
+ hasNextPage: isDefined(cursorCycle) || nextOffset < records.length,
+ startCursor: isNonEmptyArray(pageRecords) ? String(offset) : null,
+ endCursor: getEndCursor(),
+ },
+ });
+});
+
+const getLastRequest = () => {
+ const lastRequest = server.requests.at(-1);
+
+ assertIsDefinedOrThrow(lastRequest);
+
+ return lastRequest;
+};
+
+const runJson = async (args: string[]) => {
+ const result = await runCliForTest(['data', ...args, '--json']);
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+
+const runStream = async (args: string[]) => {
+ const result = await runCliForTest([
+ 'data',
+ 'list',
+ ...args,
+ '--format',
+ 'ndjson',
+ ]);
+ return {
+ ...result,
+ events: result.stdout
+ .trimEnd()
+ .split('\n')
+ .map((line) => JSON.parse(line)),
+ };
+};
+
+describe('data inspection commands', () => {
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'fixture-data-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ objects = [company];
+ records = [
+ {
+ id: '1',
+ name: 'Acme',
+ employees: 100,
+ domainName: { primaryLinkUrl: 'acme.test' },
+ },
+ {
+ id: '2',
+ name: 'Twenty',
+ employees: 20,
+ domainName: { primaryLinkUrl: 'twenty.test' },
+ },
+ { id: '3', name: 'Example', employees: 5 },
+ ];
+ record = records[0];
+ status = 200;
+ metadataDenied = false;
+ failPageAfter = false;
+ invalidPayload = undefined;
+ cursorCycle = undefined;
+ restRequests = 0;
+ server.requests.length = 0;
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+ afterAll(() => server.close());
+
+ it('defaults to one page of 50, using canonical plural names and paired credentials', async () => {
+ records = Array.from({ length: 51 }, (_, index) => ({
+ id: String(index),
+ name: 'Company',
+ }));
+ const result = await runJson(['list', 'company']);
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.envelope.data.records).toHaveLength(50);
+ expect(result.envelope.data).toMatchObject({
+ totalCount: 51,
+ pageInfo: { hasNextPage: true, endCursor: '50' },
+ });
+ expect(restRequests).toBe(1);
+ expect(getLastRequest()).toMatchObject({
+ path: '/rest/companies?limit=50',
+ method: 'GET',
+ headers: { authorization: 'Bearer fixture-data-key' },
+ });
+ });
+
+ it('preserves REST filters, ordering and opaque cursor contents without interpreting them', async () => {
+ const filter = "name[eq]:A&B + O'Reilly";
+ const order = 'employees[DescNullsLast],id[AscNullsFirst]';
+ await runJson([
+ 'list',
+ 'companies',
+ '--filter',
+ filter,
+ '--order-by',
+ order,
+ '--limit',
+ '2',
+ '--cursor',
+ '1',
+ ]);
+ const url = new URL(getLastRequest().path, server.url);
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ limit: '2',
+ starting_after: '1',
+ filter,
+ order_by: order,
+ });
+ await runJson(['list', 'companies', '--cursor', 'opaque+/=&?']);
+ expect(
+ new URL(getLastRequest().path, server.url).searchParams.get(
+ 'starting_after',
+ ),
+ ).toBe('opaque+/=&?');
+ });
+
+ it('resolves custom objects for list and get without generated types', async () => {
+ objects = [
+ { id: 'invoice-object', nameSingular: 'invoice', namePlural: 'invoices' },
+ ];
+ expect((await runJson(['list', 'invoice'])).envelope.data.records).toEqual(
+ records,
+ );
+ const result = await runJson(['get', 'invoices', '1']);
+ expect(result.envelope.data).toEqual(record);
+ expect(getLastRequest().path).toBe('/rest/invoices/1?depth=1');
+ });
+
+ it('rejects ambiguous aliases before sending a REST request', async () => {
+ objects.push({
+ id: 'second',
+ nameSingular: 'companies',
+ namePlural: 'companies2',
+ });
+ const result = await runJson(['list', 'companies']);
+ expect(result.exitCode).toBe(2);
+ expect(result.envelope.error.code).toBe('AMBIGUOUS_RESOURCE');
+ expect(restRequests).toBe(0);
+ });
+
+ it.each(['Companies', 'COMPANIES', 'comp'])(
+ 'does not guess the object name %s',
+ async (name) => {
+ const result = await runJson(['list', name]);
+ expect(result.exitCode).toBe(4);
+ expect(restRequests).toBe(0);
+ },
+ );
+
+ it.each(['0', '-1', '201', '1.5', 'NaN', 'Infinity', '1e2', ''])(
+ 'rejects invalid page limit %s before network access',
+ async (limit) => {
+ const result = await runJson(['list', 'companies', '--limit', limit]);
+ expect(result.exitCode).toBe(2);
+ expect(result.envelope.error.code).toBe('USAGE');
+ expect(server.requests).toHaveLength(0);
+ },
+ );
+
+ it('accepts 200 as the page size', async () => {
+ expect(
+ (await runJson(['list', 'companies', '--limit', '200'])).exitCode,
+ ).toBe(0);
+ });
+
+ it.each([
+ ['--fields', 'name,'],
+ ['--cursor', ''],
+ ])('rejects empty values for %s', async (flag, value) => {
+ expect((await runJson(['list', 'companies', flag, value])).exitCode).toBe(
+ 2,
+ );
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it('collects every remaining page and retains final pagination information', async () => {
+ const result = await runJson([
+ 'list',
+ 'companies',
+ '--limit',
+ '1',
+ '--cursor',
+ '1',
+ '--all',
+ ]);
+ expect(result.envelope.data.records).toEqual(records.slice(1));
+ expect(result.envelope.data.pageInfo).toMatchObject({
+ hasNextPage: false,
+ endCursor: '3',
+ });
+ expect(
+ server.requests
+ .filter((request) => request.path.startsWith('/rest'))
+ .map((request) =>
+ new URL(request.path, server.url).searchParams.get('starting_after'),
+ ),
+ ).toEqual(['1', '2']);
+ });
+
+ it('keeps all fields in JSON while selecting only human table columns', async () => {
+ const result = await runJson(['list', 'companies', '--fields', 'name']);
+ expect(result.envelope.data.records[0]).toEqual(records[0]);
+ const human = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--fields',
+ 'name,domainName',
+ '--limit',
+ '1',
+ '--filter',
+ "name[eq]:O'Reilly",
+ '--order-by',
+ 'name',
+ ]);
+ expect(human.stdout).toContain('Acme');
+ expect(human.stdout).toContain('acme.test');
+ expect(human.stdout).not.toContain('employees');
+ expect(human.stdout).toContain(
+ '1 of 3 records · --all for every page · --json for the next cursor',
+ );
+ expect(human.stdout).not.toContain('--cursor');
+ const page = await runJson(['list', 'companies', '--limit', '1']);
+ expect(page.envelope.data.pageInfo).toMatchObject({
+ hasNextPage: true,
+ endCursor: '1',
+ });
+ });
+
+ it('returns an empty list with page information and useful human output', async () => {
+ records = [];
+ expect((await runJson(['list', 'companies'])).envelope.data).toEqual({
+ records: [],
+ totalCount: 0,
+ pageInfo: {
+ hasPreviousPage: false,
+ hasNextPage: false,
+ startCursor: null,
+ endCursor: null,
+ },
+ });
+ expect(
+ (await runCliForTest(['data', 'list', 'companies'])).stdout,
+ ).toContain('No records.');
+ });
+
+ it('shows composites and related records while preserving their raw JSON', async () => {
+ record = {
+ id: '1',
+ name: { firstName: 'Jane', lastName: 'Cooper' },
+ emails: { primaryEmail: '[email protected]' },
+ company: { id: '2', name: 'Acme' },
+ active: false,
+ nullable: null,
+ };
+ expect((await runJson(['get', 'companies', '1'])).envelope.data).toEqual(
+ record,
+ );
+ const human = await runCliForTest(['data', 'get', 'company', '1']);
+ expect(human.stdout).toContain('Jane Cooper');
+ expect(human.stdout).toContain('[email protected]');
+ expect(human.stdout).toContain('Acme (2)');
+ expect(human.stdout).toContain('false');
+ });
+
+ it('summarizes returned related records and bounds detail values in human output', async () => {
+ record = {
+ id: '1',
+ name: 'Acme',
+ people: [
+ {
+ id: 'p1',
+ name: { firstName: 'Jane', lastName: 'Cooper' },
+ notes: 'x'.repeat(5_000),
+ },
+ { id: 'p2', name: { firstName: 'Ann', lastName: 'Lee' } },
+ { id: 'p3', title: 'Buyer' },
+ { id: 'p4' },
+ ],
+ manager: { id: 'm1', title: 'Head of sales' },
+ taskTargets: [],
+ workPolicy: ['REMOTE_WORK', 'HYBRID'],
+ tagline: 'y'.repeat(5_000),
+ };
+
+ const human = await runCliForTest(['data', 'get', 'companies', '1']);
+ const lines = human.stdout.split('\n');
+
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout).toContain(
+ '4 records returned · Jane Cooper, Ann Lee, Buyer, …',
+ );
+ expect(human.stdout).toContain('Head of sales (m1)');
+ expect(human.stdout).toContain('REMOTE_WORK, HYBRID');
+ expect(lines.find((line) => line.includes('taskTargets'))).toMatch(
+ /taskTargets\s+-$/,
+ );
+ expect(human.stdout).toContain(`${'y'.repeat(119)}…`);
+ expect(human.stdout).not.toContain('x'.repeat(100));
+ expect(Math.max(...lines.map((line) => line.length))).toBeLessThan(160);
+ expect((await runJson(['get', 'companies', '1'])).envelope.data).toEqual(
+ record,
+ );
+ });
+
+ it('warns once in human output when no returned record has a requested field', async () => {
+ const human = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--fields',
+ 'name,nope',
+ ]);
+ const all = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '1',
+ '--fields',
+ 'nope',
+ ]);
+ const json = await runJson(['list', 'companies', '--fields', 'nope']);
+
+ records = [];
+
+ const empty = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--fields',
+ 'nope',
+ ]);
+
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout).toContain('Acme');
+ expect(human.stderr).toContain(
+ 'No returned record has nope; see twenty metadata field list companies.',
+ );
+ expect(all.stderr.match(/No returned record has nope/g)).toHaveLength(1);
+ expect(json.envelope.warnings).toEqual([]);
+ expect(empty.stderr).not.toContain('No returned record');
+ });
+
+ it('escapes record control characters in human tables without altering JSON', async () => {
+ records = [{ id: '1', name: 'Acme\n\u001b[31m' }];
+ const result = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--fields',
+ 'name',
+ ]);
+ expect(result.stdout).toContain('Acme\\n\\u001b[31m');
+ expect(
+ (await runJson(['list', 'companies'])).envelope.data.records,
+ ).toEqual(records);
+ });
+
+ it.each([
+ [401, 3],
+ [403, 3],
+ [404, 4],
+ [429, 1],
+ [500, 1],
+ ])('preserves HTTP %s failures', async (responseStatus, expectedExitCode) => {
+ status = responseStatus;
+ const result = await runJson(['get', 'companies', '1']);
+ expect(result.envelope.ok).toBe(false);
+ expect(result.envelope.error.details.status).toBe(responseStatus);
+ expect(result.exitCode).toBe(expectedExitCode);
+ expect(restRequests).toBe(1);
+ });
+
+ it('bounds table cell widths and treats absent columns as absent values', async () => {
+ records = [
+ { id: '1', name: 'x'.repeat(100_000) },
+ { id: '2', name: 'Short' },
+ ];
+ const result = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--fields',
+ 'name,toString',
+ ]);
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout.length).toBeLessThan(300);
+ expect(result.stdout).toContain('x'.repeat(59) + '…');
+ expect(result.stdout).toContain('Short');
+ expect(result.stdout).toContain('-');
+ });
+
+ it('rejects a REST page that exceeds the requested page size', async () => {
+ invalidPayload = {
+ data: { companies: records },
+ totalCount: records.length,
+ pageInfo: { hasNextPage: false, startCursor: '0', endCursor: '3' },
+ };
+ expect(
+ (await runJson(['list', 'companies', '--limit', '1'])).envelope.error
+ .code,
+ ).toBe('INVALID_RESPONSE');
+ });
+
+ it('rejects a non-progressing final page instead of claiming completion', async () => {
+ invalidPayload = {
+ data: { companies: [records[0]] },
+ totalCount: 3,
+ pageInfo: { hasNextPage: false, startCursor: '1', endCursor: '1' },
+ };
+ const result = await runJson([
+ 'list',
+ 'companies',
+ '--cursor',
+ '1',
+ '--all',
+ ]);
+ expect(result.envelope.error.code).toBe('INVALID_RESPONSE');
+ });
+
+ it('rejects malformed single-record responses', async () => {
+ record = [];
+ expect((await runJson(['get', 'companies', '1'])).envelope.error.code).toBe(
+ 'INVALID_RESPONSE',
+ );
+ });
+
+ it('maps a null single-record response to NOT_FOUND', async () => {
+ record = null;
+ expect((await runJson(['get', 'companies', '1'])).exitCode).toBe(4);
+ });
+
+ it('encodes record ids as one path segment and rejects traversal segments', async () => {
+ await runJson(['get', 'companies', 'a/b?c=d#e']);
+ expect(getLastRequest().path).toBe(
+ '/rest/companies/a%2Fb%3Fc%3Dd%23e?depth=1',
+ );
+ for (const id of ['.', '..']) {
+ expect((await runJson(['get', 'companies', id])).exitCode).toBe(2);
+ }
+ expect(restRequests).toBe(1);
+ });
+
+ it('preserves metadata permission errors without trying REST', async () => {
+ metadataDenied = true;
+ expect((await runJson(['list', 'companies'])).exitCode).toBe(3);
+ expect(restRequests).toBe(0);
+ });
+
+ it('fetches object metadata afresh on each invocation', async () => {
+ expect((await runJson(['list', 'companies'])).exitCode).toBe(0);
+ metadataDenied = true;
+ expect((await runJson(['list', 'companies'])).exitCode).toBe(3);
+ expect(restRequests).toBe(1);
+ });
+
+ it.each([
+ {},
+ {
+ data: { companies: null },
+ totalCount: 0,
+ pageInfo: { hasNextPage: false, startCursor: null, endCursor: null },
+ },
+ { data: { companies: [] }, totalCount: 0, pageInfo: {} },
+ {
+ data: { companies: [] },
+ totalCount: 0,
+ pageInfo: { hasNextPage: true, startCursor: null, endCursor: null },
+ },
+ {
+ data: { companies: [{}] },
+ totalCount: 1,
+ pageInfo: { hasNextPage: true, startCursor: '0', endCursor: '' },
+ },
+ {
+ data: { companies: [null] },
+ totalCount: 1,
+ pageInfo: { hasNextPage: false, startCursor: null, endCursor: null },
+ },
+ ])('fails explicitly on malformed REST pagination %#', async (payload) => {
+ invalidPayload = payload;
+ const result = await runJson(['list', 'companies', '--all']);
+ expect(result.envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(result.exitCode).toBe(1);
+ });
+
+ it.each([['1'], ['1', '2', '3']])(
+ 'detects pagination cycles without a successful partial result %#',
+ async (...cycle) => {
+ cursorCycle = cycle;
+ const result = await runJson(['list', 'companies', '--all']);
+ expect(result.envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(restRequests).toBeLessThan(12);
+ },
+ );
+
+ it('fails finite JSON on page-two errors without leaking a partial success', async () => {
+ failPageAfter = true;
+ const result = await runJson([
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '1',
+ ]);
+ expect(result.exitCode).toBe(3);
+ expect(result.envelope.error.code).toBe('PERMISSION_DENIED');
+ expect(result.envelope.data).toBeUndefined();
+ });
+
+ it('rejects results over 10,000 records in JSON and human modes', async () => {
+ records = Array.from({ length: 10_001 }, (_, index) => ({
+ id: String(index),
+ }));
+ const json = await runJson([
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '200',
+ ]);
+ expect(json.exitCode).toBe(2);
+ expect(json.envelope.error).toMatchObject({
+ code: 'RESULT_LIMIT_EXCEEDED',
+ details: { recordCount: 10_001 },
+ });
+ expect(json.envelope.error.hint).toContain('--format ndjson');
+ const human = await runCliForTest([
+ 'data',
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '200',
+ ]);
+ expect(human.exitCode).toBe(2);
+ expect(human.stdout).toBe('');
+ });
+
+ it('accepts exactly 10,000 records in a finite result', async () => {
+ records = Array.from({ length: 10_000 }, (_, index) => ({
+ id: String(index),
+ }));
+ const result = await runJson([
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '200',
+ ]);
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.envelope.data.records).toHaveLength(10_000);
+ });
+
+ it('bounds combined payload bytes across individually valid pages', async () => {
+ records = [
+ { id: '1', text: 'x'.repeat(9 * 1024 * 1024) },
+ { id: '2', text: 'x'.repeat(9 * 1024 * 1024) },
+ ];
+ const result = await runJson([
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '1',
+ ]);
+ expect(result.envelope.error.code).toBe('RESULT_LIMIT_EXCEEDED');
+ expect(result.envelope.error.details.bytes).toBeGreaterThan(
+ 16 * 1024 * 1024,
+ );
+ expect(result.exitCode).toBe(2);
+ });
+
+ it('still enforces the per-response transport cap in streaming mode', async () => {
+ records = [{ id: '1', text: 'x'.repeat(17 * 1024 * 1024) }];
+ const result = await runStream(['companies', '--all']);
+ expect(result.exitCode).toBe(1);
+ expect(result.events.at(-1)).toMatchObject({
+ type: 'error',
+ data: { code: 'RESPONSE_LIMIT_EXCEEDED' },
+ });
+ expect(result.events.some((event) => event.type === 'record')).toBe(false);
+ });
+
+ it('streams numbered events beyond the finite item limit and terminates once', async () => {
+ records = Array.from({ length: 10_001 }, (_, index) => ({
+ id: String(index),
+ fullRecord: true,
+ }));
+ const result = await runStream([
+ 'companies',
+ '--all',
+ '--limit',
+ '200',
+ '--fields',
+ 'id',
+ ]);
+ expect(result.exitCode, result.stdout).toBe(0);
+ expect(result.events[0]).toMatchObject({
+ type: 'start',
+ data: { object: 'companies', target: { apiUrl: server.url } },
+ });
+ expect(
+ result.events.filter((event) => event.type === 'record'),
+ ).toHaveLength(10_001);
+ expect(result.events[1].data).toEqual(records[0]);
+ expect(result.events.at(-1)).toMatchObject({
+ type: 'result',
+ data: {
+ recordCount: 10_001,
+ pages: 51,
+ pageInfo: { hasNextPage: false },
+ },
+ });
+ expect(
+ result.events.filter((event) => ['result', 'error'].includes(event.type)),
+ ).toHaveLength(1);
+ expect(
+ result.events.every(
+ (event, index) =>
+ event.sequence === index + 1 &&
+ event.schemaVersion === 1 &&
+ event.command === 'data list',
+ ),
+ ).toBe(true);
+ });
+
+ it('preserves delivered records and a completed-page cursor when a later page fails', async () => {
+ failPageAfter = true;
+ const result = await runStream(['companies', '--all', '--limit', '1']);
+ expect(result.exitCode).toBe(3);
+ expect(
+ result.events
+ .filter((event) => event.type === 'record')
+ .map((event) => event.data),
+ ).toEqual([records[0]]);
+ expect(result.events.at(-1)).toMatchObject({
+ type: 'error',
+ data: {
+ code: 'PERMISSION_DENIED',
+ details: { recordCount: 1, pages: 1, resumeCursor: '1' },
+ },
+ });
+ expect(result.events.some((event) => event.type === 'result')).toBe(false);
+ });
+
+ it('streams only one page without --all', async () => {
+ const result = await runStream(['companies', '--limit', '1']);
+ expect(restRequests).toBe(1);
+ expect(result.events.at(-1).data.pageInfo.hasNextPage).toBe(true);
+ });
+
+ it.each([false, true])(
+ 'stops fetching under stdout backpressure, cancel=%s',
+ async (cancel) => {
+ let stdout = '';
+ const blocked = Promise.withResolvers<void>();
+ const stdoutSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation((chunk) => {
+ stdout += String(chunk);
+ if (stdout.trimEnd().split('\n').length === 2) {
+ blocked.resolve();
+ return false;
+ }
+ return true;
+ });
+ const previousExitCode = process.exitCode;
+ process.exitCode = undefined;
+
+ try {
+ const pending = runCli([
+ 'data',
+ 'list',
+ 'companies',
+ '--all',
+ '--limit',
+ '1',
+ '--format',
+ 'ndjson',
+ ]);
+ await blocked.promise;
+ await setImmediate();
+ await setImmediate();
+ expect(restRequests).toBe(1);
+ if (cancel) {
+ process.emit('SIGINT');
+ } else {
+ process.stdout.emit('drain');
+ }
+ await pending;
+ const events = stdout
+ .trimEnd()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ if (cancel) {
+ expect(Number(process.exitCode)).toBe(130);
+ expect(events.at(-1)).toMatchObject({
+ type: 'error',
+ data: {
+ code: 'CANCELLED',
+ details: { pages: 0, resumeCursor: null },
+ },
+ });
+ expect(restRequests).toBe(1);
+ } else {
+ expect(restRequests).toBe(3);
+ expect(events.at(-1).type).toBe('result');
+ }
+ } finally {
+ stdoutSpy.mockRestore();
+ process.exitCode = previousExitCode;
+ }
+ },
+ );
+
+ it('advertises only the implemented output modes and works without credentials for help', async () => {
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ const help = await runCliForTest(['data', 'list', '--help']);
+ expect(help.exitCode).toBe(0);
+ expect(help.stdout).toContain('--cursor');
+ const commands = parseSingleJsonLine(
+ (await runCliForTest(['commands', '--json'])).stdout,
+ ).data.commands;
+ expect(
+ commands.find(
+ (command: { name: string }) => command.name === 'data list',
+ ),
+ ).toMatchObject({
+ outputs: ['human', 'json', 'ndjson'],
+ writes: false,
+ needsProject: false,
+ });
+ expect(
+ (
+ await runCliForTest([
+ 'data',
+ 'get',
+ 'companies',
+ '1',
+ '--format',
+ 'ndjson',
+ ])
+ ).exitCode,
+ ).toBe(2);
+ expect(server.requests).toHaveLength(0);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/data/get/data-get.command-definition.ts b/packages/twenty-cli/src/commands/data/get/data-get.command-definition.ts
new file mode 100644
index 00000000000..f488e224807
--- /dev/null
+++ b/packages/twenty-cli/src/commands/data/get/data-get.command-definition.ts
@@ -0,0 +1,25 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const DATA_GET_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['data', 'get'],
+ description: 'Inspect a record by id',
+ arguments: [
+ {
+ name: 'object',
+ description: 'Exact singular or plural API name',
+ required: true,
+ },
+ { name: 'id', description: 'Record id', required: true },
+ ],
+ examples: [
+ 'twenty data get companies <id>',
+ 'twenty data get people <id> --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/data/get/run-data-get-command'))
+ .runDataGetCommand,
+};
diff --git a/packages/twenty-cli/src/commands/data/get/run-data-get-command.ts b/packages/twenty-cli/src/commands/data/get/run-data-get-command.ts
new file mode 100644
index 00000000000..fa2d3b0c26a
--- /dev/null
+++ b/packages/twenty-cli/src/commands/data/get/run-data-get-command.ts
@@ -0,0 +1,54 @@
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataCell, formatDataDetail } from '@/data/format-data-value';
+import { parseDataRecord } from '@/data/parse-data-response';
+import { resolveMetadataObject } from '@/metadata/resolve-metadata-object';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatDetails } from '@/output/format-details';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+import { createRestClient } from '@/transport/rest/create-rest-client';
+
+export const runDataGetCommand: CommandRun<TargetCommandContext> = async ({
+ arguments: commandArguments,
+ target,
+ signal,
+ outputMode,
+}) => {
+ const id = readStringArgument(commandArguments, 1) ?? '';
+
+ if (id.length === 0 || id === '.' || id === '..') {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'A record id is required.',
+ });
+ }
+
+ const object = await resolveMetadataObject({
+ client: createMetadataClient({ target, signal }),
+ name: readStringArgument(commandArguments, 0) ?? '',
+ });
+ const record = parseDataRecord(
+ await createRestClient({ target, signal }).get(
+ `/rest/${encodeURIComponent(object.namePlural)}/${encodeURIComponent(id)}`,
+ { query: { depth: 1 } },
+ ),
+ object.nameSingular,
+ );
+
+ return {
+ data: record,
+ ...(outputMode === 'human'
+ ? {
+ human: formatDetails(
+ Object.entries(record).map(([name, value]) => [
+ formatDataCell(name),
+ formatDataDetail(value),
+ ]),
+ ),
+ }
+ : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/data/list/data-list.command-definition.ts b/packages/twenty-cli/src/commands/data/list/data-list.command-definition.ts
new file mode 100644
index 00000000000..bc45befad78
--- /dev/null
+++ b/packages/twenty-cli/src/commands/data/list/data-list.command-definition.ts
@@ -0,0 +1,53 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const DATA_LIST_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['data', 'list'],
+ description: 'List records with REST filters and pagination',
+ arguments: [
+ {
+ name: 'object',
+ description: 'Exact singular or plural API name',
+ required: true,
+ },
+ ],
+ options: [
+ {
+ flags: '--filter <expression>',
+ description: 'REST filter expression, passed through unchanged',
+ },
+ {
+ flags: '--order-by <expression>',
+ description: 'REST order_by expression, passed through unchanged',
+ },
+ {
+ flags: '--fields <names>',
+ description:
+ 'Comma-separated human table columns; JSON and NDJSON retain full records',
+ },
+ {
+ flags: '--limit <count>',
+ description: 'Records per page, 1–200 (default: 50)',
+ },
+ {
+ flags: '--cursor <cursor>',
+ description: 'Start after this opaque REST cursor',
+ },
+ {
+ flags: '--all',
+ description:
+ 'Read every remaining page, bounded unless --format ndjson is used',
+ },
+ ],
+ examples: [
+ 'twenty data list companies --limit 20',
+ "twenty data list companies --filter 'employees[gte]:5000' --order-by 'employees[DescNullsLast]'",
+ 'twenty data list people --all --format ndjson',
+ ],
+ outputModes: ['human', 'json', 'ndjson'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/data/list/run-data-list-command'))
+ .runDataListCommand,
+};
diff --git a/packages/twenty-cli/src/commands/data/list/run-data-list-command.ts b/packages/twenty-cli/src/commands/data/list/run-data-list-command.ts
new file mode 100644
index 00000000000..a4043e0c792
--- /dev/null
+++ b/packages/twenty-cli/src/commands/data/list/run-data-list-command.ts
@@ -0,0 +1,161 @@
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { assertDataResultLimit } from '@/data/assert-data-result-limit';
+import { formatDataPage } from '@/data/format-data-page';
+import { iterateDataPages } from '@/data/iterate-data-pages';
+import { parseDataPage } from '@/data/parse-data-response';
+import { readDataListOptions } from '@/data/read-data-list-options';
+import {
+ type DataPageInfo,
+ type DataRecord,
+} from '@/data/types/data-page.type';
+import { resolveMetadataObject } from '@/metadata/resolve-metadata-object';
+import { CliError } from '@/output/cli-error';
+import { toCliError } from '@/output/to-cli-error';
+import { toPublicTarget } from '@/target/to-public-target';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+import { createRestClient } from '@/transport/rest/create-rest-client';
+
+export const runDataListCommand: CommandRun<TargetCommandContext> = async ({
+ arguments: commandArguments,
+ options,
+ target,
+ signal,
+ output,
+ outputMode,
+}) => {
+ const listOptions = readDataListOptions(options);
+ const object = await resolveMetadataObject({
+ client: createMetadataClient({ target, signal }),
+ name: readStringArgument(commandArguments, 0) ?? '',
+ });
+ const client = createRestClient({ target, signal });
+ const isStreaming = outputMode === 'ndjson';
+ const records: DataRecord[] = [];
+ let recordCount = 0;
+ let pages = 0;
+ let recordBytes = 0;
+ let resumeCursor = listOptions.cursor ?? null;
+ let pageInfo: DataPageInfo = {
+ hasNextPage: false,
+ startCursor: null,
+ endCursor: null,
+ };
+ let totalCount = 0;
+
+ try {
+ if (isStreaming) {
+ await output.event(
+ 'start',
+ { object: object.namePlural, target: toPublicTarget(target) },
+ signal,
+ );
+ }
+
+ for await (const page of iterateDataPages({
+ cursor: listOptions.cursor,
+ signal,
+ fetchPage: async (cursor) =>
+ parseDataPage(
+ await client.get(`/rest/${encodeURIComponent(object.namePlural)}`, {
+ query: {
+ limit: listOptions.limit,
+ starting_after: cursor,
+ filter: listOptions.filter,
+ order_by: listOptions.orderBy,
+ },
+ }),
+ object.namePlural,
+ listOptions.limit,
+ ),
+ })) {
+ for (const record of page.records) {
+ if (isStreaming) {
+ await output.event('record', record, signal);
+ } else {
+ recordBytes += Buffer.byteLength(JSON.stringify(record), 'utf8');
+ assertDataResultLimit({
+ recordCount: recordCount + 1,
+ bytes:
+ recordBytes +
+ recordCount +
+ Buffer.byteLength(
+ JSON.stringify({
+ records: [],
+ pageInfo: page.pageInfo,
+ totalCount: page.totalCount,
+ }),
+ 'utf8',
+ ),
+ });
+ records.push(record);
+ }
+
+ recordCount += 1;
+ }
+
+ pages += 1;
+ pageInfo = page.pageInfo;
+ totalCount = page.totalCount;
+ resumeCursor = pageInfo.endCursor ?? resumeCursor;
+
+ if (isStreaming) {
+ await output.event(
+ 'progress',
+ { recordCount, pages, resumeCursor, pageInfo, totalCount },
+ signal,
+ );
+ }
+
+ if (!listOptions.all) {
+ break;
+ }
+ }
+ } catch (error) {
+ const failure = toCliError(error, signal);
+
+ if (!isStreaming) {
+ throw failure;
+ }
+
+ throw new CliError({
+ code: failure.code,
+ exitCode: failure.exitCode,
+ message: failure.message,
+ hint: failure.hint,
+ details: { ...failure.details, recordCount, pages, resumeCursor },
+ });
+ }
+
+ if (isStreaming) {
+ return { data: { recordCount, pages, resumeCursor, pageInfo, totalCount } };
+ }
+
+ const page = { records, pageInfo, totalCount };
+ const absentFields =
+ outputMode === 'human' && records.length > 0
+ ? (listOptions.fields ?? []).filter(
+ (field) => !records.some((record) => Object.hasOwn(record, field)),
+ )
+ : [];
+
+ if (absentFields.length > 0) {
+ output.warn({
+ code: 'FIELDS_NOT_RETURNED',
+ message: `No returned record has ${absentFields.join(', ')}; see twenty metadata field list ${object.namePlural}.`,
+ });
+ }
+
+ return {
+ data: page,
+ ...(outputMode === 'human'
+ ? {
+ human: formatDataPage({
+ page,
+ options: listOptions,
+ }),
+ }
+ : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/doctor/__tests__/doctor.spec.ts b/packages/twenty-cli/src/commands/doctor/__tests__/doctor.spec.ts
new file mode 100644
index 00000000000..45109bfe0d0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/doctor/__tests__/doctor.spec.ts
@@ -0,0 +1,764 @@
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+vi.mock('@/transport/constants/request-timeout-milliseconds.constant', () => ({
+ REQUEST_TIMEOUT_MILLISECONDS: 500,
+}));
+
+const API_KEY = 'doctor-test-secret-key';
+const REFRESH_TOKEN = 'doctor-test-secret-refresh';
+
+describe('doctor', () => {
+ let root: string;
+ let configPath: string;
+ let servers: Awaited<ReturnType<typeof startTestServer>>[];
+
+ const runJson = async (options: string[] = []) => {
+ const result = await runCliForTest(['doctor', ...options, '--json']);
+ const envelope = parseSingleJsonLine(result.stdout);
+
+ return {
+ ...result,
+ envelope,
+ checks: envelope.ok
+ ? envelope.data.checks
+ : envelope.error.details?.checks,
+ };
+ };
+
+ const saveConfig = async (config: unknown) => {
+ await mkdir(join(root, '.twenty'), { recursive: true });
+ await writeFile(configPath, JSON.stringify(config));
+ };
+
+ const createApp = async (packageFields: Record<string, unknown> = {}) => {
+ const appPath = join(root, 'app');
+ const sdkPath = join(appPath, 'node_modules', 'twenty-sdk');
+
+ await mkdir(sdkPath, { recursive: true });
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'doctor-app',
+ devDependencies: { 'twenty-sdk': '9.9.9' },
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version: '9.9.9',
+ exports: {
+ './define': './build.cjs',
+ './front-component': './build.cjs',
+ },
+ ...packageFields,
+ }),
+ );
+ await writeFile(
+ join(sdkPath, 'build.cjs'),
+ "throw new Error('Doctor must not import the SDK');",
+ );
+
+ return { appPath, sdkPath };
+ };
+
+ const startWorkspace = async (
+ mode: 'success' | 'reject' | 'invalid' | 'hang' = 'success',
+ ) => {
+ const server = await startTestServer((request, response) => {
+ if (mode === 'hang') {
+ return;
+ }
+
+ if (mode === 'reject') {
+ return sendJson(response, 200, {
+ errors: [
+ {
+ message: `Rejected ${API_KEY} ${REFRESH_TOKEN}`,
+ extensions: { code: 'UNAUTHENTICATED' },
+ },
+ ],
+ data: null,
+ });
+ }
+
+ if (mode === 'invalid') {
+ return sendJson(response, 200, { unexpected: API_KEY });
+ }
+
+ return sendJson(response, 200, {
+ data: {
+ currentWorkspace: { displayName: API_KEY },
+ currentUser: { email: REFRESH_TOKEN },
+ },
+ });
+ });
+
+ servers.push(server);
+
+ return server;
+ };
+
+ beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'twenty-doctor-'));
+ configPath = join(root, '.twenty', 'config.json');
+ servers = [];
+ vi.stubEnv('HOME', root);
+ vi.stubEnv('PATH', join(root, 'bin'));
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.spyOn(process, 'cwd').mockReturnValue(root);
+ });
+
+ afterEach(async () => {
+ for (const server of servers) {
+ await server.close();
+ }
+
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('works without an app or credentials and explains skipped checks', async () => {
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'node', status: 'pass' }),
+ expect.objectContaining({ id: 'cli', status: 'pass' }),
+ expect.objectContaining({ id: 'project', status: 'skipped' }),
+ expect.objectContaining({ id: 'metadata-api', status: 'skipped' }),
+ ]),
+ );
+ await expect(readFile(configPath)).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+
+ const human = await runCliForTest(['doctor']);
+
+ expect(human.stdout).toContain('[SKIPPED] project:');
+ expect(human.stdout).toContain('[PASS] node:');
+ });
+
+ it('checks public SDK exports without importing or requiring a build API', async () => {
+ const { appPath } = await createApp();
+ const result = await runJson(['--path', appPath]);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'sdk',
+ status: 'pass',
+ details: expect.objectContaining({
+ version: '9.9.9',
+ }),
+ }),
+ );
+ await expect(
+ readFile(join(appPath, '.twenty', 'output', 'manifest.json')),
+ ).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('collects broken config and missing SDK failures without exposing config contents', async () => {
+ const { appPath, sdkPath } = await createApp();
+
+ await rm(sdkPath, { recursive: true });
+ await saveConfig({});
+ const invalid = `{ ${API_KEY} ${REFRESH_TOKEN}`;
+
+ await writeFile(configPath, invalid);
+ const result = await runJson(['--path', appPath]);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.envelope.error.code).toBe('DOCTOR_FAILED');
+ expect(result.checks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: 'sdk',
+ status: 'fail',
+ code: 'SDK_NOT_INSTALLED',
+ }),
+ expect.objectContaining({
+ id: 'configuration',
+ status: 'fail',
+ message: expect.stringContaining('invalid JSON at line 1, column'),
+ }),
+ ]),
+ );
+ expect(result.stdout).not.toContain(API_KEY);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+ expect(await readFile(configPath, 'utf8')).toBe(invalid);
+
+ const human = await runCliForTest(['doctor', '--path', appPath]);
+ const [failureLine, ...checklistLines] = human.stderr.trimEnd().split('\n');
+
+ expect(failureLine).toContain('doctor checks failed.');
+ expect(checklistLines.filter((line) => !line.startsWith(' '))).toEqual([]);
+ expect(human.stderr).toContain('\n [FAIL] sdk:');
+ expect(human.stderr).toContain('\n [FAIL] configuration:');
+ expect(human.stderr).not.toContain(API_KEY);
+ });
+
+ it('explains unsupported authoring SDK versions', async () => {
+ const { appPath } = await createApp({ version: '1.22.0' });
+ const result = await runJson(['--path', appPath]);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'sdk',
+ status: 'fail',
+ code: 'SDK_SOURCE_UNSUPPORTED',
+ hint: 'Install a compatible twenty-sdk version in this app.',
+ }),
+ );
+ });
+
+ it('does not warn about a missing SDK build API or project-local CLI', async () => {
+ const { appPath } = await createApp();
+ const result = await runJson(['--path', appPath]);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).not.toContainEqual(
+ expect.objectContaining({ id: 'sdk-capabilities' }),
+ );
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'cli',
+ status: 'pass',
+ details: expect.objectContaining({
+ entryPoint: process.argv[1],
+ nodeExecutable: process.execPath,
+ version: expect.any(String),
+ }),
+ }),
+ );
+ });
+
+ it('reports an unknown explicit remote while retaining the local checks', async () => {
+ const result = await runJson(['--remote', 'missing']);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'cli', status: 'pass' }),
+ expect.objectContaining({
+ id: 'target',
+ status: 'fail',
+ code: 'UNKNOWN_REMOTE',
+ }),
+ ]),
+ );
+ });
+
+ it('warns about shared config permissions without changing them', async () => {
+ await saveConfig({ version: 1, remotes: {} });
+ await chmod(configPath, 0o644);
+ const result = await runJson(['--offline']);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'configuration-permissions',
+ status: 'warning',
+ }),
+ );
+ const again = await runJson(['--offline']);
+
+ expect(again.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'configuration-permissions',
+ status: 'warning',
+ }),
+ );
+ });
+
+ it('reports an incompatible SDK Node requirement', async () => {
+ const { appPath } = await createApp({ engines: { node: '>=99.0.0' } });
+ const result = await runJson(['--path', appPath]);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'sdk',
+ status: 'fail',
+ code: 'NODE_VERSION_UNSUPPORTED',
+ }),
+ );
+ });
+
+ it('still checks the workspace when an explicit app path is invalid', async () => {
+ const server = await startWorkspace();
+
+ vi.stubEnv('TWENTY_API_URL', `${server.url}/prefix`);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson(['--path', join(root, 'missing')]);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'project', status: 'fail' }),
+ expect.objectContaining({ id: 'metadata-api', status: 'pass' }),
+ ]),
+ );
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0].path).toBe('/prefix/metadata');
+ expect(server.requests[0].headers.authorization).toBe(`Bearer ${API_KEY}`);
+ expect(result.stdout).not.toContain(API_KEY);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+ });
+
+ it.each(['reject', 'invalid'] as const)(
+ 'redacts a %s server response',
+ async (mode) => {
+ const server = await startWorkspace(mode);
+
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({ id: 'metadata-api', status: 'fail' }),
+ );
+ expect(result.stdout).not.toContain(API_KEY);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+
+ if (mode === 'reject') {
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ hint: 'Check TWENTY_API_KEY.',
+ }),
+ );
+ }
+
+ const human = await runCliForTest(['doctor']);
+
+ expect(human.stderr).toContain('[FAIL] metadata-api:');
+ expect(human.stdout + human.stderr).not.toContain(API_KEY);
+ expect(human.stdout + human.stderr).not.toContain(REFRESH_TOKEN);
+ },
+ );
+
+ it.each(['apiKey', 'oauth'] as const)(
+ 'gives the correct sign-in command for rejected %s credentials',
+ async (credentialKind) => {
+ const server = await startWorkspace('reject');
+ const token = `header.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url')}.signature`;
+
+ await saveConfig({
+ version: 1,
+ remotes: {
+ staging: {
+ apiUrl: server.url,
+ ...(credentialKind === 'apiKey'
+ ? { apiKey: API_KEY }
+ : {
+ twentyCLIAccessToken: token,
+ twentyCLIRefreshToken: REFRESH_TOKEN,
+ }),
+ },
+ },
+ });
+ const result = await runJson(['--remote', 'staging']);
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ code: 'AUTH_REQUIRED',
+ hint: `Sign in again: twenty auth login --remote staging${credentialKind === 'apiKey' ? ' --with-token' : ''}`,
+ }),
+ );
+ expect(server.requests).toHaveLength(1);
+ expect(result.stdout).not.toContain(token);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+ },
+ );
+
+ it.each([
+ ['ENOTFOUND', 'DNS could not resolve'],
+ ['ECONNREFUSED', 'refused the connection'],
+ ['CERT_HAS_EXPIRED', 'TLS certificate has expired'],
+ [API_KEY, 'Could not connect'],
+ ])(
+ 'explains network error %s without exposing arbitrary error text',
+ async (networkCode, expectedMessage) => {
+ vi.stubEnv('TWENTY_API_URL', 'https://example.invalid');
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(
+ new TypeError('fetch failed', {
+ cause: Object.assign(new Error(`Failure ${API_KEY}`), {
+ code: networkCode,
+ }),
+ }),
+ );
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ code: 'NETWORK_ERROR',
+ message: expect.stringContaining(expectedMessage),
+ }),
+ );
+ expect(result.stdout).not.toContain(API_KEY);
+ const human = await runCliForTest(['doctor']);
+
+ expect(human.stderr).toContain(expectedMessage);
+ expect(human.stdout + human.stderr).not.toContain(API_KEY);
+ },
+ );
+
+ it('does not make network requests in offline mode', async () => {
+ vi.stubEnv('TWENTY_API_URL', 'https://example.invalid');
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const result = await runJson(['--offline']);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({ id: 'metadata-api', status: 'skipped' }),
+ );
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it('diagnoses a stopped local server through the real fetch transport', async () => {
+ const server = await startWorkspace();
+ const url = new URL(server.url);
+
+ url.hostname = 'localhost';
+ await server.close();
+ vi.stubEnv('TWENTY_API_URL', url.href);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ code: 'NETWORK_ERROR',
+ message: 'The metadata endpoint refused the connection.',
+ details: { networkCode: 'ECONNREFUSED' },
+ }),
+ );
+ expect(result.stdout).not.toContain(API_KEY);
+ });
+
+ it('does not forward credentials across a redirect', async () => {
+ const destination = await startWorkspace();
+ const redirect = await startTestServer((_request, response) => {
+ response.writeHead(302, { location: `${destination.url}/metadata` });
+ response.end();
+ });
+
+ servers.push(redirect);
+ vi.stubEnv('TWENTY_API_URL', redirect.url);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ status: 'fail',
+ code: 'REDIRECT_NOT_FOLLOWED',
+ }),
+ );
+ expect(destination.requests).toHaveLength(0);
+ expect(result.stdout).not.toContain(API_KEY);
+ });
+
+ it('keeps failed JSON diagnostics free of ANSI even when color is forced', async () => {
+ vi.stubEnv('FORCE_COLOR', '1');
+ const result = await runJson(['--remote', 'missing']);
+
+ expect(result.exitCode).toBe(1);
+ expect(JSON.stringify(result.envelope)).not.toContain('\\u001b');
+ expect(result.stderr).toBe('');
+ });
+
+ it('does not echo credentials reflected in a redirect hostname', async () => {
+ const redirect = await startTestServer((_request, response) => {
+ response.writeHead(302, {
+ location: `https://${API_KEY}.example.test/metadata`,
+ });
+ response.end();
+ });
+
+ servers.push(redirect);
+ vi.stubEnv('TWENTY_API_URL', redirect.url);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ code: 'REDIRECT_NOT_FOLLOWED',
+ }),
+ );
+ expect(result.stdout).not.toContain(API_KEY);
+ const human = await runCliForTest(['doctor']);
+
+ expect(human.stdout + human.stderr).not.toContain(API_KEY);
+ });
+
+ it.each([true, false])(
+ 'reports expired OAuth credentials without refreshing (saved refresh token: %s)',
+ async (hasRefreshToken) => {
+ const server = await startWorkspace();
+ const token = `header.${Buffer.from(JSON.stringify({ exp: 1 })).toString('base64url')}.signature`;
+ const config = {
+ version: 1,
+ defaultRemote: 'prod',
+ remotes: {
+ prod: {
+ apiUrl: server.url,
+ twentyCLIAccessToken: token,
+ twentyCLIRefreshToken: hasRefreshToken ? REFRESH_TOKEN : undefined,
+ apiKey: API_KEY,
+ },
+ },
+ };
+
+ await saveConfig(config);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(hasRefreshToken ? 0 : 1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'credentials',
+ status: hasRefreshToken ? 'warning' : 'fail',
+ code: 'AUTH_REQUIRED',
+ }),
+ );
+ expect(server.requests).toHaveLength(0);
+ expect(result.stdout).not.toContain(token);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+ expect(await readFile(configPath, 'utf8')).toBe(JSON.stringify(config));
+ },
+ );
+
+ it('uses an unexpired OAuth token without refreshing it or printing user information', async () => {
+ const server = await startWorkspace();
+ const token = `header.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 30 })).toString('base64url')}.signature`;
+ const config = {
+ version: 1,
+ defaultRemote: 'prod',
+ remotes: {
+ prod: {
+ apiUrl: server.url,
+ twentyCLIAccessToken: token,
+ twentyCLIRefreshToken: REFRESH_TOKEN,
+ },
+ },
+ };
+
+ await saveConfig(config);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(0);
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0].headers.authorization).toBe(`Bearer ${token}`);
+ expect(result.stdout).not.toContain(token);
+ expect(result.stdout).not.toContain(REFRESH_TOKEN);
+ expect(await readFile(configPath, 'utf8')).toBe(JSON.stringify(config));
+ });
+
+ it('keeps explicit remote precedence without mixing environment credentials', async () => {
+ const server = await startWorkspace();
+
+ await saveConfig({
+ version: 1,
+ remotes: { staging: { apiUrl: server.url, apiKey: API_KEY } },
+ });
+ vi.stubEnv('TWENTY_API_URL', 'https://wrong.invalid');
+ vi.stubEnv('TWENTY_API_KEY', 'other-secret');
+ const result = await runJson(['--remote', 'staging']);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({ id: 'target-precedence', status: 'warning' }),
+ );
+ expect(server.requests[0].headers.authorization).toBe(`Bearer ${API_KEY}`);
+ expect(result.stdout).not.toContain('other-secret');
+ });
+
+ it('reports incomplete environment credentials instead of falling back', async () => {
+ const server = await startWorkspace();
+
+ await saveConfig({
+ version: 1,
+ defaultRemote: 'prod',
+ remotes: { prod: { apiUrl: server.url, apiKey: API_KEY } },
+ });
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'target',
+ status: 'fail',
+ code: 'INCOMPLETE_TARGET',
+ }),
+ );
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it('detects a legacy SDK owning the PATH executable without executing it', async () => {
+ const sdkPath = join(root, 'legacy', 'twenty-sdk');
+ const binPath = join(root, 'bin');
+ const executable = join(sdkPath, 'cli.cjs');
+
+ await mkdir(sdkPath, { recursive: true });
+ await mkdir(binPath);
+ await writeFile(
+ join(sdkPath, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version: '2.13.0',
+ bin: { twenty: 'cli.cjs' },
+ }),
+ );
+ await writeFile(
+ executable,
+ "#!/usr/bin/env node\nthrow new Error('Must not execute PATH binaries');\n",
+ );
+ await chmod(executable, 0o755);
+ await symlink(executable, join(binPath, 'twenty'));
+ const result = await runJson(['--offline']);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'path',
+ status: 'warning',
+ details: {
+ candidates: [
+ expect.objectContaining({
+ owner: { name: 'twenty-sdk', version: '2.13.0' },
+ }),
+ ],
+ },
+ }),
+ );
+ });
+
+ it('does not assign package ownership to an unrelated wrapper', async () => {
+ await mkdir(join(root, 'bin'));
+ await writeFile(
+ join(root, 'package.json'),
+ JSON.stringify({
+ name: 'twenty-sdk',
+ version: '2.13.0',
+ bin: { twenty: 'other.cjs' },
+ }),
+ );
+ const executable = join(root, 'bin', 'twenty');
+
+ await writeFile(executable, '#!/bin/sh\nexit 10\n');
+ await chmod(executable, 0o755);
+ const result = await runJson(['--offline']);
+
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'path',
+ status: 'warning',
+ details: expect.objectContaining({
+ candidates: [expect.objectContaining({ owner: null })],
+ }),
+ }),
+ );
+ });
+
+ it('warns when another CLI installation shadows the running one', async () => {
+ const installedPath = join(root, 'other-cli');
+ const runningPath = join(root, 'running-cli.cjs');
+ const executable = join(installedPath, 'cli.cjs');
+ const entryPoint = process.argv[1];
+
+ await mkdir(installedPath);
+ await mkdir(join(root, 'bin'));
+ await writeFile(
+ join(installedPath, 'package.json'),
+ JSON.stringify({ name: 'twenty', version: '0.1.0', bin: 'cli.cjs' }),
+ );
+ await writeFile(executable, '#!/usr/bin/env node\n');
+ await writeFile(runningPath, '#!/usr/bin/env node\n');
+ await chmod(executable, 0o755);
+ await symlink(executable, join(root, 'bin', 'twenty'));
+ process.argv[1] = runningPath;
+
+ try {
+ const result = await runJson(['--offline']);
+
+ expect(result.exitCode).toBe(0);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'path',
+ status: 'warning',
+ message: expect.stringContaining('differs from the running CLI'),
+ }),
+ );
+ } finally {
+ process.argv[1] = entryPoint;
+ }
+ });
+
+ it('bounds a stalled connection check', async () => {
+ const server = await startWorkspace('hang');
+
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const result = await runJson();
+
+ expect(result.exitCode).toBe(1);
+ expect(result.checks).toContainEqual(
+ expect.objectContaining({
+ id: 'metadata-api',
+ status: 'fail',
+ code: 'TIMEOUT',
+ }),
+ );
+ });
+
+ it('cancels an in-flight check with the standard cancellation result', async () => {
+ const server = await startWorkspace('hang');
+
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', API_KEY);
+ const run = runJson();
+
+ await vi.waitFor(() => expect(server.requests).toHaveLength(1));
+ process.emit('SIGINT');
+ const result = await run;
+
+ expect(result.exitCode).toBe(130);
+ expect(result.envelope.error.code).toBe('CANCELLED');
+ });
+});
diff --git a/packages/twenty-cli/src/commands/doctor/doctor.command-definition.ts b/packages/twenty-cli/src/commands/doctor/doctor.command-definition.ts
new file mode 100644
index 00000000000..ecd7ff588a3
--- /dev/null
+++ b/packages/twenty-cli/src/commands/doctor/doctor.command-definition.ts
@@ -0,0 +1,23 @@
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const DOCTOR_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['doctor'],
+ description: 'Diagnose CLI, app SDK and workspace connection problems',
+ helpGroup: HELP_GROUP.TOOLS,
+ options: [
+ { flags: '--path <directory>', description: 'App directory to inspect' },
+ { flags: '--offline', description: 'Skip network checks' },
+ ],
+ examples: [
+ 'twenty doctor',
+ 'twenty doctor --remote staging --path ./my-app --json',
+ 'twenty doctor --offline',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/doctor/run-doctor-command')).runDoctorCommand,
+};
diff --git a/packages/twenty-cli/src/commands/doctor/run-doctor-command.ts b/packages/twenty-cli/src/commands/doctor/run-doctor-command.ts
new file mode 100644
index 00000000000..28a93cbe76e
--- /dev/null
+++ b/packages/twenty-cli/src/commands/doctor/run-doctor-command.ts
@@ -0,0 +1,75 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { getConfigPath } from '@/config/get-config-path';
+import { formatDoctorChecks } from '@/doctor/format-doctor-checks';
+import { getConnectionDoctorChecks } from '@/doctor/get-connection-doctor-checks';
+import { getPathDoctorCheck } from '@/doctor/get-path-doctor-check';
+import { getProjectDoctorChecks } from '@/doctor/get-project-doctor-checks';
+import { getRuntimeDoctorChecks } from '@/doctor/get-runtime-doctor-checks';
+import { CliError } from '@/output/cli-error';
+
+export const runDoctorCommand: CommandRun = async ({
+ options,
+ signal,
+ outputMode,
+}) => {
+ const checks = getRuntimeDoctorChecks();
+ const workingDirectory = process.cwd();
+
+ try {
+ checks.push(
+ await getPathDoctorCheck({
+ environment: process.env,
+ workingDirectory,
+ signal,
+ }),
+ );
+ } catch {
+ signal.throwIfAborted();
+ checks.push({
+ id: 'path',
+ status: 'fail',
+ message: 'Could not inspect executables on PATH.',
+ });
+ }
+
+ checks.push(
+ ...(await getProjectDoctorChecks({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory,
+ signal,
+ })),
+ );
+ checks.push(
+ ...(await getConnectionDoctorChecks({
+ environment: process.env,
+ configPath: getConfigPath(),
+ remoteFlag: readStringOption(options, 'remote'),
+ offline: readBooleanOption(options, 'offline'),
+ signal,
+ })),
+ );
+ signal.throwIfAborted();
+
+ const failedChecks = checks.filter((check) => check.status === 'fail');
+ const human = formatDoctorChecks(checks);
+
+ if (isNonEmptyArray(failedChecks)) {
+ throw new CliError({
+ code: 'DOCTOR_FAILED',
+ message: `${failedChecks.length} doctor ${failedChecks.length === 1 ? 'check' : 'checks'} failed.`,
+ hint:
+ outputMode === 'human'
+ ? human
+ : 'Read error.details.checks for the failures and recovery hints.',
+ details: { checks },
+ });
+ }
+
+ return { data: { checks }, human };
+};
diff --git a/packages/twenty-cli/src/commands/metadata/__tests__/metadata-inspection.spec.ts b/packages/twenty-cli/src/commands/metadata/__tests__/metadata-inspection.spec.ts
new file mode 100644
index 00000000000..3ea4c4a6123
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/__tests__/metadata-inspection.spec.ts
@@ -0,0 +1,669 @@
+import { isNonEmptyString, isString } from '@sniptt/guards';
+import { Kind, parse, valueFromASTUntyped } from 'graphql';
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { isPlainObject, safeGetNestedProperty } from 'twenty-shared/utils';
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+const createObject = (
+ id: string,
+ nameSingular: string,
+ namePlural: string,
+) => ({
+ id,
+ nameSingular,
+ namePlural,
+ universalIdentifier: `universal-${id}`,
+ labelSingular: 'Company',
+ labelPlural: 'Companies',
+ description: 'CRM companies',
+ isActive: true,
+ isSystem: false,
+ isSearchable: true,
+ labelIdentifierFieldMetadataId: 'name-id',
+ applicationId: 'standard-id',
+});
+
+const createField = (
+ name: string,
+ overrides: Record<string, unknown> = {},
+) => ({
+ id: `${name}-id`,
+ universalIdentifier: `universal-${name}`,
+ name,
+ label: name,
+ description: null,
+ objectMetadataId: 'company-id',
+ type: 'TEXT',
+ applicationId: 'standard-id',
+ isActive: true,
+ isSystem: false,
+ isNullable: true,
+ isUnique: false,
+ defaultValue: null,
+ options: null,
+ settings: null,
+ relation: null,
+ morphRelations: null,
+ ...overrides,
+});
+
+const RELATION = {
+ type: 'ONE_TO_MANY',
+ sourceObjectMetadata: {
+ id: 'company-id',
+ nameSingular: 'company',
+ namePlural: 'companies',
+ },
+ targetObjectMetadata: {
+ id: 'invoice-id',
+ nameSingular: 'invoice',
+ namePlural: 'invoices',
+ },
+ sourceFieldMetadata: { id: 'invoices-id', name: 'invoices' },
+ targetFieldMetadata: { id: 'company-relation-id', name: 'company' },
+};
+
+const APPLICATIONS = [
+ {
+ id: 'standard-id',
+ name: 'Twenty',
+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ },
+ { id: 'app-id', name: 'Billing', universalIdentifier: 'billing-app' },
+];
+const FORBIDDEN = {
+ errors: [{ message: 'Forbidden', extensions: { code: 'FORBIDDEN' } }],
+ data: null,
+};
+
+let objects = [createObject('company-id', 'company', 'companies')];
+let fields = [createField('name')];
+let pageSize = 2;
+let applicationsDenied = false;
+let objectsDenied = false;
+let fieldsDenied = false;
+let failSecondFieldPage = false;
+let invalidCursor = false;
+let endlessObjects = false;
+
+const page = <TNode>(nodes: TNode[], after?: string) => {
+ const offset = Number(after ?? 0);
+ const nextOffset = offset + pageSize;
+
+ return {
+ edges: nodes.slice(offset, nextOffset).map((node) => ({ node })),
+ pageInfo: {
+ hasNextPage: nextOffset < nodes.length,
+ endCursor: invalidCursor ? '0' : String(nextOffset),
+ },
+ };
+};
+
+const server = await startTestServer((request, response) => {
+ const body: unknown = JSON.parse(request.body);
+
+ if (!isPlainObject(body) || !isString(body.query)) {
+ throw new Error('Expected a GraphQL request');
+ }
+
+ const definition = parse(body.query).definitions[0];
+
+ if (definition.kind !== Kind.OPERATION_DEFINITION) {
+ throw new Error('Expected operation');
+ }
+
+ const selection = definition.selectionSet.selections[0];
+
+ if (selection.kind !== Kind.FIELD) {
+ throw new Error('Expected root field');
+ }
+
+ const variables = isPlainObject(body.variables) ? body.variables : undefined;
+ const args = Object.fromEntries(
+ (selection.arguments ?? []).map((argument) => [
+ argument.name.value,
+ valueFromASTUntyped(argument.value, variables),
+ ]),
+ );
+ const pagingAfter = safeGetNestedProperty(args, 'paging.after');
+ const after = isString(pagingAfter) ? pagingAfter : undefined;
+
+ if (selection.name.value === 'objects') {
+ if (objectsDenied) {
+ return sendJson(response, 200, FORBIDDEN);
+ }
+
+ if (endlessObjects) {
+ const offset = Number(after ?? 0);
+ return sendJson(response, 200, {
+ data: {
+ objects: {
+ edges: Array.from({ length: 1000 }, (_, index) => ({
+ node: createObject(
+ `id-${offset + index}`,
+ `name-${offset + index}`,
+ `names-${offset + index}`,
+ ),
+ })),
+ pageInfo: { hasNextPage: true, endCursor: String(offset + 1000) },
+ },
+ },
+ });
+ }
+ return sendJson(response, 200, {
+ data: { objects: page(objects, after) },
+ });
+ }
+
+ if (selection.name.value === 'fields') {
+ if (fieldsDenied || (failSecondFieldPage && isNonEmptyString(after))) {
+ return sendJson(response, 200, FORBIDDEN);
+ }
+
+ const objectMetadataId = safeGetNestedProperty(
+ args,
+ 'filter.objectMetadataId.eq',
+ );
+
+ return sendJson(response, 200, {
+ data: {
+ fields: page(
+ fields.filter((field) => field.objectMetadataId === objectMetadataId),
+ after,
+ ),
+ },
+ });
+ }
+
+ if (selection.name.value === 'currentWorkspace') {
+ return sendJson(response, 200, {
+ data: { currentWorkspace: { workspaceCustomApplicationId: 'custom-id' } },
+ });
+ }
+
+ if (selection.name.value === 'findManyApplications') {
+ return sendJson(
+ response,
+ 200,
+ applicationsDenied
+ ? FORBIDDEN
+ : { data: { findManyApplications: APPLICATIONS } },
+ );
+ }
+
+ return sendJson(response, 400, { errors: [{ message: 'Unexpected query' }] });
+});
+
+const runJson = async (args: string[]) => {
+ const result = await runCliForTest(['metadata', ...args, '--json']);
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+
+describe('metadata inspection commands', () => {
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'fixture-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ objects = [createObject('company-id', 'company', 'companies')];
+ fields = [
+ createField('name', { isNullable: false }),
+ createField('tier', {
+ label: 'Tier',
+ type: 'SELECT',
+ applicationId: 'custom-id',
+ defaultValue: "'GOLD'",
+ options: [
+ { id: 'gold', label: 'Gold', value: 'GOLD', color: 'yellow' },
+ ],
+ }),
+ createField('invoices', {
+ type: 'RELATION',
+ applicationId: 'app-id',
+ relation: RELATION,
+ }),
+ createField('secret', { applicationId: 'unreadable-app' }),
+ createField('id', { type: 'UUID', isSystem: true }),
+ createField('foreign', { objectMetadataId: 'other-object-id' }),
+ ];
+ pageSize = 2;
+ applicationsDenied = false;
+ objectsDenied = false;
+ fieldsDenied = false;
+ failSecondFieldPage = false;
+ invalidCursor = false;
+ endlessObjects = false;
+ server.requests.length = 0;
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+ afterAll(async () => server.close());
+
+ it.each(['company', 'companies'])(
+ 'describes exact API alias %s with object properties only',
+ async (name) => {
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ name,
+ ]);
+ expect(exitCode).toBe(0);
+ expect(Object.keys(envelope.data)).toEqual(['object']);
+ expect(envelope.data.object).toMatchObject({
+ id: 'company-id',
+ owner: { kind: 'standard' },
+ });
+ expect(envelope.warnings).toEqual([]);
+ expect(
+ server.requests.every(
+ (request) =>
+ request.path === '/metadata' &&
+ request.headers.authorization === 'Bearer fixture-key',
+ ),
+ ).toBe(true);
+ },
+ );
+
+ it.each(['company', 'companies'])(
+ 'lists fields of exact API alias %s with per-field owners',
+ async (name) => {
+ const { envelope, exitCode } = await runJson(['field', 'list', name]);
+ expect(exitCode).toBe(0);
+ expect(
+ envelope.data.fields.map(
+ (field: { name: string; owner: { kind: string } }) => [
+ field.name,
+ field.owner.kind,
+ ],
+ ),
+ ).toEqual([
+ ['invoices', 'application'],
+ ['name', 'standard'],
+ ['secret', 'unknown'],
+ ['tier', 'custom'],
+ ]);
+ expect(envelope.data.hiddenSystemFieldCount).toBe(1);
+ },
+ );
+
+ it('includes system fields in field list with --all', async () => {
+ const { envelope } = await runJson(['field', 'list', 'companies', '--all']);
+ expect(
+ envelope.data.fields.map((field: { name: string }) => field.name),
+ ).toEqual(['id', 'invoices', 'name', 'secret', 'tier']);
+ expect(envelope.data.hiddenSystemFieldCount).toBe(0);
+ });
+
+ it('describes a system field without --all', async () => {
+ const { envelope, exitCode } = await runJson([
+ 'field',
+ 'describe',
+ 'companies',
+ 'id',
+ ]);
+ expect(exitCode).toBe(0);
+ expect(envelope.data.field).toMatchObject({
+ name: 'id',
+ type: 'UUID',
+ isSystem: true,
+ });
+ });
+
+ it('preserves select values, defaults and relation endpoints in JSON', async () => {
+ const tier = await runJson(['field', 'describe', 'companies', 'tier']);
+ expect(tier.envelope.data.field).toMatchObject({
+ defaultValue: "'GOLD'",
+ options: [{ label: 'Gold', value: 'GOLD' }],
+ });
+ const relation = await runJson([
+ 'field',
+ 'describe',
+ 'company',
+ 'invoices',
+ ]);
+ expect(relation.envelope.data.field.relation).toEqual(RELATION);
+ });
+
+ it('renders human field details and select values', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'metadata',
+ 'field',
+ 'describe',
+ 'companies',
+ 'tier',
+ ]);
+ expect(exitCode).toBe(0);
+ for (const text of [
+ 'Tier (tier) on companies',
+ 'Custom',
+ 'SELECT',
+ 'Nullable',
+ 'OPTION',
+ 'VALUE',
+ 'Gold',
+ 'GOLD',
+ 'yellow',
+ ]) {
+ expect(stdout).toContain(text);
+ }
+ });
+
+ it('renders only object properties in object describe', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'metadata',
+ 'object',
+ 'describe',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(0);
+ for (const text of [
+ 'Companies (companies)',
+ 'company / companies',
+ 'Fields: twenty metadata field list companies',
+ ]) {
+ expect(stdout).toContain(text);
+ }
+ expect(stdout).toMatch(/Description\s+CRM companies/);
+ expect(stdout).not.toContain('invoices');
+ expect(stdout).not.toContain('system fields hidden');
+ });
+
+ it('renders relations, label fields and system-field guidance', async () => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'metadata',
+ 'field',
+ 'list',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(0);
+ for (const text of [
+ 'Companies (companies)',
+ 'label field',
+ 'one-to-many',
+ 'invoices.company',
+ 'Billing',
+ 'system fields hidden',
+ '--all',
+ ]) {
+ expect(stdout).toContain(text);
+ }
+ });
+
+ it('keeps unknown nullable constraints unknown in human output', async () => {
+ fields = [createField('name', { isNullable: null, isUnique: null })];
+ const { stdout, exitCode } = await runCliForTest([
+ 'metadata',
+ 'field',
+ 'describe',
+ 'companies',
+ 'name',
+ ]);
+ expect(exitCode).toBe(0);
+ expect(stdout).toMatch(/Nullable\s+unknown/);
+ expect(stdout).toMatch(/Unique\s+unknown/);
+ });
+
+ it.each(['Companies', 'COMPANIES', 'compan'])(
+ 'does not resolve label or fuzzy name %s',
+ async (name) => {
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ name,
+ ]);
+ expect(exitCode).toBe(4);
+ expect(envelope.error.code).toBe('NOT_FOUND');
+ expect(server.requests).toHaveLength(1);
+ },
+ );
+
+ it('finds objects beyond the first page', async () => {
+ objects.unshift(
+ createObject('first', 'first', 'firsts'),
+ createObject('second', 'second', 'seconds'),
+ );
+ const { envelope, exitCode } = await runJson(['field', 'list', 'company']);
+ expect(exitCode).toBe(0);
+ expect(envelope.data.object.id).toBe('company-id');
+ });
+
+ it('rejects a singular/plural ambiguity on a later page before fetching fields', async () => {
+ pageSize = 1;
+ objects.push(createObject('collision', 'companies', 'firms'));
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('AMBIGUOUS_RESOURCE');
+ expect(envelope.error.details.matches).toHaveLength(2);
+ expect(server.requests).toHaveLength(2);
+ });
+
+ it('accepts identical singular and plural names on one object', async () => {
+ objects = [createObject('company-id', 'series', 'series')];
+ expect((await runJson(['object', 'describe', 'series'])).exitCode).toBe(0);
+ });
+
+ it.each(['Tier', 'foreign', 'missing'])(
+ 'does not select an inexact or foreign field %s',
+ async (name) => {
+ const { envelope, exitCode } = await runJson([
+ 'field',
+ 'describe',
+ 'companies',
+ name,
+ ]);
+ expect(exitCode).toBe(4);
+ expect(envelope.error.code).toBe('NOT_FOUND');
+ },
+ );
+
+ it('does not inherit object ownership when application names are denied', async () => {
+ applicationsDenied = true;
+ const { envelope, exitCode } = await runJson([
+ 'field',
+ 'list',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(0);
+ expect(envelope.data.object.owner.kind).toBe('unknown');
+ expect(
+ envelope.data.fields.find(
+ (field: { name: string }) => field.name === 'tier',
+ ).owner.kind,
+ ).toBe('custom');
+ expect(
+ envelope.data.fields.find(
+ (field: { name: string }) => field.name === 'invoices',
+ ).owner.kind,
+ ).toBe('unknown');
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'OWNERS_UNAVAILABLE' }),
+ ]);
+ });
+
+ it.each(['objects', 'fields', 'secondFieldPage'])(
+ 'preserves permission failures at %s without partial success',
+ async (stage) => {
+ objectsDenied = stage === 'objects';
+ fieldsDenied = stage === 'fields';
+ failSecondFieldPage = stage === 'secondFieldPage';
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(3);
+ expect(envelope.error.code).toBe('PERMISSION_DENIED');
+ expect(envelope).not.toHaveProperty('data');
+ },
+ );
+
+ it('fails a repeated cursor instead of looping or reporting an incomplete match', async () => {
+ pageSize = 1;
+ invalidCursor = true;
+ objects.push(createObject('other', 'other', 'others'));
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'companies',
+ ]);
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(server.requests).toHaveLength(2);
+ });
+
+ it('bounds metadata traversal by item count', async () => {
+ endlessObjects = true;
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'missing',
+ ]);
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('RESPONSE_LIMIT_EXCEEDED');
+ expect(server.requests).toHaveLength(11);
+ });
+
+ it('does not reuse metadata across invocations', async () => {
+ expect(
+ (await runJson(['field', 'describe', 'companies', 'tier'])).exitCode,
+ ).toBe(0);
+ fields = fields.filter((field) => field.name !== 'tier');
+ expect(
+ (await runJson(['field', 'describe', 'companies', 'tier'])).exitCode,
+ ).toBe(4);
+ });
+
+ it('bounds accumulated bytes across individually valid pages', async () => {
+ pageSize = 1;
+ objects = [
+ {
+ ...createObject('first', 'first', 'firsts'),
+ description: 'x'.repeat(9 * 1024 * 1024),
+ },
+ {
+ ...createObject('second', 'second', 'seconds'),
+ description: 'x'.repeat(9 * 1024 * 1024),
+ },
+ ];
+
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'first',
+ ]);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('RESPONSE_LIMIT_EXCEEDED');
+ expect(server.requests).toHaveLength(2);
+ });
+
+ it('ignores matching labels on other objects when resolving an exact API name', async () => {
+ objects.push({
+ ...createObject('other', 'other', 'others'),
+ labelPlural: 'companies',
+ });
+
+ const { envelope, exitCode } = await runJson([
+ 'object',
+ 'describe',
+ 'companies',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.object.id).toBe('company-id');
+ });
+
+ it('shows only the target of each polymorphic relation field', async () => {
+ const createMorphRelation = (
+ fieldName: string,
+ target: { id: string; nameSingular: string; namePlural: string },
+ ) => ({
+ type: 'MANY_TO_ONE',
+ sourceObjectMetadata: {
+ id: 'company-id',
+ nameSingular: 'company',
+ namePlural: 'companies',
+ },
+ targetObjectMetadata: target,
+ sourceFieldMetadata: { id: `${fieldName}-id`, name: 'target' },
+ targetFieldMetadata: {
+ id: `${target.namePlural}-companies-id`,
+ name: 'companies',
+ },
+ });
+ const morphRelations = [
+ createMorphRelation('targetInvoice', {
+ id: 'invoice-id',
+ nameSingular: 'invoice',
+ namePlural: 'invoices',
+ }),
+ createMorphRelation('targetPerson', {
+ id: 'person-id',
+ nameSingular: 'person',
+ namePlural: 'people',
+ }),
+ ];
+
+ fields = [
+ createField('targetInvoice', { type: 'MORPH_RELATION', morphRelations }),
+ createField('targetPerson', { type: 'MORPH_RELATION', morphRelations }),
+ ];
+
+ const described = await runCliForTest([
+ 'metadata',
+ 'field',
+ 'describe',
+ 'companies',
+ 'targetInvoice',
+ ]);
+ const listed = await runCliForTest([
+ 'metadata',
+ 'field',
+ 'list',
+ 'companies',
+ ]);
+ const personLine = listed.stdout
+ .split('\n')
+ .find((line) => line.includes('targetPerson'));
+
+ expect(described.exitCode).toBe(0);
+ expect(described.stdout).toContain('MORPH_RELATION');
+ expect(described.stdout).toContain('many-to-one · invoices.companies');
+ expect(described.stdout).not.toContain('people.companies');
+ expect(personLine).toContain('many-to-one · people.companies');
+ expect(personLine).not.toContain('invoices.companies');
+ expect(
+ (await runJson(['field', 'describe', 'companies', 'targetInvoice']))
+ .envelope.data.field.morphRelations,
+ ).toEqual(morphRelations);
+ });
+
+ it('handles missing arguments and help without a configured target', async () => {
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_API_KEY', '');
+ const missing = await runJson(['field', 'describe', 'companies']);
+ expect(missing.exitCode).toBe(2);
+ expect(missing.envelope.error.code).toBe('USAGE');
+ const help = await runJson(['field', 'describe', '--help']);
+ expect(help.exitCode).toBe(0);
+ expect(help.envelope.data.help).toContain('<object> <field>');
+ expect(server.requests).toHaveLength(0);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/metadata/field/describe/metadata-field-describe.command-definition.ts b/packages/twenty-cli/src/commands/metadata/field/describe/metadata-field-describe.command-definition.ts
new file mode 100644
index 00000000000..13b9650af8d
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/field/describe/metadata-field-describe.command-definition.ts
@@ -0,0 +1,31 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const METADATA_FIELD_DESCRIBE_COMMAND_DEFINITION: TargetCommandDefinition =
+ {
+ path: ['metadata', 'field', 'describe'],
+ description: 'Describe a field, its constraints, options and relations',
+ arguments: [
+ {
+ name: 'object',
+ description: 'Exact singular or plural object API name',
+ required: true,
+ },
+ {
+ name: 'field',
+ description: 'Exact field API name, including system fields',
+ required: true,
+ },
+ ],
+ examples: [
+ 'twenty metadata field describe companies tier',
+ 'twenty metadata field describe people company --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (
+ await import('@/commands/metadata/field/describe/run-metadata-field-describe-command')
+ ).runMetadataFieldDescribeCommand,
+ };
diff --git a/packages/twenty-cli/src/commands/metadata/field/describe/run-metadata-field-describe-command.ts b/packages/twenty-cli/src/commands/metadata/field/describe/run-metadata-field-describe-command.ts
new file mode 100644
index 00000000000..08676df318b
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/field/describe/run-metadata-field-describe-command.ts
@@ -0,0 +1,91 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { fetchMetadataInspection } from '@/metadata/fetch-metadata-inspection';
+import { formatMetadataRelations } from '@/metadata/format-metadata-fields';
+import { formatMetadataOwner } from '@/metadata/format-metadata-owner';
+import { getFieldOptions } from '@/metadata/get-field-options';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatDetails } from '@/output/format-details';
+import { formatTable } from '@/output/format-table';
+
+const formatBoolean = (value?: boolean) =>
+ isDefined(value) ? String(value) : 'unknown';
+
+export const runMetadataFieldDescribeCommand: CommandRun<
+ TargetCommandContext
+> = async ({ arguments: commandArguments, target, signal, output }) => {
+ const fieldName = readStringArgument(commandArguments, 1) ?? '';
+ const { object, fields } = await fetchMetadataInspection({
+ objectName: readStringArgument(commandArguments, 0) ?? '',
+ target,
+ signal,
+ output,
+ });
+ const matches = fields.filter((field) => field.name === fieldName);
+
+ if (matches.length > 1) {
+ throw new CliError({
+ code: 'AMBIGUOUS_RESOURCE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `More than one field has the API name ${fieldName} on ${object.namePlural}.`,
+ });
+ }
+
+ const field = matches[0];
+
+ if (!isDefined(field)) {
+ throw new CliError({
+ code: 'NOT_FOUND',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: `No field has the API name ${fieldName} on ${object.namePlural}.`,
+ hint: `Use an exact API name from twenty metadata field list ${object.namePlural} --all.`,
+ });
+ }
+
+ const optionRows = getFieldOptions(field);
+
+ return {
+ data: { object, field },
+ human: [
+ `${field.label} (${field.name}) on ${object.namePlural}`,
+ formatDetails([
+ ['ID', field.id],
+ ['Type', field.type],
+ ['Owner', formatMetadataOwner(field.owner)],
+ ['Active', formatBoolean(field.isActive)],
+ ['System', formatBoolean(field.isSystem)],
+ ['Nullable', formatBoolean(field.isNullable)],
+ ['Unique', formatBoolean(field.isUnique)],
+ ['Default', JSON.stringify(field.defaultValue ?? null)],
+ ]),
+ field.description ?? '',
+ formatMetadataRelations(field),
+ isNonEmptyArray(optionRows)
+ ? formatTable({
+ rows: optionRows,
+ columns: [
+ {
+ header: 'OPTION',
+ value: (option) => String(option.label ?? ''),
+ },
+ {
+ header: 'VALUE',
+ value: (option) => String(option.value ?? ''),
+ },
+ {
+ header: 'COLOR',
+ value: (option) => String(option.color ?? ''),
+ },
+ ],
+ })
+ : '',
+ ]
+ .filter(isNonEmptyString)
+ .join('\n\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/metadata/field/list/metadata-field-list.command-definition.ts b/packages/twenty-cli/src/commands/metadata/field/list/metadata-field-list.command-definition.ts
new file mode 100644
index 00000000000..2697dcf2e8e
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/field/list/metadata-field-list.command-definition.ts
@@ -0,0 +1,26 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const METADATA_FIELD_LIST_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['metadata', 'field', 'list'],
+ description: 'List fields and who owns each one',
+ arguments: [
+ {
+ name: 'object',
+ description: 'Exact singular or plural API name',
+ required: true,
+ },
+ ],
+ options: [{ flags: '--all', description: 'Include system fields' }],
+ examples: [
+ 'twenty metadata field list companies',
+ 'twenty metadata field list companies --all --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (
+ await import('@/commands/metadata/field/list/run-metadata-field-list-command')
+ ).runMetadataFieldListCommand,
+};
diff --git a/packages/twenty-cli/src/commands/metadata/field/list/run-metadata-field-list-command.ts b/packages/twenty-cli/src/commands/metadata/field/list/run-metadata-field-list-command.ts
new file mode 100644
index 00000000000..c8cfbc5aca0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/field/list/run-metadata-field-list-command.ts
@@ -0,0 +1,43 @@
+import {
+ readBooleanOption,
+ readStringArgument,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { fetchMetadataInspection } from '@/metadata/fetch-metadata-inspection';
+import { formatMetadataFields } from '@/metadata/format-metadata-fields';
+import { selectListedFields } from '@/metadata/select-listed-fields';
+
+export const runMetadataFieldListCommand: CommandRun<
+ TargetCommandContext
+> = async ({
+ arguments: commandArguments,
+ options,
+ target,
+ signal,
+ output,
+}) => {
+ const inspection = await fetchMetadataInspection({
+ objectName: readStringArgument(commandArguments, 0) ?? '',
+ target,
+ signal,
+ output,
+ });
+ const { object } = inspection;
+ const { fields, hiddenSystemFieldCount } = selectListedFields({
+ fields: inspection.fields,
+ includeSystemFields: readBooleanOption(options, 'all'),
+ });
+
+ return {
+ data: { object, fields, hiddenSystemFieldCount },
+ human: [
+ `${object.labelPlural} (${object.namePlural})`,
+ formatMetadataFields({
+ fields,
+ hiddenSystemFieldCount,
+ labelIdentifierFieldMetadataId: object.labelIdentifierFieldMetadataId,
+ }),
+ ].join('\n\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/metadata/object/describe/metadata-object-describe.command-definition.ts b/packages/twenty-cli/src/commands/metadata/object/describe/metadata-object-describe.command-definition.ts
new file mode 100644
index 00000000000..c4be1772784
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/object/describe/metadata-object-describe.command-definition.ts
@@ -0,0 +1,26 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const METADATA_OBJECT_DESCRIBE_COMMAND_DEFINITION: TargetCommandDefinition =
+ {
+ path: ['metadata', 'object', 'describe'],
+ description: 'Describe an object',
+ arguments: [
+ {
+ name: 'object',
+ description: 'Exact singular or plural API name',
+ required: true,
+ },
+ ],
+ examples: [
+ 'twenty metadata object describe companies',
+ 'twenty metadata object describe person --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (
+ await import('@/commands/metadata/object/describe/run-metadata-object-describe-command')
+ ).runMetadataObjectDescribeCommand,
+ };
diff --git a/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts b/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts
new file mode 100644
index 00000000000..ba85a2a7315
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/object/describe/run-metadata-object-describe-command.ts
@@ -0,0 +1,44 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+import { fetchMetadataInspection } from '@/metadata/fetch-metadata-inspection';
+import { formatMetadataOwner } from '@/metadata/format-metadata-owner';
+import { formatDetails } from '@/output/format-details';
+
+export const runMetadataObjectDescribeCommand: CommandRun<
+ TargetCommandContext
+> = async ({ arguments: commandArguments, target, signal, output }) => {
+ const { object } = await fetchMetadataInspection({
+ objectName: readStringArgument(commandArguments, 0) ?? '',
+ target,
+ signal,
+ output,
+ });
+
+ return {
+ data: { object },
+ human: [
+ `${object.labelPlural} (${object.namePlural})`,
+ formatDetails([
+ ['ID', object.id],
+ ['API names', `${object.nameSingular} / ${object.namePlural}`],
+ ...(isNonEmptyString(object.description)
+ ? [
+ ['Description', formatDataValue(object.description)] as [
+ string,
+ string,
+ ],
+ ]
+ : []),
+ ['Owner', formatMetadataOwner(object.owner)],
+ ['Active', String(object.isActive)],
+ ['System', String(object.isSystem)],
+ ['Searchable', String(object.isSearchable)],
+ ]),
+ `Fields: twenty metadata field list ${object.namePlural}`,
+ ].join('\n\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/metadata/object/list/__tests__/metadata-object-list.spec.ts b/packages/twenty-cli/src/commands/metadata/object/list/__tests__/metadata-object-list.spec.ts
new file mode 100644
index 00000000000..4135f564ccf
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/object/list/__tests__/metadata-object-list.spec.ts
@@ -0,0 +1,303 @@
+import { type ServerResponse } from 'node:http';
+
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+
+type ScenarioName =
+ | 'named'
+ | 'appsDenied'
+ | 'objectsDenied'
+ | 'paginated'
+ | 'repeatedCursor'
+ | 'missingCursor'
+ | 'laterPageDenied'
+ | 'appsPending';
+
+const objectNode = (
+ namePlural: string,
+ applicationId: string,
+ isSystem = false,
+) => ({
+ node: {
+ nameSingular: namePlural.replace(/s$/, ''),
+ namePlural,
+ labelSingular: namePlural,
+ labelPlural: namePlural,
+ isSystem,
+ isActive: true,
+ applicationId,
+ },
+});
+
+const objectsResponse = (hasNextPage: boolean) => ({
+ data: {
+ objects: {
+ pageInfo: { hasNextPage, endCursor: hasNextPage ? 'next-page' : null },
+ edges: [
+ objectNode('surveyResults', 'custom-id'),
+ objectNode('people', 'standard-id'),
+ objectNode('invoices', 'invoices-id'),
+ objectNode('companies', 'standard-id'),
+ objectNode('workspaceMembers', 'standard-id', true),
+ objectNode('secrets', 'hidden-id'),
+ ],
+ },
+ currentWorkspace: { workspaceCustomApplicationId: 'custom-id' },
+ },
+});
+
+const APPLICATIONS_RESPONSE = {
+ data: {
+ findManyApplications: [
+ {
+ id: 'standard-id',
+ name: 'Twenty Standard',
+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ },
+ {
+ id: 'invoices-id',
+ name: 'Acme Invoices',
+ universalIdentifier: 'invoices-universal-identifier',
+ },
+ ],
+ },
+};
+
+const FORBIDDEN_RESPONSE = {
+ errors: [
+ { message: 'Forbidden resource', extensions: { code: 'FORBIDDEN' } },
+ ],
+ data: null,
+};
+
+let scenario: ScenarioName = 'named';
+const requestedCursors: unknown[] = [];
+const pendingResponses: ServerResponse[] = [];
+
+const server = await startTestServer((request, response) => {
+ const isApplicationsLookup = request.body.includes('findManyApplications');
+
+ if (scenario === 'appsPending' && isApplicationsLookup) {
+ pendingResponses.push(response);
+
+ return;
+ }
+
+ if (scenario === 'appsPending' || scenario === 'objectsDenied') {
+ return sendJson(
+ response,
+ 200,
+ isApplicationsLookup ? APPLICATIONS_RESPONSE : FORBIDDEN_RESPONSE,
+ );
+ }
+
+ if (isApplicationsLookup) {
+ return sendJson(
+ response,
+ 200,
+ scenario === 'appsDenied' ? FORBIDDEN_RESPONSE : APPLICATIONS_RESPONSE,
+ );
+ }
+
+ const { variables } = JSON.parse(request.body);
+ const after = Object.values(variables).find(
+ (value) => typeof value === 'object' && value !== null && 'after' in value,
+ ) as { after?: string } | undefined;
+
+ requestedCursors.push(after?.after ?? null);
+
+ if (scenario === 'laterPageDenied' && after?.after) {
+ return sendJson(response, 200, FORBIDDEN_RESPONSE);
+ }
+
+ if (scenario === 'paginated' && after?.after === 'next-page') {
+ return sendJson(response, 200, {
+ data: {
+ objects: {
+ pageInfo: { hasNextPage: false },
+ edges: [
+ objectNode('deals', 'custom-id'),
+ objectNode('tokens', 'standard-id', true),
+ ],
+ },
+ currentWorkspace: { workspaceCustomApplicationId: 'custom-id' },
+ },
+ });
+ }
+
+ const result = objectsResponse(
+ [
+ 'paginated',
+ 'repeatedCursor',
+ 'missingCursor',
+ 'laterPageDenied',
+ ].includes(scenario),
+ );
+
+ if (scenario === 'missingCursor') {
+ result.data.objects.pageInfo.endCursor = null;
+ }
+
+ return sendJson(response, 200, result);
+});
+
+const listObjects = async (options: string[] = []) => {
+ const { stdout, exitCode } = await runCliForTest([
+ 'metadata',
+ 'object',
+ 'list',
+ ...options,
+ '--json',
+ ]);
+
+ return { envelope: parseSingleJsonLine(stdout), exitCode };
+};
+
+const summarizeOwners = (
+ objects: {
+ namePlural: string;
+ owner: { kind: string; name: string | null };
+ }[],
+) =>
+ objects.map(({ namePlural, owner }) => [namePlural, owner.kind, owner.name]);
+
+describe('metadata object list', () => {
+ beforeEach(() => {
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ scenario = 'named';
+ requestedCursors.length = 0;
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ it('lists non-system objects grouped by owner', async () => {
+ const { envelope, exitCode } = await listObjects();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.warnings).toEqual([]);
+ expect(envelope.data.hiddenSystemObjectCount).toBe(1);
+ expect(summarizeOwners(envelope.data.objects)).toEqual([
+ ['companies', 'standard', null],
+ ['people', 'standard', null],
+ ['invoices', 'application', 'Acme Invoices'],
+ ['surveyResults', 'custom', null],
+ ['secrets', 'unknown', null],
+ ]);
+ });
+
+ it('includes system objects with --all', async () => {
+ const { envelope } = await listObjects(['--all']);
+
+ expect(envelope.data.hiddenSystemObjectCount).toBe(0);
+ expect(envelope.data.objects).toHaveLength(6);
+ });
+
+ it('still lists objects when app names are not readable', async () => {
+ scenario = 'appsDenied';
+
+ const { envelope, exitCode } = await listObjects();
+
+ expect(exitCode).toBe(0);
+ expect(summarizeOwners(envelope.data.objects)).toEqual([
+ ['surveyResults', 'custom', null],
+ ['companies', 'unknown', null],
+ ['invoices', 'unknown', null],
+ ['people', 'unknown', null],
+ ['secrets', 'unknown', null],
+ ]);
+ expect(envelope.warnings).toEqual([
+ expect.objectContaining({ code: 'OWNERS_UNAVAILABLE' }),
+ ]);
+ });
+
+ it('fails without a misleading warning when objects are not readable', async () => {
+ scenario = 'objectsDenied';
+
+ const { envelope, exitCode } = await listObjects();
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error.code).toBe('PERMISSION_DENIED');
+ expect(envelope.warnings).toEqual([]);
+ });
+
+ it.each([false, true])(
+ 'lists every page before filtering system objects (all: %s)',
+ async (includeSystem) => {
+ scenario = 'paginated';
+
+ const { envelope, exitCode } = await listObjects(
+ includeSystem ? ['--all'] : [],
+ );
+
+ expect(exitCode).toBe(0);
+ expect(envelope.warnings).toEqual([]);
+ expect(requestedCursors).toEqual([null, 'next-page']);
+ expect(envelope.data.objects).toHaveLength(includeSystem ? 8 : 6);
+ expect(envelope.data.hiddenSystemObjectCount).toBe(includeSystem ? 0 : 2);
+ expect(envelope.data.objects).toContainEqual(
+ expect.objectContaining({
+ namePlural: 'deals',
+ owner: expect.objectContaining({ kind: 'custom' }),
+ }),
+ );
+ },
+ );
+
+ it.each(['repeatedCursor', 'missingCursor'] as const)(
+ 'fails instead of returning a partial list for %s',
+ async (paginationScenario) => {
+ scenario = paginationScenario;
+
+ const { envelope, exitCode } = await listObjects();
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(envelope).not.toHaveProperty('data');
+ expect(requestedCursors.length).toBeLessThanOrEqual(2);
+ },
+ );
+
+ it('fails instead of returning a partial list when a later page is denied', async () => {
+ scenario = 'laterPageDenied';
+
+ const { envelope, exitCode } = await listObjects();
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error.code).toBe('PERMISSION_DENIED');
+ expect(envelope).not.toHaveProperty('data');
+ });
+
+ it('cancels the app lookup once the command has failed', async () => {
+ scenario = 'appsPending';
+
+ const { envelope } = await listObjects();
+
+ expect(envelope.error.code).toBe('PERMISSION_DENIED');
+ await vi.waitFor(() => {
+ expect(pendingResponses).toHaveLength(1);
+ expect(pendingResponses[0].destroyed).toBe(true);
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/commands/metadata/object/list/metadata-object-list.command-definition.ts b/packages/twenty-cli/src/commands/metadata/object/list/metadata-object-list.command-definition.ts
new file mode 100644
index 00000000000..5c7c2a1316f
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/object/list/metadata-object-list.command-definition.ts
@@ -0,0 +1,25 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const METADATA_OBJECT_LIST_COMMAND_DEFINITION: TargetCommandDefinition =
+ {
+ path: ['metadata', 'object', 'list'],
+ description: 'List objects and who owns each one',
+ options: [
+ {
+ flags: '--all',
+ description: 'Include system objects',
+ },
+ ],
+ examples: [
+ 'twenty metadata object list',
+ 'twenty metadata object list --all --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (
+ await import('@/commands/metadata/object/list/run-metadata-object-list-command')
+ ).runMetadataObjectListCommand,
+ };
diff --git a/packages/twenty-cli/src/commands/metadata/object/list/run-metadata-object-list-command.ts b/packages/twenty-cli/src/commands/metadata/object/list/run-metadata-object-list-command.ts
new file mode 100644
index 00000000000..11723e7f103
--- /dev/null
+++ b/packages/twenty-cli/src/commands/metadata/object/list/run-metadata-object-list-command.ts
@@ -0,0 +1,106 @@
+import { readBooleanOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { collectMetadataNodes } from '@/metadata/collect-metadata-nodes';
+import { formatMetadataOwner } from '@/metadata/format-metadata-owner';
+import { METADATA_OWNER_KIND_ORDER } from '@/metadata/constants/metadata-owner-kind-order.constant';
+import { METADATA_PAGE_SIZE } from '@/metadata/constants/metadata-page.constant';
+import { createMetadataOwnerResolver } from '@/metadata/resolve-metadata-owner';
+import { fetchOwnerApplications } from '@/metadata/fetch-owner-applications';
+import { formatTable } from '@/output/format-table';
+import { dimText } from '@/output/style';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+type MetadataClient = ReturnType<typeof createMetadataClient>;
+
+const fetchObjects = (client: MetadataClient, after?: string) =>
+ client.query({
+ objects: {
+ __args: { paging: { first: METADATA_PAGE_SIZE, after }, filter: {} },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ edges: {
+ node: {
+ nameSingular: true,
+ namePlural: true,
+ labelSingular: true,
+ labelPlural: true,
+ isSystem: true,
+ isActive: true,
+ applicationId: true,
+ },
+ },
+ },
+ currentWorkspace: { workspaceCustomApplicationId: true },
+ });
+
+export const runMetadataObjectListCommand: CommandRun<
+ TargetCommandContext
+> = async ({ options, output, target, signal }) => {
+ const includeSystemObjects = readBooleanOption(options, 'all');
+ const client = createMetadataClient({ target, signal });
+ const [{ objects, currentWorkspace }, { applications, areOwnersNamed }] =
+ await Promise.all([fetchObjects(client), fetchOwnerApplications(client)]);
+
+ const objectNodes = await collectMetadataNodes(async (after) =>
+ after === undefined ? objects : (await fetchObjects(client, after)).objects,
+ );
+
+ if (!areOwnersNamed) {
+ output.warn({
+ code: 'OWNERS_UNAVAILABLE',
+ message:
+ 'Owners other than Custom show as unknown: listing apps needs the Applications permission.',
+ });
+ }
+
+ const resolveOwner = createMetadataOwnerResolver({
+ applications,
+ workspaceCustomApplicationId: currentWorkspace.workspaceCustomApplicationId,
+ });
+ const allObjects = objectNodes.map(({ applicationId, ...object }) => ({
+ ...object,
+ owner: resolveOwner(applicationId),
+ }));
+ const listedObjects = allObjects
+ .filter((object) => includeSystemObjects || !object.isSystem)
+ .sort((first, second) => {
+ const ownerKindDifference =
+ METADATA_OWNER_KIND_ORDER.indexOf(first.owner.kind) -
+ METADATA_OWNER_KIND_ORDER.indexOf(second.owner.kind);
+
+ if (ownerKindDifference !== 0) {
+ return ownerKindDifference;
+ }
+
+ return first.namePlural.localeCompare(second.namePlural);
+ });
+ const hiddenSystemObjectCount = allObjects.length - listedObjects.length;
+
+ return {
+ data: { objects: listedObjects, hiddenSystemObjectCount },
+ human: [
+ formatTable({
+ rows: listedObjects,
+ columns: [
+ { header: 'API NAME', value: (object) => object.namePlural },
+ {
+ header: 'LABEL',
+ value: (object) =>
+ object.isActive
+ ? object.labelPlural
+ : `${object.labelPlural} ${dimText('(inactive)')}`,
+ },
+ {
+ header: 'OWNER',
+ value: (object) => formatMetadataOwner(object.owner),
+ },
+ ],
+ }),
+ dimText(
+ hiddenSystemObjectCount > 0
+ ? `${listedObjects.length} objects · ${hiddenSystemObjectCount} system objects hidden, show them with --all`
+ : `${listedObjects.length} objects`,
+ ),
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/open/__tests__/open.spec.ts b/packages/twenty-cli/src/commands/open/__tests__/open.spec.ts
new file mode 100644
index 00000000000..50f376ee500
--- /dev/null
+++ b/packages/twenty-cli/src/commands/open/__tests__/open.spec.ts
@@ -0,0 +1,282 @@
+import { mkdtemp } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { openBrowser } from '@/oauth/open-browser';
+
+vi.mock('@/oauth/open-browser', () => ({ openBrowser: vi.fn() }));
+
+const SUBDOMAIN_URL = 'https://acme.twenty.com';
+
+const state: {
+ workspaceUrls: unknown;
+ discovery: unknown;
+ discoveryStatus: number;
+ metadataStatus: number;
+} = {
+ workspaceUrls: null,
+ discovery: null,
+ discoveryStatus: 200,
+ metadataStatus: 200,
+};
+
+const server = await startTestServer((request, response) => {
+ if (request.path === '/.well-known/oauth-authorization-server') {
+ sendJson(response, state.discoveryStatus, state.discovery);
+
+ return;
+ }
+
+ sendJson(response, state.metadataStatus, {
+ data: { currentWorkspace: { workspaceUrls: state.workspaceUrls } },
+ });
+});
+
+const stubStandardInput = ({ isTerminal }: { isTerminal: boolean }) =>
+ vi
+ .spyOn(process, 'stdin', 'get')
+ .mockReturnValue(createStandardInputStub({ isTerminal }));
+
+const runJson = async (args: string[]) => {
+ const { stdout, exitCode } = await runCliForTest(['open', ...args, '--json']);
+
+ return { envelope: parseSingleJsonLine(stdout), exitCode };
+};
+
+describe('open', () => {
+ beforeEach(async () => {
+ vi.stubEnv('HOME', await mkdtemp(join(tmpdir(), 'twenty-cli-open-')));
+ vi.stubEnv('CI', '');
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'open-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ stubStandardInput({ isTerminal: true });
+ state.workspaceUrls = { customUrl: null, subdomainUrl: SUBDOMAIN_URL };
+ state.discovery = {
+ authorization_endpoint: 'https://frontend.example/authorize?iss=api',
+ };
+ state.discoveryStatus = 200;
+ state.metadataStatus = 200;
+ server.requests.length = 0;
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ vi.mocked(openBrowser).mockReset();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ it('opens the workspace in the browser', async () => {
+ const { stdout, exitCode } = await runCliForTest(['open']);
+
+ expect(exitCode).toBe(0);
+ expect(openBrowser).toHaveBeenCalledTimes(1);
+ expect(openBrowser).toHaveBeenCalledWith(`${SUBDOMAIN_URL}/`);
+ expect(stdout).toContain(`Opening ${SUBDOMAIN_URL}/ in your browser.`);
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/metadata',
+ ]);
+ expect(server.requests[0].body).toContain('workspaceUrls');
+ });
+
+ it('prefers the custom domain and opens a page inside the workspace', async () => {
+ state.workspaceUrls = {
+ customUrl: 'https://crm.acme.com',
+ subdomainUrl: SUBDOMAIN_URL,
+ };
+
+ const { exitCode } = await runCliForTest(['open', 'settings/applications']);
+
+ expect(exitCode).toBe(0);
+ expect(openBrowser).toHaveBeenCalledWith(
+ 'https://crm.acme.com/settings/applications',
+ );
+ });
+
+ it('prints the address instead of opening a browser with --url-only', async () => {
+ const { envelope, exitCode } = await runJson([
+ '/objects/companies?view=all',
+ '--url-only',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toEqual({
+ url: `${SUBDOMAIN_URL}/objects/companies?view=all`,
+ });
+ expect(openBrowser).not.toHaveBeenCalled();
+
+ const human = await runCliForTest(['open', '--url-only']);
+
+ expect(human.stdout.trim()).toBe(`${SUBDOMAIN_URL}/`);
+ expect(openBrowser).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { name: 'JSON output', flags: ['--json'], isTerminal: true, ci: '' },
+ { name: '--no-input', flags: ['--no-input'], isTerminal: true, ci: '' },
+ { name: 'redirected stdin', flags: [], isTerminal: false, ci: '' },
+ { name: 'CI', flags: [], isTerminal: true, ci: 'true' },
+ ])('never opens a browser with $name', async ({ flags, isTerminal, ci }) => {
+ vi.stubEnv('CI', ci);
+ stubStandardInput({ isTerminal });
+
+ const { stdout, stderr, exitCode } = await runCliForTest([
+ 'open',
+ ...flags,
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(`${stdout}${stderr}`).toContain('--url-only');
+ expect(openBrowser).not.toHaveBeenCalled();
+ expect(server.requests).toHaveLength(0);
+ });
+
+ it.each([
+ 'https://evil.example/login',
+ 'http:evil.example/login',
+ '//evil.example/login',
+ '/\\evil.example/login',
+ '/.//evil.example/login',
+ 'foo/..//evil.example/login',
+ '/%2e//evil.example/login',
+ 'javascript:alert(1)',
+ ])('refuses %s as a page', async (page) => {
+ const { envelope, exitCode } = await runJson([page, '--url-only']);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.ok).toBe(false);
+ expect(envelope.error.code).toBe('USAGE');
+
+ const human = await runCliForTest(['open', page]);
+
+ expect(human.exitCode).toBe(2);
+ expect(openBrowser).not.toHaveBeenCalled();
+ });
+
+ it.each([null, {}, { customUrl: null, subdomainUrl: '' }])(
+ 'uses the discovery frontend origin when workspace URLs are missing: %j',
+ async (workspaceUrls) => {
+ state.workspaceUrls = workspaceUrls;
+ state.discovery = {
+ authorization_endpoint:
+ 'https://ignored-user:[email protected]/authorize?iss=api#fragment',
+ };
+
+ const { envelope, exitCode } = await runJson([
+ 'settings/applications',
+ '--url-only',
+ ]);
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data.url).toBe(
+ 'https://frontend.example/settings/applications',
+ );
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/metadata',
+ '/.well-known/oauth-authorization-server',
+ ]);
+ expect(server.requests[1].headers.authorization).toBeUndefined();
+
+ const human = await runCliForTest(['open']);
+
+ expect(human.exitCode).toBe(0);
+ expect(openBrowser).toHaveBeenCalledWith('https://frontend.example/');
+ },
+ );
+
+ it.each([
+ undefined,
+ '',
+ 'javascript:alert(1)',
+ 'file:///etc/passwd',
+ '/authorize',
+ ])(
+ 'rejects an invalid discovery frontend: %s',
+ async (authorizationEndpoint) => {
+ state.workspaceUrls = null;
+ state.discovery = { authorization_endpoint: authorizationEndpoint };
+
+ const { envelope, exitCode } = await runJson(['--url-only']);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(openBrowser).not.toHaveBeenCalled();
+ },
+ );
+
+ it('rejects a failed discovery response', async () => {
+ state.workspaceUrls = null;
+ state.discoveryStatus = 404;
+
+ const { envelope, exitCode } = await runJson(['--url-only']);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+ });
+
+ it('does not hide an authentication failure with the fallback', async () => {
+ state.workspaceUrls = null;
+ state.metadataStatus = 401;
+
+ const { envelope, exitCode } = await runJson(['--url-only']);
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error.code).toBe('AUTH_REQUIRED');
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/metadata',
+ ]);
+ });
+
+ it('still rejects pages that leave the discovered frontend', async () => {
+ state.workspaceUrls = null;
+
+ const { envelope, exitCode } = await runJson([
+ '/.//evil.example/login',
+ '--url-only',
+ ]);
+
+ expect(exitCode).toBe(2);
+ expect(envelope.error.code).toBe('USAGE');
+ expect(openBrowser).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { customUrl: null, subdomainUrl: 'javascript:alert(1)' },
+ { customUrl: 'file:///etc/passwd', subdomainUrl: SUBDOMAIN_URL },
+ ])(
+ 'refuses a workspace address it cannot open: %j',
+ async (workspaceUrls) => {
+ state.workspaceUrls = workspaceUrls;
+
+ const { envelope, exitCode } = await runJson(['--url-only']);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_RESPONSE');
+
+ const { exitCode: humanExitCode } = await runCliForTest(['open']);
+
+ expect(humanExitCode).toBe(1);
+ expect(openBrowser).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/commands/open/open.command-definition.ts b/packages/twenty-cli/src/commands/open/open.command-definition.ts
new file mode 100644
index 00000000000..d31811ee4b5
--- /dev/null
+++ b/packages/twenty-cli/src/commands/open/open.command-definition.ts
@@ -0,0 +1,32 @@
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const OPEN_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['open'],
+ description: 'Open the workspace in your browser',
+ helpGroup: HELP_GROUP.WORKSPACE,
+ arguments: [
+ {
+ name: 'page',
+ description: 'Page to open, for example settings/applications',
+ required: false,
+ },
+ ],
+ options: [
+ {
+ flags: '--url-only',
+ description: 'Print the address instead of opening a browser',
+ },
+ ],
+ examples: [
+ 'twenty open',
+ 'twenty open settings/applications',
+ 'twenty open --remote staging --url-only --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: true,
+ load: async () =>
+ (await import('@/commands/open/run-open-command')).runOpenCommand,
+};
diff --git a/packages/twenty-cli/src/commands/open/resolve-workspace-page-url.ts b/packages/twenty-cli/src/commands/open/resolve-workspace-page-url.ts
new file mode 100644
index 00000000000..18c5152b762
--- /dev/null
+++ b/packages/twenty-cli/src/commands/open/resolve-workspace-page-url.ts
@@ -0,0 +1,33 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const resolveWorkspacePageUrl = ({
+ workspaceUrl,
+ page,
+}: {
+ workspaceUrl: URL;
+ page: string | undefined;
+}) => {
+ if (!isDefined(page)) {
+ return workspaceUrl.href;
+ }
+
+ const pageUrl = URL.parse(page, workspaceUrl);
+
+ if (
+ !isDefined(pageUrl) ||
+ pageUrl.origin !== workspaceUrl.origin ||
+ pageUrl.pathname.startsWith('//')
+ ) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${page} is not a page of the workspace.`,
+ hint: 'Pass a path inside the workspace, for example settings/applications.',
+ });
+ }
+
+ return pageUrl.href;
+};
diff --git a/packages/twenty-cli/src/commands/open/run-open-command.ts b/packages/twenty-cli/src/commands/open/run-open-command.ts
new file mode 100644
index 00000000000..c4d6d56f9c8
--- /dev/null
+++ b/packages/twenty-cli/src/commands/open/run-open-command.ts
@@ -0,0 +1,45 @@
+import {
+ readBooleanOption,
+ readStringArgument,
+} from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
+import { resolveWorkspacePageUrl } from '@/commands/open/resolve-workspace-page-url';
+import { openBrowser } from '@/oauth/open-browser';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+import { fetchWorkspaceUrl } from '@/transport/metadata/fetch-workspace-url';
+
+export const runOpenCommand: CommandRun<TargetCommandContext> = async ({
+ arguments: commandArguments,
+ options,
+ outputMode,
+ target,
+ signal,
+}) => {
+ const isUrlOnly = readBooleanOption(options, 'urlOnly');
+
+ if (!isUrlOnly && !isInteractionAllowed({ options, outputMode })) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message:
+ 'twenty open only opens a browser in an interactive terminal, not with --no-input, JSON output, redirected stdin or in CI.',
+ hint: 'Add --url-only to print the address instead.',
+ });
+ }
+
+ const url = resolveWorkspacePageUrl({
+ workspaceUrl: await fetchWorkspaceUrl({ target, signal }),
+ page: readStringArgument(commandArguments, 0),
+ });
+
+ if (isUrlOnly) {
+ return { data: { url }, human: url };
+ }
+
+ openBrowser(url);
+
+ return { data: { url }, human: `Opening ${url} in your browser.` };
+};
diff --git a/packages/twenty-cli/src/commands/remote/list/remote-list.command-definition.ts b/packages/twenty-cli/src/commands/remote/list/remote-list.command-definition.ts
new file mode 100644
index 00000000000..c2ea22a3dd5
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/list/remote-list.command-definition.ts
@@ -0,0 +1,13 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const REMOTE_LIST_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['remote', 'list'],
+ description: 'List saved remotes',
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/remote/list/run-remote-list-command'))
+ .runRemoteListCommand,
+};
diff --git a/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts b/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts
new file mode 100644
index 00000000000..bcb4abe56e5
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/list/run-remote-list-command.ts
@@ -0,0 +1,51 @@
+import { isString } from '@sniptt/guards';
+
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { CREDENTIAL_KIND_LABELS } from '@/config/constants/credential-kind-labels.constant';
+import { getConfigPath } from '@/config/get-config-path';
+import { getCredentialKind } from '@/config/get-credential-kind';
+import { readConfig } from '@/config/read-config';
+import { formatTable } from '@/output/format-table';
+import { colorText, dimText } from '@/output/style';
+
+export const runRemoteListCommand: CommandRun = async () => {
+ const config = await readConfig(getConfigPath());
+ const remotes = Object.entries(config.remotes)
+ .map(([name, remote]) => ({
+ name,
+ apiUrl: remote.apiUrl,
+ credentials: getCredentialKind(remote),
+ workspaceName: isString(remote.workspaceName)
+ ? remote.workspaceName
+ : null,
+ isDefault: name === config.defaultRemote,
+ }))
+ .sort((first, second) => first.name.localeCompare(second.name));
+
+ if (remotes.length === 0) {
+ return {
+ data: { remotes, defaultRemote: null },
+ human: `No saved remotes. ${dimText('Sign in with: twenty auth login --with-token --url <url> --name <name>')}`,
+ };
+ }
+
+ return {
+ data: { remotes, defaultRemote: config.defaultRemote ?? null },
+ human: formatTable({
+ rows: remotes,
+ columns: [
+ {
+ header: ' ',
+ value: (remote) => (remote.isDefault ? colorText('green', '●') : ''),
+ },
+ { header: 'NAME', value: (remote) => remote.name },
+ { header: 'URL', value: (remote) => remote.apiUrl },
+ {
+ header: 'AUTH',
+ value: (remote) => CREDENTIAL_KIND_LABELS[remote.credentials],
+ },
+ { header: 'WORKSPACE', value: (remote) => remote.workspaceName ?? '' },
+ ],
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/remote/remove/remote-remove.command-definition.ts b/packages/twenty-cli/src/commands/remote/remove/remote-remove.command-definition.ts
new file mode 100644
index 00000000000..a5f2724ced0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/remove/remote-remove.command-definition.ts
@@ -0,0 +1,14 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const REMOTE_REMOVE_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['remote', 'remove'],
+ description: 'Remove a saved remote and its credentials',
+ arguments: [{ name: 'name', description: 'Saved remote', required: true }],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/remote/remove/run-remote-remove-command'))
+ .runRemoteRemoveCommand,
+};
diff --git a/packages/twenty-cli/src/commands/remote/remove/run-remote-remove-command.ts b/packages/twenty-cli/src/commands/remote/remove/run-remote-remove-command.ts
new file mode 100644
index 00000000000..cf4a23cbb90
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/remove/run-remote-remove-command.ts
@@ -0,0 +1,47 @@
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { getConfigPath } from '@/config/get-config-path';
+import { updateConfig } from '@/config/update-config';
+import { dimText, formatSuccessLine } from '@/output/style';
+import { findRemote } from '@/target/find-remote';
+
+export const runRemoteRemoveCommand: CommandRun = async ({
+ arguments: commandArguments,
+ signal,
+}) => {
+ const remoteName = readStringArgument(commandArguments, 0) ?? '';
+
+ const wasDefault = await updateConfig({
+ configPath: getConfigPath(),
+ signal,
+ update: (config) => {
+ findRemote(config, remoteName);
+
+ const { [remoteName]: _removedRemote, ...remotes } = config.remotes;
+ const { defaultRemote, ...configWithoutDefault } = config;
+ const isRemovingDefault = defaultRemote === remoteName;
+
+ return {
+ result: isRemovingDefault,
+ config: {
+ ...(isRemovingDefault ? configWithoutDefault : config),
+ remotes,
+ },
+ };
+ },
+ });
+
+ return {
+ data: { removed: remoteName, wasDefault },
+ human: [
+ formatSuccessLine(`Removed ${remoteName}.`),
+ ...(wasDefault
+ ? [
+ dimText(
+ ' There is no default remote now. Pick one with: twenty remote use <name>',
+ ),
+ ]
+ : []),
+ ].join('\n'),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/remote/rename/remote-rename.command-definition.ts b/packages/twenty-cli/src/commands/remote/rename/remote-rename.command-definition.ts
new file mode 100644
index 00000000000..88c81bdd049
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/rename/remote-rename.command-definition.ts
@@ -0,0 +1,17 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const REMOTE_RENAME_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['remote', 'rename'],
+ description: 'Rename a saved remote',
+ arguments: [
+ { name: 'current', description: 'Current name', required: true },
+ { name: 'new', description: 'New name', required: true },
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/remote/rename/run-remote-rename-command'))
+ .runRemoteRenameCommand,
+};
diff --git a/packages/twenty-cli/src/commands/remote/rename/run-remote-rename-command.ts b/packages/twenty-cli/src/commands/remote/rename/run-remote-rename-command.ts
new file mode 100644
index 00000000000..27b1ec4f5c1
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/rename/run-remote-rename-command.ts
@@ -0,0 +1,53 @@
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { getConfigPath } from '@/config/get-config-path';
+import { updateConfig } from '@/config/update-config';
+import { validateRemoteName } from '@/config/validate-remote-name';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatSuccessLine } from '@/output/style';
+import { findRemote } from '@/target/find-remote';
+
+export const runRemoteRenameCommand: CommandRun = async ({
+ arguments: commandArguments,
+ signal,
+}) => {
+ const currentName = readStringArgument(commandArguments, 0) ?? '';
+ const newName = validateRemoteName(
+ readStringArgument(commandArguments, 1) ?? '',
+ );
+
+ const isDefault = await updateConfig({
+ configPath: getConfigPath(),
+ signal,
+ update: (config) => {
+ const remote = findRemote(config, currentName);
+
+ if (Object.hasOwn(config.remotes, newName)) {
+ throw new CliError({
+ code: 'REMOTE_EXISTS',
+ exitCode: EXIT_CODE.USAGE,
+ message: `A remote named ${newName} already exists.`,
+ hint: `Pick another name, or remove it first: twenty remote remove ${newName}`,
+ });
+ }
+
+ const { [currentName]: _renamedRemote, ...otherRemotes } = config.remotes;
+ const wasDefault = config.defaultRemote === currentName;
+
+ return {
+ result: wasDefault,
+ config: {
+ ...config,
+ remotes: { ...otherRemotes, [newName]: remote },
+ ...(wasDefault ? { defaultRemote: newName } : {}),
+ },
+ };
+ },
+ });
+
+ return {
+ data: { previousName: currentName, name: newName, isDefault },
+ human: formatSuccessLine(`Renamed ${currentName} to ${newName}.`),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/remote/use/remote-use.command-definition.ts b/packages/twenty-cli/src/commands/remote/use/remote-use.command-definition.ts
new file mode 100644
index 00000000000..a5234b85d60
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/use/remote-use.command-definition.ts
@@ -0,0 +1,14 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const REMOTE_USE_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['remote', 'use'],
+ description: 'Make a saved remote the default',
+ arguments: [{ name: 'name', description: 'Saved remote', required: true }],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/remote/use/run-remote-use-command'))
+ .runRemoteUseCommand,
+};
diff --git a/packages/twenty-cli/src/commands/remote/use/run-remote-use-command.ts b/packages/twenty-cli/src/commands/remote/use/run-remote-use-command.ts
new file mode 100644
index 00000000000..9fdeff097d0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/remote/use/run-remote-use-command.ts
@@ -0,0 +1,28 @@
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { getConfigPath } from '@/config/get-config-path';
+import { updateConfig } from '@/config/update-config';
+import { dimText, formatSuccessLine } from '@/output/style';
+import { findRemote } from '@/target/find-remote';
+
+export const runRemoteUseCommand: CommandRun = async ({
+ arguments: commandArguments,
+ signal,
+}) => {
+ const remoteName = readStringArgument(commandArguments, 0) ?? '';
+ const remote = await updateConfig({
+ configPath: getConfigPath(),
+ signal,
+ update: (config) => ({
+ result: findRemote(config, remoteName),
+ config: { ...config, defaultRemote: remoteName },
+ }),
+ });
+
+ return {
+ data: { defaultRemote: remoteName, apiUrl: remote.apiUrl },
+ human: formatSuccessLine(
+ `Default remote is now ${remoteName} ${dimText(`(${remote.apiUrl})`)}`,
+ ),
+ };
+};
diff --git a/packages/twenty-cli/src/commands/version/run-version-command.ts b/packages/twenty-cli/src/commands/version/run-version-command.ts
new file mode 100644
index 00000000000..4781eef1b18
--- /dev/null
+++ b/packages/twenty-cli/src/commands/version/run-version-command.ts
@@ -0,0 +1,19 @@
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+import { dimText } from '@/output/style';
+
+export const runVersionCommand: CommandRun = async () => {
+ const versionInformation = {
+ version: CLI_VERSION,
+ node: process.versions.node,
+ platform: process.platform,
+ arch: process.arch,
+ };
+
+ return {
+ data: versionInformation,
+ human: `twenty ${versionInformation.version} ${dimText(
+ `(node ${versionInformation.node}, ${versionInformation.platform}-${versionInformation.arch})`,
+ )}`,
+ };
+};
diff --git a/packages/twenty-cli/src/commands/version/version.command-definition.ts b/packages/twenty-cli/src/commands/version/version.command-definition.ts
new file mode 100644
index 00000000000..3a747c572af
--- /dev/null
+++ b/packages/twenty-cli/src/commands/version/version.command-definition.ts
@@ -0,0 +1,14 @@
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const VERSION_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['version'],
+ description: 'Print version information',
+ helpGroup: HELP_GROUP.TOOLS,
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/version/run-version-command')).runVersionCommand,
+};
diff --git a/packages/twenty-cli/src/config/__tests__/read-config.spec.ts b/packages/twenty-cli/src/config/__tests__/read-config.spec.ts
new file mode 100644
index 00000000000..d2253b78a4d
--- /dev/null
+++ b/packages/twenty-cli/src/config/__tests__/read-config.spec.ts
@@ -0,0 +1,145 @@
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { readConfig } from '@/config/read-config';
+
+describe('readConfig', () => {
+ let configPath: string;
+
+ const writeConfig = (content: unknown) =>
+ writeFile(
+ configPath,
+ isString(content) ? content : JSON.stringify(content),
+ );
+
+ beforeEach(async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'twenty-cli-config-'));
+
+ configPath = join(directory, 'config.json');
+ });
+
+ it('treats a missing or empty file as an empty config', async () => {
+ await expect(readConfig(configPath)).resolves.toEqual({
+ version: 1,
+ remotes: {},
+ });
+
+ await writeConfig('');
+
+ await expect(readConfig(configPath)).resolves.toEqual({
+ version: 1,
+ remotes: {},
+ });
+ });
+
+ it('keeps version 1 names and unknown fields as they are', async () => {
+ await writeConfig({
+ version: 1,
+ defaultRemote: 'local',
+ futureSetting: { keep: true },
+ remotes: {
+ local: { apiUrl: 'http://localhost:3000', apiKey: 'local-key' },
+ default: {
+ apiUrl: 'https://prod.example.com',
+ apiKey: 'prod-key',
+ appRegistrationId: 'registration-1',
+ },
+ },
+ });
+
+ await expect(readConfig(configPath)).resolves.toEqual({
+ version: 1,
+ defaultRemote: 'local',
+ futureSetting: { keep: true },
+ remotes: {
+ local: { apiUrl: 'http://localhost:3000', apiKey: 'local-key' },
+ default: {
+ apiUrl: 'https://prod.example.com',
+ apiKey: 'prod-key',
+ appRegistrationId: 'registration-1',
+ },
+ },
+ });
+ });
+
+ it('reads the legacy profiles format without duplicating aliased secrets', async () => {
+ await writeConfig({
+ profiles: {
+ default: { apiUrl: 'http://localhost:2020', apiKey: 'local-key' },
+ prod: {
+ apiUrl: 'https://acme.twenty.com',
+ accessToken: 'access-token',
+ refreshToken: 'refresh-token',
+ },
+ },
+ defaultWorkspace: 'default',
+ otherSetting: 1,
+ });
+
+ await expect(readConfig(configPath)).resolves.toEqual({
+ version: 1,
+ defaultRemote: 'local',
+ otherSetting: 1,
+ remotes: {
+ local: { apiUrl: 'http://localhost:2020', apiKey: 'local-key' },
+ prod: {
+ apiUrl: 'https://acme.twenty.com',
+ twentyCLIAccessToken: 'access-token',
+ twentyCLIRefreshToken: 'refresh-token',
+ },
+ },
+ });
+ });
+
+ it('keeps a legacy default profile when local is already taken', async () => {
+ await writeConfig({
+ profiles: {
+ default: { apiUrl: 'https://prod.example.com' },
+ local: { apiUrl: 'http://localhost:2020' },
+ },
+ defaultWorkspace: 'default',
+ });
+
+ const config = await readConfig(configPath);
+
+ expect(Object.keys(config.remotes).sort()).toEqual(['default', 'local']);
+ expect(config.defaultRemote).toBe('default');
+ });
+
+ it('reads the legacy single-server format as the local remote', async () => {
+ await writeConfig({ apiUrl: 'http://localhost:2020', apiKey: 'key' });
+
+ await expect(readConfig(configPath)).resolves.toMatchObject({
+ remotes: { local: { apiUrl: 'http://localhost:2020', apiKey: 'key' } },
+ });
+ });
+
+ it('reports invalid JSON without quoting the file', async () => {
+ await writeConfig('{"apiKey": SECRET_SENTINEL_TOKEN_12345}');
+
+ const error = await readConfig(configPath).catch(
+ (caught: unknown) => caught,
+ );
+
+ expect(error).toMatchObject({ code: 'INVALID_CONFIG', exitCode: 2 });
+ expect(JSON.stringify(error)).not.toContain('SECRET');
+ expect(String(error)).not.toContain('SECRET');
+ });
+
+ it.each([
+ [{ version: 999, remotes: {} }, 'version 999 is not supported'],
+ [{ version: 1, remotes: { prod: { apiKey: 'no-url' } } }, 'apiUrl'],
+ [{ version: 1, remotes: {}, defaultRemote: 42 }, 'defaultRemote'],
+ ])('rejects %j', async (content, reason) => {
+ await writeConfig(content);
+
+ await expect(readConfig(configPath)).rejects.toMatchObject({
+ code: 'INVALID_CONFIG',
+ message: expect.stringContaining(reason),
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/config/__tests__/update-config.spec.ts b/packages/twenty-cli/src/config/__tests__/update-config.spec.ts
new file mode 100644
index 00000000000..943f726d862
--- /dev/null
+++ b/packages/twenty-cli/src/config/__tests__/update-config.spec.ts
@@ -0,0 +1,182 @@
+import { spawnSync } from 'node:child_process';
+import { mkdtemp, readFile, stat, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { updateConfig } from '@/config/update-config';
+
+const { configLock, SHORT_CONFIG_LOCK } = vi.hoisted(() => {
+ const SHORT_CONFIG_LOCK = {
+ TIMEOUT_MILLISECONDS: 500,
+ RETRY_MILLISECONDS: 10,
+ };
+
+ return { SHORT_CONFIG_LOCK, configLock: { ...SHORT_CONFIG_LOCK } };
+});
+
+vi.mock('@/config/constants/config-lock.constant', () => ({
+ CONFIG_LOCK: configLock,
+}));
+
+const CONCURRENT_UPDATE_LOCK_TIMEOUT_MILLISECONDS = 4_000;
+
+const INITIAL_CONFIG: ConfigFile = {
+ version: 1,
+ remotes: { dev: { apiUrl: 'http://localhost:3000' } },
+};
+
+const addRemote = (config: ConfigFile, name: string) => ({
+ result: name,
+ config: {
+ ...config,
+ remotes: { ...config.remotes, [name]: { apiUrl: `https://${name}.dev` } },
+ },
+});
+
+describe('updateConfig', () => {
+ let configPath: string;
+
+ const readConfigFile = async (): Promise<ConfigFile> =>
+ JSON.parse(await readFile(configPath, 'utf8'));
+
+ beforeEach(async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'twenty-cli-update-'));
+
+ configPath = join(directory, '.twenty', 'config.json');
+ Object.assign(configLock, SHORT_CONFIG_LOCK);
+ });
+
+ it('creates a private config directory and file', async () => {
+ await updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: (config) => addRemote(config, 'first'),
+ });
+
+ expect((await stat(dirname(configPath))).mode & 0o777).toBe(0o700);
+ expect((await stat(configPath)).mode & 0o777).toBe(0o600);
+ expect(Object.keys((await readConfigFile()).remotes)).toEqual(['first']);
+ });
+
+ it('keeps every write when updates run concurrently', async () => {
+ const names = Array.from({ length: 20 }, (_, index) => `remote-${index}`);
+
+ configLock.TIMEOUT_MILLISECONDS =
+ CONCURRENT_UPDATE_LOCK_TIMEOUT_MILLISECONDS;
+
+ await Promise.all(
+ names.map((name) =>
+ updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: (config) => addRemote(config, name),
+ }),
+ ),
+ );
+
+ expect(Object.keys((await readConfigFile()).remotes).sort()).toEqual(
+ [...names].sort(),
+ );
+ });
+
+ it('never overwrites an invalid config', async () => {
+ await updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: (config) => addRemote(config, 'first'),
+ });
+ await writeFile(configPath, '{ broken');
+
+ await expect(
+ updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: (config) => addRemote(config, 'second'),
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_CONFIG' });
+ expect(await readFile(configPath, 'utf8')).toBe('{ broken');
+ });
+
+ it('waits for a lock held by a running command, then says who holds it', async () => {
+ await updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: () => ({ result: null, config: INITIAL_CONFIG }),
+ });
+
+ const heldLock = JSON.stringify({ pid: process.pid, token: 'held' });
+
+ await writeFile(`${configPath}.lock`, heldLock);
+
+ await expect(
+ updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: (config) => addRemote(config, 'blocked'),
+ }),
+ ).rejects.toMatchObject({
+ code: 'CONFIG_LOCKED',
+ details: { ownerPid: process.pid },
+ });
+ expect(await readFile(`${configPath}.lock`, 'utf8')).toBe(heldLock);
+ expect(Object.keys((await readConfigFile()).remotes)).toEqual(['dev']);
+ });
+
+ it('never breaks a lock left by an exited command, and explains how to recover', async () => {
+ await updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: () => ({ result: null, config: INITIAL_CONFIG }),
+ });
+
+ const exitedProcess = spawnSync(process.execPath, ['-e', 'process.pid']);
+ const abandonedLock = JSON.stringify({
+ pid: exitedProcess.pid,
+ token: 'abandoned',
+ });
+
+ await writeFile(`${configPath}.lock`, abandonedLock);
+ configLock.TIMEOUT_MILLISECONDS = 125_000;
+ const signal = AbortSignal.timeout(2_000);
+
+ await expect(
+ updateConfig({
+ configPath,
+ signal,
+ update: (config) => addRemote(config, 'after-crash'),
+ }),
+ ).rejects.toMatchObject({
+ code: 'CONFIG_LOCKED',
+ hint: `Delete ${configPath}.lock and try again.`,
+ });
+ expect(await readFile(`${configPath}.lock`, 'utf8')).toBe(abandonedLock);
+ });
+
+ it('stops waiting for the lock when the command is cancelled', async () => {
+ await updateConfig({
+ configPath,
+ signal: new AbortController().signal,
+ update: () => ({ result: null, config: INITIAL_CONFIG }),
+ });
+ await writeFile(
+ `${configPath}.lock`,
+ JSON.stringify({ pid: process.pid, token: 'held' }),
+ );
+
+ const abortController = new AbortController();
+
+ setTimeout(() => abortController.abort(), 50);
+
+ await expect(
+ updateConfig({
+ configPath,
+ signal: abortController.signal,
+ update: (config) => addRemote(config, 'cancelled'),
+ }),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ expect(Object.keys((await readConfigFile()).remotes)).toEqual(['dev']);
+ });
+});
diff --git a/packages/twenty-cli/src/config/constants/config-file-mode.constant.ts b/packages/twenty-cli/src/config/constants/config-file-mode.constant.ts
new file mode 100644
index 00000000000..0933d891c3f
--- /dev/null
+++ b/packages/twenty-cli/src/config/constants/config-file-mode.constant.ts
@@ -0,0 +1,4 @@
+export const CONFIG_FILE_MODE = {
+ PRIVATE_DIRECTORY: 0o700,
+ PRIVATE_FILE: 0o600,
+} as const;
diff --git a/packages/twenty-cli/src/config/constants/config-lock.constant.ts b/packages/twenty-cli/src/config/constants/config-lock.constant.ts
new file mode 100644
index 00000000000..d32836a4659
--- /dev/null
+++ b/packages/twenty-cli/src/config/constants/config-lock.constant.ts
@@ -0,0 +1,7 @@
+import { REQUEST_TIMEOUT_MILLISECONDS } from '@/transport/constants/request-timeout-milliseconds.constant';
+
+export const CONFIG_LOCK = {
+ // OAuth refresh holds the lock across discovery and token exchange.
+ TIMEOUT_MILLISECONDS: 2 * REQUEST_TIMEOUT_MILLISECONDS + 5_000,
+ RETRY_MILLISECONDS: 50,
+} as const;
diff --git a/packages/twenty-cli/src/config/constants/credential-kind-labels.constant.ts b/packages/twenty-cli/src/config/constants/credential-kind-labels.constant.ts
new file mode 100644
index 00000000000..a39de189f84
--- /dev/null
+++ b/packages/twenty-cli/src/config/constants/credential-kind-labels.constant.ts
@@ -0,0 +1,5 @@
+export const CREDENTIAL_KIND_LABELS = {
+ apiKey: 'API key',
+ oauth: 'browser',
+ none: 'none',
+} as const;
diff --git a/packages/twenty-cli/src/config/get-config-path.ts b/packages/twenty-cli/src/config/get-config-path.ts
new file mode 100644
index 00000000000..42aa0979260
--- /dev/null
+++ b/packages/twenty-cli/src/config/get-config-path.ts
@@ -0,0 +1,4 @@
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+export const getConfigPath = () => join(homedir(), '.twenty', 'config.json');
diff --git a/packages/twenty-cli/src/config/get-credential-kind.ts b/packages/twenty-cli/src/config/get-credential-kind.ts
new file mode 100644
index 00000000000..f9e638d9080
--- /dev/null
+++ b/packages/twenty-cli/src/config/get-credential-kind.ts
@@ -0,0 +1,14 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type RemoteEntry } from '@/config/types/config-file.type';
+import { type CredentialKind } from '@/target/types/credential-kind.type';
+
+export const getCredentialKind = (
+ remote: RemoteEntry,
+): CredentialKind | 'none' => {
+ if (isNonEmptyString(remote.twentyCLIAccessToken)) {
+ return 'oauth';
+ }
+
+ return isNonEmptyString(remote.apiKey) ? 'apiKey' : 'none';
+};
diff --git a/packages/twenty-cli/src/config/normalize-config.ts b/packages/twenty-cli/src/config/normalize-config.ts
new file mode 100644
index 00000000000..bd646201541
--- /dev/null
+++ b/packages/twenty-cli/src/config/normalize-config.ts
@@ -0,0 +1,160 @@
+import { isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import {
+ type ConfigFile,
+ type RemoteEntry,
+} from '@/config/types/config-file.type';
+
+const LEGACY_DEFAULT_PROFILE_NAME = 'default';
+
+const LEGACY_REMOTE_NAME = 'local';
+
+const LEGACY_FIELD_ALIASES: Record<string, string[]> = {
+ twentyCLIAccessToken: ['accessToken', 'applicationAccessToken'],
+ twentyCLIRefreshToken: ['refreshToken', 'applicationRefreshToken'],
+ twentyCLIRegistrationClientId: ['oauthClientId'],
+};
+
+const LEGACY_ALIAS_FIELDS = Object.values(LEGACY_FIELD_ALIASES).flat();
+
+const LEGACY_TOP_LEVEL_REMOTE_FIELDS = [
+ 'apiUrl',
+ 'apiKey',
+ 'appRegistrationId',
+ 'appRegistrationClientId',
+ ...Object.entries(LEGACY_FIELD_ALIASES).flat(2),
+];
+
+const toRemoteEntry = (value: unknown): RemoteEntry | undefined => {
+ if (!isPlainObject(value) || !isString(value.apiUrl)) {
+ return undefined;
+ }
+
+ const aliasedFields = Object.fromEntries(
+ Object.entries(LEGACY_FIELD_ALIASES).flatMap(([field, aliases]) => {
+ const aliasValue = [field, ...aliases]
+ .map((name) => value[name])
+ .find(isString);
+
+ return isDefined(aliasValue) ? [[field, aliasValue]] : [];
+ }),
+ );
+
+ const fieldsWithoutAliases = Object.fromEntries(
+ Object.entries(value).filter(
+ ([field]) => !LEGACY_ALIAS_FIELDS.includes(field),
+ ),
+ );
+
+ return { ...fieldsWithoutAliases, apiUrl: value.apiUrl, ...aliasedFields };
+};
+
+const normalizeRemotes = (
+ value: unknown,
+): Record<string, RemoteEntry> | undefined => {
+ if (!isPlainObject(value)) {
+ return undefined;
+ }
+
+ const remotes: Record<string, RemoteEntry> = {};
+
+ for (const [name, entry] of Object.entries(value)) {
+ const remote = toRemoteEntry(entry);
+
+ if (!isDefined(remote)) {
+ return undefined;
+ }
+
+ remotes[name] = remote;
+ }
+
+ return remotes;
+};
+
+const renameLegacyDefaultRemote = (remotes: Record<string, RemoteEntry>) => {
+ if (
+ !Object.hasOwn(remotes, LEGACY_DEFAULT_PROFILE_NAME) ||
+ Object.hasOwn(remotes, LEGACY_REMOTE_NAME)
+ ) {
+ return { remotes, isRenamed: false };
+ }
+
+ const { [LEGACY_DEFAULT_PROFILE_NAME]: defaultProfile, ...otherRemotes } =
+ remotes;
+
+ return {
+ remotes: { ...otherRemotes, [LEGACY_REMOTE_NAME]: defaultProfile },
+ isRenamed: true,
+ };
+};
+
+const normalizeLegacyConfig = (
+ raw: Record<string, unknown>,
+): ConfigFile | undefined => {
+ const profileRemotes = normalizeRemotes(raw.profiles ?? {});
+ const currentRemotes = normalizeRemotes(raw.remotes ?? {});
+
+ if (!isDefined(profileRemotes) || !isDefined(currentRemotes)) {
+ return undefined;
+ }
+
+ const topLevelRemote = toRemoteEntry(
+ Object.fromEntries(
+ LEGACY_TOP_LEVEL_REMOTE_FIELDS.filter((field) => field in raw).map(
+ (field) => [field, raw[field]],
+ ),
+ ),
+ );
+ const otherFields = Object.fromEntries(
+ Object.entries(raw).filter(
+ ([field]) =>
+ !LEGACY_TOP_LEVEL_REMOTE_FIELDS.includes(field) &&
+ !['profiles', 'remotes', 'defaultWorkspace', 'version'].includes(field),
+ ),
+ );
+ const { remotes, isRenamed } = renameLegacyDefaultRemote({
+ ...profileRemotes,
+ ...currentRemotes,
+ });
+
+ if (
+ isDefined(topLevelRemote) &&
+ !Object.hasOwn(remotes, LEGACY_REMOTE_NAME)
+ ) {
+ remotes[LEGACY_REMOTE_NAME] = topLevelRemote;
+ }
+
+ const defaultRemote =
+ isRenamed && raw.defaultWorkspace === LEGACY_DEFAULT_PROFILE_NAME
+ ? LEGACY_REMOTE_NAME
+ : raw.defaultWorkspace;
+
+ return {
+ ...otherFields,
+ version: 1,
+ remotes,
+ ...(isString(defaultRemote) ? { defaultRemote } : {}),
+ };
+};
+
+export const normalizeConfig = (raw: unknown): ConfigFile | undefined => {
+ if (!isPlainObject(raw)) {
+ return undefined;
+ }
+
+ if (!isDefined(raw.version) && ('profiles' in raw || 'apiUrl' in raw)) {
+ return normalizeLegacyConfig(raw);
+ }
+
+ const remotes = normalizeRemotes(raw.remotes ?? {});
+
+ if (
+ !isDefined(remotes) ||
+ (isDefined(raw.defaultRemote) && !isString(raw.defaultRemote))
+ ) {
+ return undefined;
+ }
+
+ return { ...raw, version: 1, remotes };
+};
diff --git a/packages/twenty-cli/src/config/read-config.ts b/packages/twenty-cli/src/config/read-config.ts
new file mode 100644
index 00000000000..94b2a2f8b53
--- /dev/null
+++ b/packages/twenty-cli/src/config/read-config.ts
@@ -0,0 +1,88 @@
+import { readFile } from 'node:fs/promises';
+
+import { isNumber } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { normalizeConfig } from '@/config/normalize-config';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+const EMPTY_CONFIG: ConfigFile = { version: 1, remotes: {} };
+
+const createInvalidConfigError = (configPath: string, reason: string) =>
+ new CliError({
+ code: 'INVALID_CONFIG',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${configPath} is not a valid Twenty config: ${reason}`,
+ hint: 'Fix or move the file. It is never overwritten while it is invalid.',
+ details: { configPath },
+ });
+
+const JSON_ERROR_LOCATION_PATTERN = /line (\d+) column (\d+)/;
+
+const describeJsonSyntaxError = (error: unknown) => {
+ const location =
+ error instanceof Error
+ ? JSON_ERROR_LOCATION_PATTERN.exec(error.message)
+ : null;
+
+ return isDefined(location)
+ ? `invalid JSON at line ${location[1]}, column ${location[2]}.`
+ : 'invalid JSON.';
+};
+
+const readConfigText = async (configPath: string) => {
+ try {
+ return await readFile(configPath, 'utf8');
+ } catch (error) {
+ if (hasErrorCode(error, 'ENOENT')) {
+ return '';
+ }
+
+ throw new CliError({
+ code: 'INVALID_CONFIG',
+ exitCode: EXIT_CODE.USAGE,
+ message: `Could not read ${configPath}.`,
+ details: {
+ configPath,
+ reason: error instanceof Error ? error.message : String(error),
+ },
+ });
+ }
+};
+
+export const readConfig = async (configPath: string): Promise<ConfigFile> => {
+ const text = await readConfigText(configPath);
+
+ if (text.trim() === '') {
+ return EMPTY_CONFIG;
+ }
+
+ let raw: unknown;
+
+ try {
+ raw = JSON.parse(text);
+ } catch (error) {
+ throw createInvalidConfigError(configPath, describeJsonSyntaxError(error));
+ }
+
+ if (isPlainObject(raw) && isDefined(raw.version) && raw.version !== 1) {
+ throw createInvalidConfigError(
+ configPath,
+ `version ${isNumber(raw.version) ? raw.version : 'unknown'} is not supported by this CLI.`,
+ );
+ }
+
+ const config = normalizeConfig(raw);
+
+ if (!isDefined(config)) {
+ throw createInvalidConfigError(
+ configPath,
+ 'remotes need an apiUrl and defaultRemote must be a name.',
+ );
+ }
+
+ return config;
+};
diff --git a/packages/twenty-cli/src/config/replace-remote-credentials.ts b/packages/twenty-cli/src/config/replace-remote-credentials.ts
new file mode 100644
index 00000000000..4309db30a99
--- /dev/null
+++ b/packages/twenty-cli/src/config/replace-remote-credentials.ts
@@ -0,0 +1,33 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type RemoteEntry } from '@/config/types/config-file.type';
+import { type RemoteCredentials } from '@/config/types/remote-credentials.type';
+
+export const replaceRemoteCredentials = ({
+ remote,
+ credentials,
+}: {
+ remote: RemoteEntry;
+ credentials: RemoteCredentials;
+}): RemoteEntry => {
+ const {
+ apiKey: _apiKey,
+ twentyCLIAccessToken: _accessToken,
+ twentyCLIRefreshToken: _refreshToken,
+ twentyCLIRegistrationClientId: _clientId,
+ ...preservedFields
+ } = remote;
+
+ return {
+ ...preservedFields,
+ ...(credentials.kind === 'apiKey'
+ ? { apiKey: credentials.apiKey }
+ : {
+ twentyCLIAccessToken: credentials.accessToken,
+ twentyCLIRegistrationClientId: credentials.clientId,
+ ...(isDefined(credentials.refreshToken)
+ ? { twentyCLIRefreshToken: credentials.refreshToken }
+ : {}),
+ }),
+ };
+};
diff --git a/packages/twenty-cli/src/config/types/config-file.type.ts b/packages/twenty-cli/src/config/types/config-file.type.ts
new file mode 100644
index 00000000000..d95b3e6834b
--- /dev/null
+++ b/packages/twenty-cli/src/config/types/config-file.type.ts
@@ -0,0 +1,16 @@
+export type RemoteEntry = {
+ apiUrl: string;
+ apiKey?: string;
+ twentyCLIAccessToken?: string;
+ twentyCLIRefreshToken?: string;
+ twentyCLIRegistrationClientId?: string;
+ workspaceName?: string;
+ [field: string]: unknown;
+};
+
+export type ConfigFile = {
+ version: 1;
+ defaultRemote?: string;
+ remotes: Record<string, RemoteEntry>;
+ [field: string]: unknown;
+};
diff --git a/packages/twenty-cli/src/config/types/remote-credentials.type.ts b/packages/twenty-cli/src/config/types/remote-credentials.type.ts
new file mode 100644
index 00000000000..9abe6b8fdf9
--- /dev/null
+++ b/packages/twenty-cli/src/config/types/remote-credentials.type.ts
@@ -0,0 +1,8 @@
+export type RemoteCredentials =
+ | { kind: 'apiKey'; apiKey: string }
+ | {
+ kind: 'oauth';
+ accessToken: string;
+ refreshToken?: string;
+ clientId: string;
+ };
diff --git a/packages/twenty-cli/src/config/update-config.ts b/packages/twenty-cli/src/config/update-config.ts
new file mode 100644
index 00000000000..240fc3529a5
--- /dev/null
+++ b/packages/twenty-cli/src/config/update-config.ts
@@ -0,0 +1,26 @@
+import { readConfig } from '@/config/read-config';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { withConfigLock } from '@/config/with-config-lock';
+import { writeConfigAtomically } from '@/config/write-config-atomically';
+
+export const updateConfig = <TResult>({
+ configPath,
+ signal,
+ update,
+}: {
+ configPath: string;
+ signal: AbortSignal;
+ update: (config: ConfigFile) => { config: ConfigFile; result: TResult };
+}) =>
+ withConfigLock({
+ configPath,
+ signal,
+ operation: async () => {
+ const { config, result } = update(await readConfig(configPath));
+
+ signal.throwIfAborted();
+ await writeConfigAtomically(configPath, config);
+
+ return result;
+ },
+ });
diff --git a/packages/twenty-cli/src/config/validate-remote-name.ts b/packages/twenty-cli/src/config/validate-remote-name.ts
new file mode 100644
index 00000000000..6e67ce23877
--- /dev/null
+++ b/packages/twenty-cli/src/config/validate-remote-name.ts
@@ -0,0 +1,17 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const REMOTE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
+
+export const validateRemoteName = (remoteName: string) => {
+ if (!REMOTE_NAME_PATTERN.test(remoteName)) {
+ throw new CliError({
+ code: 'INVALID_REMOTE_NAME',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${remoteName} is not a valid remote name.`,
+ hint: 'Use letters, digits, dots, dashes and underscores, starting with a letter or digit.',
+ });
+ }
+
+ return remoteName;
+};
diff --git a/packages/twenty-cli/src/config/with-config-lock.ts b/packages/twenty-cli/src/config/with-config-lock.ts
new file mode 100644
index 00000000000..30e4a38edf7
--- /dev/null
+++ b/packages/twenty-cli/src/config/with-config-lock.ts
@@ -0,0 +1,134 @@
+import { randomUUID } from 'node:crypto';
+import { mkdir, open, readFile, rm } from 'node:fs/promises';
+import { dirname } from 'node:path';
+import { setTimeout as sleep } from 'node:timers/promises';
+
+import { isNumber, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CONFIG_FILE_MODE } from '@/config/constants/config-file-mode.constant';
+import { CONFIG_LOCK } from '@/config/constants/config-lock.constant';
+import { CliError } from '@/output/cli-error';
+import { hasErrorCode } from '@/utils/has-error-code';
+
+type LockOwner = { pid: number; token: string };
+
+const readLockOwner = async (
+ lockPath: string,
+): Promise<LockOwner | undefined> => {
+ try {
+ const owner: unknown = JSON.parse(await readFile(lockPath, 'utf8'));
+
+ return isPlainObject(owner) && isNumber(owner.pid) && isString(owner.token)
+ ? { pid: owner.pid, token: owner.token }
+ : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+const isProcessAlive = (processId: number) => {
+ try {
+ process.kill(processId, 0);
+
+ return true;
+ } catch (error) {
+ return hasErrorCode(error, 'EPERM');
+ }
+};
+
+const createLockedError = async (lockPath: string) => {
+ const owner = await readLockOwner(lockPath);
+ const isOwnerGone = isDefined(owner) && !isProcessAlive(owner.pid);
+ const ownerLabel = isDefined(owner) ? ` (pid ${owner.pid})` : '';
+
+ return new CliError({
+ code: 'CONFIG_LOCKED',
+ message: isOwnerGone
+ ? `A twenty command (pid ${owner.pid}) stopped without releasing ${lockPath}.`
+ : `Another twenty command${ownerLabel} is changing ${dirname(lockPath)}.`,
+ hint: isOwnerGone
+ ? `Delete ${lockPath} and try again.`
+ : `Try again when it finishes. If no twenty command is running, delete ${lockPath}.`,
+ details: { lockPath, ownerPid: owner?.pid ?? null },
+ });
+};
+
+const tryCreateLock = async (lockPath: string, token: string) => {
+ try {
+ const lock = await open(lockPath, 'wx', CONFIG_FILE_MODE.PRIVATE_FILE);
+
+ await lock.writeFile(JSON.stringify({ pid: process.pid, token }));
+ await lock.close();
+
+ return true;
+ } catch (error) {
+ if (hasErrorCode(error, 'EEXIST')) {
+ return false;
+ }
+
+ throw error;
+ }
+};
+
+const acquireLock = async ({
+ lockPath,
+ token,
+ signal,
+}: {
+ lockPath: string;
+ token: string;
+ signal: AbortSignal;
+}) => {
+ const deadline = Date.now() + CONFIG_LOCK.TIMEOUT_MILLISECONDS;
+ let isAcquired = await tryCreateLock(lockPath, token);
+
+ while (!isAcquired) {
+ signal.throwIfAborted();
+
+ const owner = await readLockOwner(lockPath);
+
+ if (
+ (isDefined(owner) && !isProcessAlive(owner.pid)) ||
+ Date.now() > deadline
+ ) {
+ throw await createLockedError(lockPath);
+ }
+
+ await sleep(CONFIG_LOCK.RETRY_MILLISECONDS, undefined, { signal });
+ isAcquired = await tryCreateLock(lockPath, token);
+ }
+};
+
+const releaseLock = async (lockPath: string, token: string) => {
+ const owner = await readLockOwner(lockPath);
+
+ if (owner?.token === token) {
+ await rm(lockPath, { force: true });
+ }
+};
+
+export const withConfigLock = async <TResult>({
+ configPath,
+ signal,
+ operation,
+}: {
+ configPath: string;
+ signal: AbortSignal;
+ operation: () => Promise<TResult>;
+}) => {
+ const lockPath = `${configPath}.lock`;
+ const token = randomUUID();
+
+ await mkdir(dirname(configPath), {
+ recursive: true,
+ mode: CONFIG_FILE_MODE.PRIVATE_DIRECTORY,
+ });
+ await acquireLock({ lockPath, token, signal });
+
+ try {
+ return await operation();
+ } finally {
+ await releaseLock(lockPath, token);
+ }
+};
diff --git a/packages/twenty-cli/src/config/write-config-atomically.ts b/packages/twenty-cli/src/config/write-config-atomically.ts
new file mode 100644
index 00000000000..b64040fe3a5
--- /dev/null
+++ b/packages/twenty-cli/src/config/write-config-atomically.ts
@@ -0,0 +1,29 @@
+import { randomUUID } from 'node:crypto';
+import { open, rename, rm } from 'node:fs/promises';
+
+import { CONFIG_FILE_MODE } from '@/config/constants/config-file-mode.constant';
+import { type ConfigFile } from '@/config/types/config-file.type';
+
+export const writeConfigAtomically = async (
+ configPath: string,
+ config: ConfigFile,
+) => {
+ const temporaryPath = `${configPath}.${process.pid}.${randomUUID()}.tmp`;
+ const temporaryFile = await open(
+ temporaryPath,
+ 'wx',
+ CONFIG_FILE_MODE.PRIVATE_FILE,
+ );
+
+ try {
+ await temporaryFile.writeFile(`${JSON.stringify(config, null, 2)}\n`);
+ await temporaryFile.sync();
+ await temporaryFile.close();
+ await rename(temporaryPath, configPath);
+ } catch (error) {
+ await temporaryFile.close().catch(() => undefined);
+ await rm(temporaryPath, { force: true });
+
+ throw error;
+ }
+};
diff --git a/packages/twenty-cli/src/constants/cli-version.constant.ts b/packages/twenty-cli/src/constants/cli-version.constant.ts
new file mode 100644
index 00000000000..2f238dc66d1
--- /dev/null
+++ b/packages/twenty-cli/src/constants/cli-version.constant.ts
@@ -0,0 +1,3 @@
+import { version } from '../../package.json';
+
+export const CLI_VERSION = version;
diff --git a/packages/twenty-cli/src/data/assert-data-result-limit.ts b/packages/twenty-cli/src/data/assert-data-result-limit.ts
new file mode 100644
index 00000000000..6a627fb1dbd
--- /dev/null
+++ b/packages/twenty-cli/src/data/assert-data-result-limit.ts
@@ -0,0 +1,22 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { RESPONSE_BYTE_LIMIT } from '@/transport/constants/response-byte-limit.constant';
+import { RESULT_ITEM_LIMIT } from '@/transport/constants/result-item-limit.constant';
+
+export const assertDataResultLimit = ({
+ recordCount,
+ bytes,
+}: {
+ recordCount: number;
+ bytes: number;
+}) => {
+ if (recordCount > RESULT_ITEM_LIMIT || bytes > RESPONSE_BYTE_LIMIT) {
+ throw new CliError({
+ code: 'RESULT_LIMIT_EXCEEDED',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'Records exceed the 10,000-item or 16 MiB result limit.',
+ hint: 'Use data list <object> --all --format ndjson to stream records, or request fewer records.',
+ details: { recordCount, bytes },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/data/format-data-page.ts b/packages/twenty-cli/src/data/format-data-page.ts
new file mode 100644
index 00000000000..4a01620c983
--- /dev/null
+++ b/packages/twenty-cli/src/data/format-data-page.ts
@@ -0,0 +1,64 @@
+import { assertDataResultLimit } from '@/data/assert-data-result-limit';
+import { formatDataCell } from '@/data/format-data-value';
+import { type readDataListOptions } from '@/data/read-data-list-options';
+import { type DataPage, type DataRecord } from '@/data/types/data-page.type';
+import { TABLE_LAYOUT } from '@/output/constants/table-layout.constant';
+import { formatTable } from '@/output/format-table';
+
+const getDataCell = (record: DataRecord, field: string) =>
+ formatDataCell(Object.hasOwn(record, field) ? record[field] : undefined);
+
+export const formatDataPage = ({
+ page,
+ options,
+}: {
+ page: DataPage;
+ options: ReturnType<typeof readDataListOptions>;
+}) => {
+ const availableFields = Object.keys(page.records[0] ?? {});
+ const fields =
+ options.fields ??
+ [
+ ...['id', 'name'].filter((field) => availableFields.includes(field)),
+ ...availableFields.filter((field) => field !== 'id' && field !== 'name'),
+ ].slice(0, 5);
+
+ let rowWidth = TABLE_LAYOUT.ROW_INDENT.length;
+ let extraBytes = 0;
+
+ for (const field of fields) {
+ const header = formatDataCell(field);
+ let columnWidth = header.length;
+
+ extraBytes += Buffer.byteLength(header, 'utf8') - header.length;
+
+ for (const record of page.records) {
+ const cell = getDataCell(record, field);
+
+ columnWidth = Math.max(columnWidth, cell.length);
+ extraBytes += Buffer.byteLength(cell, 'utf8') - cell.length;
+ }
+
+ rowWidth += columnWidth + TABLE_LAYOUT.COLUMN_GAP.length;
+ }
+
+ assertDataResultLimit({
+ recordCount: page.records.length,
+ bytes: rowWidth * (page.records.length + 1) + extraBytes,
+ });
+ const table =
+ page.records.length === 0
+ ? 'No records.'
+ : formatTable({
+ rows: page.records,
+ columns: fields.map((field) => ({
+ header: formatDataCell(field),
+ value: (record: DataRecord) => getDataCell(record, field),
+ })),
+ });
+ const footer = `${page.records.length} of ${page.totalCount} records`;
+
+ return page.pageInfo.hasNextPage
+ ? `${table}\n${footer} · --all for every page · --json for the next cursor`
+ : `${table}\n${footer}`;
+};
diff --git a/packages/twenty-cli/src/data/format-data-value.ts b/packages/twenty-cli/src/data/format-data-value.ts
new file mode 100644
index 00000000000..d759b2e76ac
--- /dev/null
+++ b/packages/twenty-cli/src/data/format-data-value.ts
@@ -0,0 +1,83 @@
+import { isArray, isNonEmptyString, isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+const RECORD_LABEL_FIELDS = ['name', 'title', 'subject'];
+const RECORD_PREVIEW_COUNT = 3;
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ isPlainObject(value) && isNonEmptyString(value.id);
+
+const findRecordLabel = (record: Record<string, unknown>) =>
+ RECORD_LABEL_FIELDS.map((field) => record[field]).find(isDefined);
+
+const truncateText = (text: string, maxLength: number) =>
+ text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
+
+const formatDataList = (values: unknown[]) => {
+ if (values.length === 0) {
+ return '-';
+ }
+
+ if (values.every(isRecord)) {
+ const labels = values
+ .slice(0, RECORD_PREVIEW_COUNT)
+ .map((record) => formatDataValue(findRecordLabel(record) ?? record.id));
+ const more = values.length > RECORD_PREVIEW_COUNT ? ', …' : '';
+
+ return `${values.length} ${values.length === 1 ? 'record' : 'records'} returned · ${labels.join(', ')}${more}`;
+ }
+
+ return values.some((value) => isPlainObject(value) || isArray(value))
+ ? JSON.stringify(values)
+ : values.map(formatDataValue).join(', ');
+};
+
+export const formatDataValue = (value: unknown): string => {
+ if (!isDefined(value)) {
+ return '-';
+ }
+
+ if (isString(value)) {
+ return /[\x00-\x1f\x7f-\x9f]/.test(value)
+ ? JSON.stringify(value).replace(
+ /[\x7f-\x9f]/g,
+ (character) =>
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,
+ )
+ : value;
+ }
+
+ if (isArray(value)) {
+ return formatDataList(value);
+ }
+
+ if (isPlainObject(value)) {
+ if (isNonEmptyString(value.firstName) || isNonEmptyString(value.lastName)) {
+ return formatDataValue(
+ [value.firstName, value.lastName].filter(isNonEmptyString).join(' '),
+ );
+ }
+
+ if (isNonEmptyString(value.primaryEmail)) {
+ return formatDataValue(value.primaryEmail);
+ }
+
+ if (isNonEmptyString(value.primaryLinkUrl)) {
+ return formatDataValue(value.primaryLinkUrl);
+ }
+
+ const label = isRecord(value) ? findRecordLabel(value) : undefined;
+
+ if (isDefined(label)) {
+ return `${formatDataValue(label)} (${formatDataValue(value.id)})`;
+ }
+ }
+
+ return JSON.stringify(value);
+};
+
+export const formatDataCell = (value: unknown) =>
+ truncateText(formatDataValue(value), 60);
+
+export const formatDataDetail = (value: unknown) =>
+ truncateText(formatDataValue(value), 120);
diff --git a/packages/twenty-cli/src/data/iterate-data-pages.ts b/packages/twenty-cli/src/data/iterate-data-pages.ts
new file mode 100644
index 00000000000..b35e4cd9e65
--- /dev/null
+++ b/packages/twenty-cli/src/data/iterate-data-pages.ts
@@ -0,0 +1,50 @@
+import { type DataPage } from '@/data/types/data-page.type';
+import { CliError } from '@/output/cli-error';
+
+export async function* iterateDataPages({
+ fetchPage,
+ cursor,
+ signal,
+}: {
+ fetchPage: (cursor?: string) => Promise<DataPage>;
+ cursor?: string;
+ signal: AbortSignal;
+}) {
+ let pageCursor = cursor;
+ let checkpoint = cursor;
+ let checkpointInterval = 1;
+ let pagesSinceCheckpoint = 0;
+ let hasNextPage = true;
+
+ while (hasNextPage) {
+ signal.throwIfAborted();
+ const page = await fetchPage(pageCursor);
+ signal.throwIfAborted();
+ const nextCursor = page.pageInfo.endCursor ?? undefined;
+
+ if (
+ page.records.length > 0 &&
+ (nextCursor === pageCursor || nextCursor === checkpoint)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned a repeated pagination cursor.',
+ });
+ }
+
+ hasNextPage = page.pageInfo.hasNextPage;
+
+ if (hasNextPage) {
+ pagesSinceCheckpoint += 1;
+
+ if (pagesSinceCheckpoint === checkpointInterval) {
+ checkpoint = nextCursor;
+ checkpointInterval *= 2;
+ pagesSinceCheckpoint = 0;
+ }
+ }
+
+ yield page;
+ pageCursor = nextCursor;
+ }
+}
diff --git a/packages/twenty-cli/src/data/parse-data-response.ts b/packages/twenty-cli/src/data/parse-data-response.ts
new file mode 100644
index 00000000000..44ff770f189
--- /dev/null
+++ b/packages/twenty-cli/src/data/parse-data-response.ts
@@ -0,0 +1,93 @@
+import {
+ isArray,
+ isBoolean,
+ isNonEmptyString,
+ isNull,
+ isNumber,
+ isUndefined,
+} from '@sniptt/guards';
+import { isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
+
+import { type DataPage } from '@/data/types/data-page.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const createInvalidResponseError = () =>
+ new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server returned an invalid record response.',
+ });
+
+const isCursor = (value: unknown): value is string | null =>
+ isNull(value) || isNonEmptyString(value);
+
+export const parseDataPage = (
+ body: unknown,
+ objectName: string,
+ limit: number,
+): DataPage => {
+ if (!isPlainObject(body) || !isPlainObject(body.data)) {
+ throw createInvalidResponseError();
+ }
+
+ const records = body.data[objectName];
+ const pageInfo = body.pageInfo;
+ const totalCount = body.totalCount;
+
+ if (
+ !isArray(records) ||
+ records.length > limit ||
+ !records.every(isPlainObject) ||
+ !isPlainObject(pageInfo) ||
+ !isBoolean(pageInfo.hasNextPage) ||
+ (!isUndefined(pageInfo.hasPreviousPage) &&
+ !isBoolean(pageInfo.hasPreviousPage)) ||
+ !isCursor(pageInfo.startCursor) ||
+ !isCursor(pageInfo.endCursor) ||
+ (isNonEmptyArray(records) &&
+ (!isNonEmptyString(pageInfo.startCursor) ||
+ !isNonEmptyString(pageInfo.endCursor))) ||
+ (pageInfo.hasNextPage &&
+ (!isNonEmptyArray(records) || !isNonEmptyString(pageInfo.endCursor))) ||
+ !isNumber(totalCount) ||
+ !Number.isSafeInteger(totalCount) ||
+ totalCount < 0
+ ) {
+ throw createInvalidResponseError();
+ }
+
+ return {
+ records,
+ pageInfo: {
+ hasNextPage: pageInfo.hasNextPage,
+ ...(isBoolean(pageInfo.hasPreviousPage)
+ ? { hasPreviousPage: pageInfo.hasPreviousPage }
+ : {}),
+ startCursor: pageInfo.startCursor,
+ endCursor: pageInfo.endCursor,
+ },
+ totalCount,
+ };
+};
+
+export const parseDataRecord = (body: unknown, objectName: string) => {
+ if (!isPlainObject(body) || !isPlainObject(body.data)) {
+ throw createInvalidResponseError();
+ }
+
+ const record = body.data[objectName];
+
+ if (isNull(record)) {
+ throw new CliError({
+ code: 'NOT_FOUND',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: `No ${objectName} record has that id.`,
+ });
+ }
+
+ if (!isPlainObject(record)) {
+ throw createInvalidResponseError();
+ }
+
+ return record;
+};
diff --git a/packages/twenty-cli/src/data/read-data-list-options.ts b/packages/twenty-cli/src/data/read-data-list-options.ts
new file mode 100644
index 00000000000..b3ef65f7abc
--- /dev/null
+++ b/packages/twenty-cli/src/data/read-data-list-options.ts
@@ -0,0 +1,49 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const readDataListOptions = (options: Record<string, unknown>) => {
+ const limitText = readStringOption(options, 'limit') ?? '50';
+ const limit = Number(limitText);
+ const fieldsText = readStringOption(options, 'fields');
+ const fields = fieldsText?.split(',').map((field) => field.trim());
+ const cursor = readStringOption(options, 'cursor');
+
+ if (
+ !/^\d+$/.test(limitText) ||
+ !Number.isInteger(limit) ||
+ limit < 1 ||
+ limit > 200
+ ) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: '--limit must be an integer between 1 and 200.',
+ });
+ }
+
+ if (
+ fields?.some((field) => field.length === 0) ||
+ (isDefined(cursor) && cursor.length === 0)
+ ) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: '--fields and --cursor cannot contain empty values.',
+ });
+ }
+
+ return {
+ limit,
+ fields: isDefined(fields) ? [...new Set(fields)] : undefined,
+ cursor,
+ filter: readStringOption(options, 'filter'),
+ orderBy: readStringOption(options, 'orderBy'),
+ all: readBooleanOption(options, 'all'),
+ };
+};
diff --git a/packages/twenty-cli/src/data/types/data-page.type.ts b/packages/twenty-cli/src/data/types/data-page.type.ts
new file mode 100644
index 00000000000..05eb03d4171
--- /dev/null
+++ b/packages/twenty-cli/src/data/types/data-page.type.ts
@@ -0,0 +1,14 @@
+export type DataRecord = Record<string, unknown>;
+
+export type DataPageInfo = {
+ hasNextPage: boolean;
+ hasPreviousPage?: boolean;
+ startCursor: string | null;
+ endCursor: string | null;
+};
+
+export type DataPage = {
+ records: DataRecord[];
+ pageInfo: DataPageInfo;
+ totalCount: number;
+};
diff --git a/packages/twenty-cli/src/doctor/format-doctor-checks.ts b/packages/twenty-cli/src/doctor/format-doctor-checks.ts
new file mode 100644
index 00000000000..bbbc0b16908
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/format-doctor-checks.ts
@@ -0,0 +1,12 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+
+export const formatDoctorChecks = (checks: DoctorCheck[]) =>
+ checks
+ .map((check) => {
+ const hint = isDefined(check.hint) ? `\n ${check.hint}` : '';
+
+ return `[${check.status.toUpperCase()}] ${check.id}: ${check.message}${hint}`;
+ })
+ .join('\n');
diff --git a/packages/twenty-cli/src/doctor/get-connection-doctor-checks.ts b/packages/twenty-cli/src/doctor/get-connection-doctor-checks.ts
new file mode 100644
index 00000000000..9d6a3b9568f
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/get-connection-doctor-checks.ts
@@ -0,0 +1,258 @@
+import { stat } from 'node:fs/promises';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { readConfig } from '@/config/read-config';
+import { CONFIG_FILE_MODE } from '@/config/constants/config-file-mode.constant';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+import { getMetadataDoctorFailure } from '@/doctor/get-metadata-doctor-failure';
+import { getAccessTokenExpiry } from '@/oauth/is-access-token-expiring';
+import { CliError } from '@/output/cli-error';
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { parseApiUrl } from '@/target/parse-api-url';
+import { selectTarget } from '@/target/select-target';
+import { toPublicTarget } from '@/target/to-public-target';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { fetchSignedInIdentity } from '@/transport/metadata/fetch-signed-in-identity';
+
+export const getConnectionDoctorChecks = async ({
+ configPath,
+ environment,
+ remoteFlag,
+ offline,
+ signal,
+}: {
+ configPath: string;
+ environment: NodeJS.ProcessEnv;
+ remoteFlag: string | undefined;
+ offline: boolean;
+ signal: AbortSignal;
+}): Promise<DoctorCheck[]> => {
+ const checks: DoctorCheck[] = [];
+ let config: ConfigFile | undefined;
+ let configError: unknown;
+
+ signal.throwIfAborted();
+
+ try {
+ config = await readConfig(configPath);
+ checks.push({
+ id: 'configuration',
+ status: 'pass',
+ message: `CLI configuration checked at ${configPath}.`,
+ details: {
+ path: configPath,
+ remoteCount: Object.keys(config.remotes).length,
+ defaultRemote: config.defaultRemote ?? null,
+ },
+ });
+
+ if (process.platform !== 'win32') {
+ const configStats = await stat(configPath).catch(() => undefined);
+
+ if (isDefined(configStats) && (configStats.mode & 0o077) !== 0) {
+ checks.push({
+ id: 'configuration-permissions',
+ status: 'warning',
+ message: 'Other users may access the CLI configuration file.',
+ hint: `Review its permissions; ${CONFIG_FILE_MODE.PRIVATE_FILE.toString(8)} is the expected mode. Doctor does not change them.`,
+ });
+ }
+ }
+ } catch (error) {
+ configError = error;
+ checks.push({
+ id: 'configuration',
+ status: 'fail',
+ code: error instanceof CliError ? error.code : 'INVALID_CONFIG',
+ message:
+ error instanceof CliError
+ ? error.message
+ : 'The CLI configuration is unreadable or invalid.',
+ hint:
+ error instanceof CliError
+ ? error.hint
+ : `Check ${configPath}. Doctor does not overwrite it.`,
+ });
+ }
+
+ let target: ResolvedTarget;
+
+ try {
+ const selection = await selectTarget({
+ environment,
+ remoteFlag,
+ loadConfig: async () => {
+ if (!isDefined(config)) {
+ throw configError;
+ }
+
+ return config;
+ },
+ warn: (warning) =>
+ checks.push({
+ id: 'target-precedence',
+ status: 'warning',
+ code: warning.code,
+ message: warning.message,
+ }),
+ });
+ const apiUrl = parseApiUrl({
+ rawUrl:
+ selection.source === 'remote'
+ ? selection.remote.apiUrl
+ : selection.apiUrl,
+ sourceName:
+ selection.source === 'remote'
+ ? `The URL of remote ${selection.remoteName}`
+ : TARGET_ENVIRONMENT_VARIABLE.API_URL,
+ });
+ const publicTarget = {
+ apiUrl,
+ source: selection.source,
+ remote: selection.source === 'remote' ? selection.remoteName : null,
+ };
+
+ checks.push({
+ id: 'target',
+ status: 'pass',
+ message: `Selected ${apiUrl} from ${selection.source}.`,
+ details: publicTarget,
+ });
+
+ const accessToken =
+ selection.source === 'remote'
+ ? selection.remote.twentyCLIAccessToken
+ : undefined;
+ const credentialKind = isNonEmptyString(accessToken) ? 'oauth' : 'apiKey';
+ const apiKey =
+ selection.source === 'remote'
+ ? selection.remote.apiKey
+ : selection.apiKey;
+ const bearerToken = isNonEmptyString(accessToken) ? accessToken : apiKey;
+
+ if (!isNonEmptyString(bearerToken)) {
+ checks.push({
+ id: 'credentials',
+ status: 'fail',
+ code: 'AUTH_REQUIRED',
+ message: 'The selected remote has no saved credentials.',
+ hint: 'Sign in with twenty auth login, then rerun doctor.',
+ });
+
+ return [
+ ...checks,
+ {
+ id: 'metadata-api',
+ status: 'skipped',
+ message: 'No credentials are available.',
+ },
+ ];
+ }
+
+ const expiry =
+ credentialKind === 'oauth'
+ ? getAccessTokenExpiry(bearerToken)
+ : undefined;
+
+ if (isDefined(expiry) && expiry <= Date.now()) {
+ const canAttemptRenewal =
+ selection.source === 'remote' &&
+ isNonEmptyString(selection.remote.twentyCLIRefreshToken);
+
+ checks.push({
+ id: 'credentials',
+ status: canAttemptRenewal ? 'warning' : 'fail',
+ code: 'AUTH_REQUIRED',
+ message: canAttemptRenewal
+ ? 'The OAuth access token has expired. A refresh token is saved, but renewal has not been verified.'
+ : 'The saved OAuth access token has expired and no refresh token is available.',
+ hint: 'Run twenty auth status with the same remote to refresh the session, or sign in again. Doctor does not refresh credentials.',
+ });
+
+ return [
+ ...checks,
+ {
+ id: 'metadata-api',
+ status: 'skipped',
+ message: 'The access token has expired.',
+ },
+ ];
+ }
+
+ target = {
+ apiUrl,
+ source: selection.source,
+ ...(selection.source === 'remote'
+ ? { remoteName: selection.remoteName }
+ : {}),
+ credentialKind,
+ bearerToken,
+ };
+ checks.push({
+ id: 'credentials',
+ status: 'pass',
+ message: `${credentialKind === 'oauth' ? 'OAuth token' : 'API key'} configured; acceptance is checked separately.`,
+ details: { kind: credentialKind },
+ });
+ } catch (error) {
+ signal.throwIfAborted();
+
+ const code = error instanceof CliError ? error.code : 'INTERNAL_ERROR';
+
+ checks.push({
+ id: 'target',
+ status: code === 'TARGET_REQUIRED' ? 'skipped' : 'fail',
+ code,
+ message:
+ error instanceof CliError
+ ? error.message
+ : 'Could not select a workspace.',
+ hint: error instanceof CliError ? error.hint : undefined,
+ });
+
+ return [
+ ...checks,
+ {
+ id: 'credentials',
+ status: 'skipped',
+ message: 'No workspace was selected.',
+ },
+ {
+ id: 'metadata-api',
+ status: 'skipped',
+ message: 'No workspace was selected.',
+ },
+ ];
+ }
+
+ if (offline) {
+ return [
+ ...checks,
+ {
+ id: 'metadata-api',
+ status: 'skipped',
+ message: 'Network checks disabled by --offline.',
+ },
+ ];
+ }
+
+ try {
+ signal.throwIfAborted();
+ await fetchSignedInIdentity({ target, signal });
+ checks.push({
+ id: 'metadata-api',
+ status: 'pass',
+ message: 'The metadata endpoint accepted the configured credentials.',
+ details: { ...toPublicTarget(target) },
+ });
+ } catch (error) {
+ signal.throwIfAborted();
+
+ checks.push(getMetadataDoctorFailure(error));
+ }
+
+ return checks;
+};
diff --git a/packages/twenty-cli/src/doctor/get-metadata-doctor-failure.ts b/packages/twenty-cli/src/doctor/get-metadata-doctor-failure.ts
new file mode 100644
index 00000000000..032cae2e79c
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/get-metadata-doctor-failure.ts
@@ -0,0 +1,94 @@
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+import { CliError } from '@/output/cli-error';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+
+const FAILURE_MESSAGES: Partial<
+ Record<CliErrorCode, { message: string; hint: string }>
+> = {
+ AUTH_REQUIRED: {
+ message: 'The metadata endpoint rejected these credentials.',
+ hint: 'Check the configured credentials, or sign in again.',
+ },
+ PERMISSION_DENIED: {
+ message: 'The metadata endpoint denied access to the workspace identity.',
+ hint: 'Check the selected remote and the permissions granted to its credentials.',
+ },
+ INVALID_RESPONSE: {
+ message: 'The server did not return a valid metadata API response.',
+ hint: 'Check the API URL and base path, and whether a proxy returned another page.',
+ },
+ UNSUPPORTED_RESPONSE_TYPE: {
+ message: 'The metadata endpoint returned an unsupported response type.',
+ hint: 'Check the API URL and base path, and whether a proxy returned another page.',
+ },
+ REDIRECT_NOT_FOLLOWED: {
+ message:
+ 'The metadata endpoint redirected the request. No redirect was followed.',
+ hint: 'Configure the final Twenty API URL, including the correct protocol and base path.',
+ },
+ TIMEOUT: {
+ message:
+ 'The metadata endpoint did not respond before the request timed out.',
+ hint: 'Check server availability and the network connection.',
+ },
+ NETWORK_ERROR: {
+ message: 'Could not connect to the metadata endpoint.',
+ hint: 'Check the API URL, network connection, server availability and TLS configuration.',
+ },
+};
+
+const NETWORK_FAILURE_MESSAGES: Partial<Record<string, string>> = {
+ ENOTFOUND: 'DNS could not resolve the metadata endpoint hostname.',
+ EAI_AGAIN: 'DNS resolution of the metadata endpoint temporarily failed.',
+ ECONNREFUSED: 'The metadata endpoint refused the connection.',
+ ECONNRESET: 'The connection to the metadata endpoint was reset.',
+ EHOSTUNREACH: 'The metadata endpoint host is unreachable.',
+ ENETUNREACH: 'The network containing the metadata endpoint is unreachable.',
+ ETIMEDOUT: 'The connection to the metadata endpoint timed out.',
+ UND_ERR_CONNECT_TIMEOUT: 'The connection to the metadata endpoint timed out.',
+ CERT_HAS_EXPIRED: 'The metadata endpoint TLS certificate has expired.',
+ ERR_TLS_CERT_ALTNAME_INVALID:
+ 'The metadata endpoint TLS certificate does not match its hostname.',
+ DEPTH_ZERO_SELF_SIGNED_CERT:
+ 'The metadata endpoint uses an untrusted self-signed TLS certificate.',
+ SELF_SIGNED_CERT_IN_CHAIN:
+ 'The metadata endpoint TLS certificate chain contains an untrusted self-signed certificate.',
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE:
+ 'The metadata endpoint TLS certificate chain could not be verified.',
+ UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
+ 'The metadata endpoint TLS certificate issuer is not trusted locally.',
+};
+
+export const getMetadataDoctorFailure = (error: unknown): DoctorCheck => {
+ const code = error instanceof CliError ? error.code : 'INTERNAL_ERROR';
+ const description = FAILURE_MESSAGES[code] ?? {
+ message: `The metadata endpoint could not be verified (${code}).`,
+ hint: 'Check the API URL and server availability.',
+ };
+ const networkCode =
+ error instanceof CliError && code === 'NETWORK_ERROR'
+ ? error.details?.networkCode
+ : undefined;
+ const networkMessage =
+ isString(networkCode) &&
+ Object.hasOwn(NETWORK_FAILURE_MESSAGES, networkCode)
+ ? NETWORK_FAILURE_MESSAGES[networkCode]
+ : undefined;
+
+ return {
+ id: 'metadata-api',
+ status: 'fail',
+ code,
+ message: networkMessage ?? description.message,
+ hint:
+ error instanceof CliError &&
+ code === 'AUTH_REQUIRED' &&
+ isDefined(error.hint)
+ ? error.hint
+ : description.hint,
+ ...(isDefined(networkMessage) ? { details: { networkCode } } : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/doctor/get-path-doctor-check.ts b/packages/twenty-cli/src/doctor/get-path-doctor-check.ts
new file mode 100644
index 00000000000..1b5ee085b94
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/get-path-doctor-check.ts
@@ -0,0 +1,138 @@
+import { constants } from 'node:fs';
+import { access, realpath, stat } from 'node:fs/promises';
+import { delimiter, dirname, join, resolve } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
+
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+import { readJsonObject } from '@/app/read-json-object';
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+
+const readExecutableOwner = async (executable: string) => {
+ for (const directory of listAncestorDirectories(dirname(executable))) {
+ const manifest = await readJsonObject(join(directory, 'package.json'));
+
+ if (!isDefined(manifest)) {
+ continue;
+ }
+
+ const bin = manifest.bin;
+ const declaredBin =
+ isString(bin) && manifest.name === 'twenty' ? bin : undefined;
+ const namedBin =
+ isPlainObject(bin) && isString(bin.twenty) ? bin.twenty : declaredBin;
+
+ if (
+ isDefined(namedBin) &&
+ (await realpath(resolve(directory, namedBin)).catch(() => undefined)) ===
+ executable
+ ) {
+ return {
+ name: isString(manifest.name) ? manifest.name : 'unknown',
+ version: isString(manifest.version) ? manifest.version : 'unknown',
+ };
+ }
+ }
+
+ return null;
+};
+
+export const getPathDoctorCheck = async ({
+ environment,
+ workingDirectory,
+ signal,
+}: {
+ environment: NodeJS.ProcessEnv;
+ workingDirectory: string;
+ signal: AbortSignal;
+}): Promise<DoctorCheck> => {
+ const candidates: {
+ path: string;
+ resolvedPath: string;
+ owner: { name: string; version: string } | null;
+ }[] = [];
+ const names =
+ process.platform === 'win32'
+ ? ['twenty.exe', 'twenty.cmd', 'twenty.bat', 'twenty']
+ : ['twenty'];
+
+ const directories = isDefined(environment.PATH)
+ ? environment.PATH.split(delimiter)
+ : [];
+
+ for (const directory of new Set(directories)) {
+ for (const name of names) {
+ signal.throwIfAborted();
+
+ const candidate = resolve(workingDirectory, directory, name);
+ const isExecutable = await access(candidate, constants.X_OK).then(
+ () => stat(candidate).then((value) => value.isFile()),
+ () => false,
+ );
+
+ if (!isExecutable) {
+ continue;
+ }
+
+ const resolvedPath = await realpath(candidate);
+
+ candidates.push({
+ path: candidate,
+ resolvedPath,
+ owner: await readExecutableOwner(resolvedPath),
+ });
+ }
+ }
+
+ const first = candidates[0];
+ const runningEntry = process.argv[1];
+ const runningPath = isDefined(runningEntry)
+ ? await realpath(resolve(workingDirectory, runningEntry)).catch(
+ () => undefined,
+ )
+ : undefined;
+ const legacy = candidates.filter(
+ (entry) => entry.owner?.name === 'twenty-sdk',
+ );
+
+ if (isNonEmptyArray(legacy)) {
+ return {
+ id: 'path',
+ status: 'warning',
+ message: `PATH contains legacy twenty-sdk executable(s) named twenty: ${legacy.map((entry) => entry.path).join(', ')}.`,
+ hint: 'If this is a global twenty-sdk installation, remove it before installing the twenty CLI so the CLI owns the twenty name. Removing the SDK afterward can remove that executable link. Keep app-local SDK dependencies; use the intended CLI by its full path when needed. Doctor does not change installations.',
+ details: { candidates },
+ };
+ }
+
+ if (!isDefined(first)) {
+ return {
+ id: 'path',
+ status: 'warning',
+ message: 'No executable named twenty was found on PATH.',
+ hint: 'Use the CLI entry point shown above, or your package manager to invoke the installed CLI.',
+ details: { candidates },
+ };
+ }
+
+ if (isDefined(runningPath) && first.resolvedPath !== runningPath) {
+ return {
+ id: 'path',
+ status: 'warning',
+ message: `${first.path} is first on PATH and differs from the running CLI.`,
+ hint: 'Use the intended executable by its full path, or review PATH order. Shell aliases, functions and command caches are not inspected.',
+ details: { candidates, runningPath },
+ };
+ }
+
+ return {
+ id: 'path',
+ status: first.owner?.name === 'twenty' ? 'pass' : 'warning',
+ message: isDefined(first.owner)
+ ? `First twenty executable on PATH: ${first.path} (${first.owner.name} ${first.owner.version}).`
+ : `First twenty executable on PATH: ${first.path}. Its package owner could not be determined.`,
+ hint: 'Shell aliases, functions and command caches are not inspected.',
+ details: { candidates },
+ };
+};
diff --git a/packages/twenty-cli/src/doctor/get-project-doctor-checks.ts b/packages/twenty-cli/src/doctor/get-project-doctor-checks.ts
new file mode 100644
index 00000000000..e39f902fd45
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/get-project-doctor-checks.ts
@@ -0,0 +1,87 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { type AppProject } from '@/app/project/types/app-project.type';
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+import { CliError } from '@/output/cli-error';
+
+export const getProjectDoctorChecks = async ({
+ explicitPath,
+ workingDirectory,
+ signal,
+}: {
+ explicitPath: string | undefined;
+ workingDirectory: string;
+ signal: AbortSignal;
+}): Promise<DoctorCheck[]> => {
+ let project: AppProject;
+
+ signal.throwIfAborted();
+
+ try {
+ project = await resolveAppProject({ explicitPath, workingDirectory });
+ } catch (error) {
+ signal.throwIfAborted();
+
+ const isOptional =
+ !isDefined(explicitPath) &&
+ error instanceof CliError &&
+ (error.code === 'APP_NOT_FOUND' || error.code === 'APP_PATH_REQUIRED');
+
+ return [
+ {
+ id: 'project',
+ status: isOptional ? 'skipped' : 'fail',
+ message:
+ error instanceof CliError
+ ? error.message
+ : 'Could not inspect the app directory.',
+ hint: 'Use --path <app directory> to check a specific app.',
+ },
+ { id: 'sdk', status: 'skipped', message: 'No app was selected.' },
+ ];
+ }
+
+ const projectCheck: DoctorCheck = {
+ id: 'project',
+ status: 'pass',
+ message: `${project.name} at ${project.path}.`,
+ details: { name: project.name, path: project.path },
+ };
+
+ try {
+ signal.throwIfAborted();
+
+ const sdk = await resolveSourceSdk({ appPath: project.path });
+
+ return [
+ projectCheck,
+ {
+ id: 'sdk',
+ status: 'pass',
+ message: `twenty-sdk ${sdk.version} provides the authoring exports required by the CLI.`,
+ details: { version: sdk.version, path: sdk.packagePath },
+ },
+ ];
+ } catch (error) {
+ signal.throwIfAborted();
+
+ return [
+ projectCheck,
+ {
+ id: 'sdk',
+ status: 'fail',
+ code: error instanceof CliError ? error.code : 'INTERNAL_ERROR',
+ message:
+ error instanceof CliError
+ ? error.message
+ : 'Could not inspect the app SDK installation.',
+ hint:
+ error instanceof CliError
+ ? error.hint
+ : 'Check that the app dependencies are installed and readable.',
+ },
+ ];
+ }
+};
diff --git a/packages/twenty-cli/src/doctor/get-runtime-doctor-checks.ts b/packages/twenty-cli/src/doctor/get-runtime-doctor-checks.ts
new file mode 100644
index 00000000000..43a35766204
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/get-runtime-doctor-checks.ts
@@ -0,0 +1,37 @@
+import { engines } from '../../package.json';
+
+import { checkNodeRequirement } from '@/app/project/check-node-requirement';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+import { type DoctorCheck } from '@/doctor/types/doctor-check.type';
+
+export const getRuntimeDoctorChecks = (): DoctorCheck[] => {
+ const isSupported =
+ checkNodeRequirement({
+ version: process.versions.node,
+ range: engines.node,
+ }) === 'satisfied';
+
+ return [
+ {
+ id: 'node',
+ status: isSupported ? 'pass' : 'fail',
+ message: `Node ${process.versions.node}, required ${engines.node}.`,
+ ...(isSupported
+ ? {}
+ : { hint: 'Switch to a supported Node version and rerun doctor.' }),
+ details: { version: process.versions.node, required: engines.node },
+ },
+ {
+ id: 'cli',
+ status: 'pass',
+ message: `twenty ${CLI_VERSION}, entry point ${process.argv[1] ?? 'unknown'}.`,
+ details: {
+ version: CLI_VERSION,
+ nodeExecutable: process.execPath,
+ entryPoint: process.argv[1] ?? null,
+ platform: process.platform,
+ arch: process.arch,
+ },
+ },
+ ];
+};
diff --git a/packages/twenty-cli/src/doctor/types/doctor-check.type.ts b/packages/twenty-cli/src/doctor/types/doctor-check.type.ts
new file mode 100644
index 00000000000..9d07da23819
--- /dev/null
+++ b/packages/twenty-cli/src/doctor/types/doctor-check.type.ts
@@ -0,0 +1,8 @@
+export type DoctorCheck = {
+ id: string;
+ status: 'pass' | 'warning' | 'fail' | 'skipped';
+ message: string;
+ code?: string;
+ hint?: string;
+ details?: Record<string, unknown>;
+};
diff --git a/packages/twenty-cli/src/input/assert-single-standard-input-reader.ts b/packages/twenty-cli/src/input/assert-single-standard-input-reader.ts
new file mode 100644
index 00000000000..bc48d66ef89
--- /dev/null
+++ b/packages/twenty-cli/src/input/assert-single-standard-input-reader.ts
@@ -0,0 +1,20 @@
+import { INPUT_SOURCE_MARKER } from '@/input/constants/input-source-marker.constant';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const assertSingleStandardInputReader = (
+ optionValues: Record<string, string | undefined>,
+) => {
+ const standardInputOptions = Object.entries(optionValues)
+ .filter(([, value]) => value === INPUT_SOURCE_MARKER.STANDARD_INPUT)
+ .map(([optionName]) => optionName);
+
+ if (standardInputOptions.length > 1) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `Only one option can read standard input, but ${standardInputOptions.join(' and ')} both use -.`,
+ hint: 'Pass the other one inline or as @file.',
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/input/confirm-in-terminal.ts b/packages/twenty-cli/src/input/confirm-in-terminal.ts
new file mode 100644
index 00000000000..ef668952641
--- /dev/null
+++ b/packages/twenty-cli/src/input/confirm-in-terminal.ts
@@ -0,0 +1,24 @@
+import { createInterface } from 'node:readline/promises';
+
+const YES_ANSWER_PATTERN = /^y(es)?$/i;
+
+export const confirmInTerminal = async ({
+ question,
+ signal,
+}: {
+ question: string;
+ signal: AbortSignal;
+}) => {
+ const terminal = createInterface({
+ input: process.stdin,
+ output: process.stderr,
+ });
+
+ try {
+ const answer = await terminal.question(`${question} [y/N] `, { signal });
+
+ return YES_ANSWER_PATTERN.test(answer.trim());
+ } finally {
+ terminal.close();
+ }
+};
diff --git a/packages/twenty-cli/src/input/constants/input-byte-limit.constant.ts b/packages/twenty-cli/src/input/constants/input-byte-limit.constant.ts
new file mode 100644
index 00000000000..3a83a38bf7b
--- /dev/null
+++ b/packages/twenty-cli/src/input/constants/input-byte-limit.constant.ts
@@ -0,0 +1 @@
+export const INPUT_BYTE_LIMIT = 16 * 1024 * 1024;
diff --git a/packages/twenty-cli/src/input/constants/input-source-marker.constant.ts b/packages/twenty-cli/src/input/constants/input-source-marker.constant.ts
new file mode 100644
index 00000000000..8cc1316d014
--- /dev/null
+++ b/packages/twenty-cli/src/input/constants/input-source-marker.constant.ts
@@ -0,0 +1,4 @@
+export const INPUT_SOURCE_MARKER = {
+ STANDARD_INPUT: '-',
+ FILE_PREFIX: '@',
+} as const;
diff --git a/packages/twenty-cli/src/input/parse-json-input.ts b/packages/twenty-cli/src/input/parse-json-input.ts
new file mode 100644
index 00000000000..0174ea5effe
--- /dev/null
+++ b/packages/twenty-cli/src/input/parse-json-input.ts
@@ -0,0 +1,44 @@
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const createInvalidJsonError = (optionName: string, reason: string) =>
+ new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${optionName} is not valid JSON: ${reason}`,
+ });
+
+export const parseJsonInput = ({
+ text,
+ optionName,
+}: {
+ text: string;
+ optionName: string;
+}): unknown => {
+ try {
+ return JSON.parse(text);
+ } catch (error) {
+ throw createInvalidJsonError(
+ optionName,
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+};
+
+export const parseJsonObjectInput = ({
+ text,
+ optionName,
+}: {
+ text: string;
+ optionName: string;
+}) => {
+ const value = parseJsonInput({ text, optionName });
+
+ if (!isPlainObject(value)) {
+ throw createInvalidJsonError(optionName, 'expected a JSON object.');
+ }
+
+ return value;
+};
diff --git a/packages/twenty-cli/src/input/read-input-value.ts b/packages/twenty-cli/src/input/read-input-value.ts
new file mode 100644
index 00000000000..4eed8453981
--- /dev/null
+++ b/packages/twenty-cli/src/input/read-input-value.ts
@@ -0,0 +1,77 @@
+import { readFile } from 'node:fs/promises';
+import { addAbortSignal } from 'node:stream';
+
+import { INPUT_BYTE_LIMIT } from '@/input/constants/input-byte-limit.constant';
+import { INPUT_SOURCE_MARKER } from '@/input/constants/input-source-marker.constant';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+const readStandardInput = async (optionName: string, signal: AbortSignal) => {
+ const chunks: Buffer[] = [];
+ let receivedBytes = 0;
+
+ for await (const chunk of addAbortSignal(signal, process.stdin)) {
+ const buffer = Buffer.from(chunk);
+
+ receivedBytes += buffer.byteLength;
+
+ if (receivedBytes > INPUT_BYTE_LIMIT) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `Standard input for ${optionName} is larger than ${INPUT_BYTE_LIMIT / 1024 / 1024} MiB.`,
+ });
+ }
+
+ chunks.push(buffer);
+ }
+
+ return Buffer.concat(chunks).toString('utf8');
+};
+
+const readInputFile = async (
+ filePath: string,
+ optionName: string,
+ signal: AbortSignal,
+) => {
+ try {
+ return await readFile(filePath, { encoding: 'utf8', signal });
+ } catch (error) {
+ if (signal.aborted) {
+ throw error;
+ }
+
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `Could not read ${filePath} for ${optionName}.`,
+ details: {
+ reason: error instanceof Error ? error.message : String(error),
+ },
+ });
+ }
+};
+
+export const readInputValue = async ({
+ value,
+ optionName,
+ signal,
+}: {
+ value: string;
+ optionName: string;
+ signal: AbortSignal;
+}) => {
+ if (value === INPUT_SOURCE_MARKER.STANDARD_INPUT) {
+ return readStandardInput(optionName, signal);
+ }
+
+ if (value.startsWith(INPUT_SOURCE_MARKER.FILE_PREFIX)) {
+ return readInputFile(
+ value.slice(INPUT_SOURCE_MARKER.FILE_PREFIX.length),
+ optionName,
+ signal,
+ );
+ }
+
+ return value;
+};
diff --git a/packages/twenty-cli/src/metadata/__tests__/resolve-metadata-owner.spec.ts b/packages/twenty-cli/src/metadata/__tests__/resolve-metadata-owner.spec.ts
new file mode 100644
index 00000000000..0123434d2a4
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/__tests__/resolve-metadata-owner.spec.ts
@@ -0,0 +1,50 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { describe, expect, it } from 'vitest';
+
+import { createMetadataOwnerResolver } from '@/metadata/resolve-metadata-owner';
+
+const resolveOwner = createMetadataOwnerResolver({
+ applications: [
+ {
+ id: 'standard-id',
+ name: 'Twenty Standard',
+ universalIdentifier: TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ },
+ {
+ id: 'invoices-id',
+ name: 'Acme Invoices',
+ universalIdentifier: 'invoices-universal-identifier',
+ },
+ ],
+ workspaceCustomApplicationId: 'custom-id',
+});
+
+describe('createMetadataOwnerResolver', () => {
+ it('recognizes the standard application', () => {
+ expect(resolveOwner('standard-id')).toEqual({
+ kind: 'standard',
+ applicationId: 'standard-id',
+ name: null,
+ });
+ });
+
+ it('recognizes the workspace custom application even when it is not listed', () => {
+ expect(resolveOwner('custom-id').kind).toBe('custom');
+ });
+
+ it('names an installed app', () => {
+ expect(resolveOwner('invoices-id')).toEqual({
+ kind: 'application',
+ applicationId: 'invoices-id',
+ name: 'Acme Invoices',
+ });
+ });
+
+ it('keeps an owner it cannot see as unknown', () => {
+ expect(resolveOwner('hidden-id')).toEqual({
+ kind: 'unknown',
+ applicationId: 'hidden-id',
+ name: null,
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/metadata/collect-metadata-nodes.ts b/packages/twenty-cli/src/metadata/collect-metadata-nodes.ts
new file mode 100644
index 00000000000..a4558e46d0d
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/collect-metadata-nodes.ts
@@ -0,0 +1,63 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { CliError } from '@/output/cli-error';
+import { RESPONSE_BYTE_LIMIT } from '@/transport/constants/response-byte-limit.constant';
+import { RESULT_ITEM_LIMIT } from '@/transport/constants/result-item-limit.constant';
+
+type MetadataPage<TNode> = {
+ edges: { node: TNode }[];
+ pageInfo: { hasNextPage?: boolean; endCursor?: string };
+};
+
+export const collectMetadataNodes = async <TNode>(
+ fetchPage: (after?: string) => Promise<MetadataPage<TNode>>,
+) => {
+ const nodes: TNode[] = [];
+ const cursors = new Set<string>();
+ let after: string | undefined;
+ let bytes = 0;
+ let hasNextPage = true;
+
+ while (hasNextPage) {
+ const page = await fetchPage(after);
+
+ for (const { node } of page.edges) {
+ bytes += Buffer.byteLength(JSON.stringify(node), 'utf8');
+
+ if (nodes.length >= RESULT_ITEM_LIMIT || bytes > RESPONSE_BYTE_LIMIT) {
+ throw new CliError({
+ code: 'RESPONSE_LIMIT_EXCEEDED',
+ message:
+ 'Metadata exceeds the 10,000-item or 16 MiB inspection limit.',
+ hint: 'Use api graphql to select and page the metadata you need.',
+ });
+ }
+
+ nodes.push(node);
+ }
+
+ hasNextPage = page.pageInfo.hasNextPage !== false;
+
+ if (hasNextPage) {
+ const cursor = page.pageInfo.endCursor;
+
+ if (
+ page.pageInfo.hasNextPage !== true ||
+ !isNonEmptyString(cursor) ||
+ cursors.has(cursor) ||
+ page.edges.length === 0
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message:
+ 'The metadata server returned invalid pagination information.',
+ });
+ }
+
+ cursors.add(cursor);
+ after = cursor;
+ }
+ }
+
+ return nodes;
+};
diff --git a/packages/twenty-cli/src/metadata/constants/metadata-owner-kind-order.constant.ts b/packages/twenty-cli/src/metadata/constants/metadata-owner-kind-order.constant.ts
new file mode 100644
index 00000000000..76899cca45c
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/constants/metadata-owner-kind-order.constant.ts
@@ -0,0 +1,8 @@
+import { type MetadataOwnerKind } from '@/metadata/types/metadata-owner.type';
+
+export const METADATA_OWNER_KIND_ORDER: MetadataOwnerKind[] = [
+ 'standard',
+ 'application',
+ 'custom',
+ 'unknown',
+];
diff --git a/packages/twenty-cli/src/metadata/constants/metadata-page.constant.ts b/packages/twenty-cli/src/metadata/constants/metadata-page.constant.ts
new file mode 100644
index 00000000000..719a7c290d0
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/constants/metadata-page.constant.ts
@@ -0,0 +1 @@
+export const METADATA_PAGE_SIZE = 1000;
diff --git a/packages/twenty-cli/src/metadata/fetch-metadata-inspection.ts b/packages/twenty-cli/src/metadata/fetch-metadata-inspection.ts
new file mode 100644
index 00000000000..68ab17b927e
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/fetch-metadata-inspection.ts
@@ -0,0 +1,96 @@
+import { collectMetadataNodes } from '@/metadata/collect-metadata-nodes';
+import { METADATA_PAGE_SIZE } from '@/metadata/constants/metadata-page.constant';
+import { fetchOwnerApplications } from '@/metadata/fetch-owner-applications';
+import { createMetadataOwnerResolver } from '@/metadata/resolve-metadata-owner';
+import { resolveMetadataObject } from '@/metadata/resolve-metadata-object';
+import { type Output } from '@/output/types/output.type';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+const RELATION_SELECTION = {
+ type: true,
+ sourceObjectMetadata: { id: true, nameSingular: true, namePlural: true },
+ targetObjectMetadata: { id: true, nameSingular: true, namePlural: true },
+ sourceFieldMetadata: { id: true, name: true },
+ targetFieldMetadata: { id: true, name: true },
+} as const;
+
+export const fetchMetadataInspection = async ({
+ objectName,
+ target,
+ signal,
+ output,
+}: {
+ objectName: string;
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ output: Output;
+}) => {
+ const client = createMetadataClient({ target, signal });
+ const object = await resolveMetadataObject({ client, name: objectName });
+ const [fields, { currentWorkspace }, { applications, areOwnersNamed }] =
+ await Promise.all([
+ collectMetadataNodes(async (after) => {
+ const { fields } = await client.query({
+ fields: {
+ __args: {
+ paging: { first: METADATA_PAGE_SIZE, after },
+ filter: { objectMetadataId: { eq: object.id } },
+ },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ edges: {
+ node: {
+ id: true,
+ universalIdentifier: true,
+ objectMetadataId: true,
+ name: true,
+ label: true,
+ description: true,
+ type: true,
+ isActive: true,
+ isSystem: true,
+ isNullable: true,
+ isUnique: true,
+ defaultValue: true,
+ options: true,
+ settings: true,
+ applicationId: true,
+ relation: RELATION_SELECTION,
+ morphRelations: RELATION_SELECTION,
+ },
+ },
+ },
+ });
+
+ return fields;
+ }),
+ client.query({
+ currentWorkspace: { workspaceCustomApplicationId: true },
+ }),
+ fetchOwnerApplications(client),
+ ]);
+
+ if (!areOwnersNamed) {
+ output.warn({
+ code: 'OWNERS_UNAVAILABLE',
+ message:
+ 'Owners other than Custom show as unknown: listing apps needs the Applications permission.',
+ });
+ }
+
+ const resolveOwner = createMetadataOwnerResolver({
+ applications,
+ workspaceCustomApplicationId: currentWorkspace.workspaceCustomApplicationId,
+ });
+ const { applicationId, ...objectMetadata } = object;
+
+ return {
+ object: { ...objectMetadata, owner: resolveOwner(applicationId) },
+ fields: fields
+ .map(({ applicationId, ...field }) => ({
+ ...field,
+ owner: resolveOwner(applicationId),
+ }))
+ .sort((first, second) => first.name.localeCompare(second.name)),
+ };
+};
diff --git a/packages/twenty-cli/src/metadata/fetch-owner-applications.ts b/packages/twenty-cli/src/metadata/fetch-owner-applications.ts
new file mode 100644
index 00000000000..025dbf11531
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/fetch-owner-applications.ts
@@ -0,0 +1,20 @@
+import { CliError } from '@/output/cli-error';
+import { type createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchOwnerApplications = async (
+ client: ReturnType<typeof createMetadataClient>,
+) => {
+ try {
+ const { findManyApplications } = await client.query({
+ findManyApplications: { id: true, name: true, universalIdentifier: true },
+ });
+
+ return { applications: findManyApplications, areOwnersNamed: true };
+ } catch (error) {
+ if (!(error instanceof CliError) || error.code !== 'PERMISSION_DENIED') {
+ throw error;
+ }
+
+ return { applications: [], areOwnersNamed: false };
+ }
+};
diff --git a/packages/twenty-cli/src/metadata/format-metadata-fields.ts b/packages/twenty-cli/src/metadata/format-metadata-fields.ts
new file mode 100644
index 00000000000..80f761553db
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/format-metadata-fields.ts
@@ -0,0 +1,72 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { formatMetadataOwner } from '@/metadata/format-metadata-owner';
+import { getFieldOptions } from '@/metadata/get-field-options';
+import { type InspectedField } from '@/metadata/types/metadata-inspection.type';
+import { formatTable } from '@/output/format-table';
+import { dimText } from '@/output/style';
+
+export const formatMetadataRelations = (field: InspectedField) => {
+ const relations = isDefined(field.relation)
+ ? [field.relation]
+ : (field.morphRelations ?? []).filter(
+ (relation) => relation.sourceFieldMetadata.id === field.id,
+ );
+
+ return relations
+ .map(
+ (relation) =>
+ `${relation.type.toLowerCase().replaceAll('_', '-')} · ${relation.targetObjectMetadata.namePlural}.${relation.targetFieldMetadata.name}`,
+ )
+ .join(' · ');
+};
+
+const formatMetadataFieldDetails = (field: InspectedField) =>
+ [
+ field.isActive === false ? 'inactive' : '',
+ field.isNullable === false ? 'required' : '',
+ field.isUnique === true ? 'unique' : '',
+ formatMetadataRelations(field),
+ ...getFieldOptions(field).map((option) =>
+ String(option.label ?? option.value ?? ''),
+ ),
+ ]
+ .filter(isNonEmptyString)
+ .join(' · ');
+
+export const formatMetadataFields = ({
+ fields,
+ hiddenSystemFieldCount,
+ labelIdentifierFieldMetadataId,
+}: {
+ fields: InspectedField[];
+ hiddenSystemFieldCount: number;
+ labelIdentifierFieldMetadataId?: string;
+}) =>
+ [
+ formatTable({
+ rows: fields,
+ columns: [
+ { header: 'FIELD', value: (field) => field.name },
+ { header: 'LABEL', value: (field) => field.label },
+ { header: 'TYPE', value: (field) => field.type },
+ { header: 'OWNER', value: (field) => formatMetadataOwner(field.owner) },
+ {
+ header: 'DETAILS',
+ value: (field) =>
+ [
+ field.id === labelIdentifierFieldMetadataId ? 'label field' : '',
+ formatMetadataFieldDetails(field),
+ ]
+ .filter(isNonEmptyString)
+ .join(' · '),
+ },
+ ],
+ }),
+ dimText(
+ hiddenSystemFieldCount > 0
+ ? `${fields.length} fields · ${hiddenSystemFieldCount} system fields hidden, show them with --all`
+ : `${fields.length} fields`,
+ ),
+ ].join('\n');
diff --git a/packages/twenty-cli/src/metadata/format-metadata-owner.ts b/packages/twenty-cli/src/metadata/format-metadata-owner.ts
new file mode 100644
index 00000000000..ba8b32b357b
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/format-metadata-owner.ts
@@ -0,0 +1,15 @@
+import { type MetadataOwner } from '@/metadata/types/metadata-owner.type';
+import { colorText } from '@/output/style';
+
+export const formatMetadataOwner = (owner: MetadataOwner) => {
+ switch (owner.kind) {
+ case 'standard':
+ return 'Standard';
+ case 'custom':
+ return colorText('cyan', 'Custom');
+ case 'application':
+ return colorText('magenta', owner.name ?? 'Unknown app');
+ case 'unknown':
+ return colorText('yellow', 'Unknown');
+ }
+};
diff --git a/packages/twenty-cli/src/metadata/get-field-options.ts b/packages/twenty-cli/src/metadata/get-field-options.ts
new file mode 100644
index 00000000000..203e7b3556b
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/get-field-options.ts
@@ -0,0 +1,10 @@
+import { isArray } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type InspectedField } from '@/metadata/types/metadata-inspection.type';
+
+export const getFieldOptions = (field: InspectedField) => {
+ const options: unknown = field.options;
+
+ return isArray(options) ? options.filter(isPlainObject) : [];
+};
diff --git a/packages/twenty-cli/src/metadata/resolve-metadata-object.ts b/packages/twenty-cli/src/metadata/resolve-metadata-object.ts
new file mode 100644
index 00000000000..d9491897132
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/resolve-metadata-object.ts
@@ -0,0 +1,78 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { collectMetadataNodes } from '@/metadata/collect-metadata-nodes';
+import { METADATA_PAGE_SIZE } from '@/metadata/constants/metadata-page.constant';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { type createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const resolveMetadataObject = async ({
+ client,
+ name,
+}: {
+ client: ReturnType<typeof createMetadataClient>;
+ name: string;
+}) => {
+ const objects = await collectMetadataNodes(async (after) => {
+ const { objects } = await client.query({
+ objects: {
+ __args: { paging: { first: METADATA_PAGE_SIZE, after }, filter: {} },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ edges: {
+ node: {
+ id: true,
+ universalIdentifier: true,
+ nameSingular: true,
+ namePlural: true,
+ labelSingular: true,
+ labelPlural: true,
+ description: true,
+ isActive: true,
+ isSystem: true,
+ isSearchable: true,
+ labelIdentifierFieldMetadataId: true,
+ applicationId: true,
+ },
+ },
+ },
+ });
+
+ return objects;
+ });
+ const matches = objects.filter(
+ (object) => object.nameSingular === name || object.namePlural === name,
+ );
+
+ if (matches.length > 1) {
+ throw new CliError({
+ code: 'AMBIGUOUS_RESOURCE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `More than one object has the API name ${name}.`,
+ hint: 'Use an unambiguous singular or plural API name.',
+ details: {
+ matches: matches
+ .map(({ id, nameSingular, namePlural }) => ({
+ id,
+ nameSingular,
+ namePlural,
+ }))
+ .sort((first, second) =>
+ first.namePlural.localeCompare(second.namePlural),
+ ),
+ },
+ });
+ }
+
+ const object = matches[0];
+
+ if (!isDefined(object)) {
+ throw new CliError({
+ code: 'NOT_FOUND',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: `No object has the API name ${name}.`,
+ hint: 'Use an exact singular or plural API name from twenty metadata object list --all.',
+ });
+ }
+
+ return object;
+};
diff --git a/packages/twenty-cli/src/metadata/resolve-metadata-owner.ts b/packages/twenty-cli/src/metadata/resolve-metadata-owner.ts
new file mode 100644
index 00000000000..97f03136dbb
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/resolve-metadata-owner.ts
@@ -0,0 +1,43 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type MetadataOwner } from '@/metadata/types/metadata-owner.type';
+
+type OwnerApplication = {
+ id: string;
+ name: string;
+ universalIdentifier: string;
+};
+
+export const createMetadataOwnerResolver = ({
+ applications,
+ workspaceCustomApplicationId,
+}: {
+ applications: OwnerApplication[];
+ workspaceCustomApplicationId: string;
+}) => {
+ const applicationsById = new Map(
+ applications.map((application) => [application.id, application]),
+ );
+
+ return (applicationId: string): MetadataOwner => {
+ const application = applicationsById.get(applicationId);
+
+ if (applicationId === workspaceCustomApplicationId) {
+ return { kind: 'custom', applicationId, name: null };
+ }
+
+ if (!isDefined(application)) {
+ return { kind: 'unknown', applicationId, name: null };
+ }
+
+ if (
+ application.universalIdentifier ===
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER
+ ) {
+ return { kind: 'standard', applicationId, name: null };
+ }
+
+ return { kind: 'application', applicationId, name: application.name };
+ };
+};
diff --git a/packages/twenty-cli/src/metadata/select-listed-fields.ts b/packages/twenty-cli/src/metadata/select-listed-fields.ts
new file mode 100644
index 00000000000..b5a8d9b68f6
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/select-listed-fields.ts
@@ -0,0 +1,18 @@
+import { type InspectedField } from '@/metadata/types/metadata-inspection.type';
+
+export const selectListedFields = ({
+ fields,
+ includeSystemFields,
+}: {
+ fields: InspectedField[];
+ includeSystemFields: boolean;
+}) => {
+ const listedFields = fields.filter(
+ (field) => includeSystemFields || field.isSystem !== true,
+ );
+
+ return {
+ fields: listedFields,
+ hiddenSystemFieldCount: fields.length - listedFields.length,
+ };
+};
diff --git a/packages/twenty-cli/src/metadata/types/metadata-inspection.type.ts b/packages/twenty-cli/src/metadata/types/metadata-inspection.type.ts
new file mode 100644
index 00000000000..06e3d62f49f
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/types/metadata-inspection.type.ts
@@ -0,0 +1,6 @@
+import { type fetchMetadataInspection } from '@/metadata/fetch-metadata-inspection';
+
+export type MetadataInspection = Awaited<
+ ReturnType<typeof fetchMetadataInspection>
+>;
+export type InspectedField = MetadataInspection['fields'][number];
diff --git a/packages/twenty-cli/src/metadata/types/metadata-owner.type.ts b/packages/twenty-cli/src/metadata/types/metadata-owner.type.ts
new file mode 100644
index 00000000000..b4c598a5953
--- /dev/null
+++ b/packages/twenty-cli/src/metadata/types/metadata-owner.type.ts
@@ -0,0 +1,11 @@
+export type MetadataOwnerKind =
+ | 'standard'
+ | 'custom'
+ | 'application'
+ | 'unknown';
+
+export type MetadataOwner = {
+ kind: MetadataOwnerKind;
+ applicationId: string;
+ name: string | null;
+};
diff --git a/packages/twenty-cli/src/oauth/__tests__/browser-sign-in-and-refresh.spec.ts b/packages/twenty-cli/src/oauth/__tests__/browser-sign-in-and-refresh.spec.ts
new file mode 100644
index 00000000000..68b46b97147
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/__tests__/browser-sign-in-and-refresh.spec.ts
@@ -0,0 +1,574 @@
+import { createHash } from 'node:crypto';
+import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+
+import { isString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { openBrowser } from '@/oauth/open-browser';
+import { refreshOAuthSession } from '@/oauth/refresh-oauth-session';
+import { startCallbackServer } from '@/oauth/start-callback-server';
+
+vi.mock('@/oauth/open-browser', () => ({ openBrowser: vi.fn() }));
+
+const CLIENT_ID = 'cli-client';
+
+type Scenario = {
+ refreshDelayMilliseconds?: number;
+ isDeclined?: boolean;
+ returnedState?: string;
+ returnedIssuer?: string | null;
+ advertisedIssuer?: string;
+ tokenEndpointOrigin?: string;
+ tokenEndpointPath?: string;
+};
+
+type ServerState = {
+ scenario: Scenario;
+ codeChallenge: string;
+ isVerifierValid: boolean;
+ codeExchanges: number;
+ currentRefreshToken: string;
+ refreshCalls: number;
+ validAccessTokens: Set<string>;
+};
+
+type RefusalCase = {
+ args?: string[];
+ continuousIntegration?: string;
+ isTerminal?: boolean;
+};
+
+const encode = (value: unknown) =>
+ Buffer.from(JSON.stringify(value)).toString('base64url');
+
+const createAccessToken = (expiresInSeconds: number, id: string) =>
+ [
+ encode({ alg: 'none' }),
+ encode({ sub: id, exp: Math.floor(Date.now() / 1000) + expiresInSeconds }),
+ 'signature',
+ ].join('.');
+
+const state: ServerState = {
+ scenario: {},
+ codeChallenge: '',
+ isVerifierValid: false,
+ codeExchanges: 0,
+ currentRefreshToken: 'refresh-1',
+ refreshCalls: 0,
+ validAccessTokens: new Set<string>(),
+};
+
+const server = await startTestServer((request, response) => {
+ const url = new URL(request.path, 'http://fake');
+
+ if (url.pathname === '/.well-known/oauth-authorization-server') {
+ return sendJson(response, 200, {
+ issuer: state.scenario.advertisedIssuer ?? server.url,
+ authorization_endpoint: `${server.url}/authorize`,
+ token_endpoint: `${state.scenario.tokenEndpointOrigin ?? server.url}${state.scenario.tokenEndpointPath ?? '/oauth/token'}`,
+ cli_client_id: CLIENT_ID,
+ code_challenge_methods_supported: ['S256'],
+ authorization_response_iss_parameter_supported: true,
+ });
+ }
+
+ if (url.pathname === '/authorize') {
+ const callback = new URL(url.searchParams.get('redirect_uri') ?? '');
+ const {
+ isDeclined,
+ returnedState,
+ returnedIssuer = server.url,
+ } = state.scenario;
+
+ state.codeChallenge = url.searchParams.get('code_challenge') ?? '';
+
+ if (isDeclined === true) {
+ callback.searchParams.set('error', 'access_denied');
+ } else {
+ callback.searchParams.set('code', 'authorization-code');
+ }
+
+ callback.searchParams.set(
+ 'state',
+ returnedState ?? url.searchParams.get('state') ?? '',
+ );
+
+ if (isDefined(returnedIssuer)) {
+ callback.searchParams.set('iss', returnedIssuer);
+ }
+
+ response.writeHead(302, { location: callback.href });
+
+ return response.end();
+ }
+
+ if (url.pathname === (state.scenario.tokenEndpointPath ?? '/oauth/token')) {
+ const parameters: unknown = JSON.parse(request.body);
+
+ if (!isPlainObject(parameters)) {
+ return sendJson(response, 400, { error: 'invalid_request' });
+ }
+
+ if (parameters.grant_type === 'authorization_code') {
+ state.codeExchanges += 1;
+ state.isVerifierValid =
+ isString(parameters.code_verifier) &&
+ createHash('sha256')
+ .update(parameters.code_verifier)
+ .digest('base64url') === state.codeChallenge;
+
+ if (!state.isVerifierValid || parameters.client_id !== CLIENT_ID) {
+ return sendJson(response, 400, { error: 'invalid_grant' });
+ }
+ } else {
+ state.refreshCalls += 1;
+
+ if (parameters.refresh_token !== state.currentRefreshToken) {
+ return sendJson(response, 400, {
+ error: 'invalid_grant',
+ error_description: 'The refresh token is invalid.',
+ });
+ }
+ }
+
+ const accessToken = createAccessToken(3600, `access-${Math.random()}`);
+
+ state.currentRefreshToken = `refresh-${state.refreshCalls + 2}`;
+ state.validAccessTokens.add(accessToken);
+
+ const sendTokens = () =>
+ sendJson(response, 200, {
+ access_token: accessToken,
+ refresh_token: state.currentRefreshToken,
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+
+ if (parameters.grant_type === 'refresh_token') {
+ setTimeout(sendTokens, state.scenario.refreshDelayMilliseconds ?? 0);
+ return;
+ }
+
+ return sendTokens();
+ }
+
+ const bearerToken = request.headers.authorization?.replace('Bearer ', '');
+
+ if (!state.validAccessTokens.has(bearerToken ?? '')) {
+ return sendJson(response, 200, {
+ errors: [
+ { message: 'Token invalid.', extensions: { code: 'UNAUTHENTICATED' } },
+ ],
+ data: null,
+ });
+ }
+
+ return sendJson(response, 200, {
+ data: {
+ currentWorkspace: { displayName: 'Cloud' },
+ currentUser: { email: '[email protected]' },
+ },
+ });
+});
+
+const runJson = async (args: string[]) => {
+ const { stdout, exitCode } = await runCliForTest([...args, '--json']);
+
+ return { envelope: parseSingleJsonLine(stdout), exitCode };
+};
+
+const signIn = (args: string[] = []) =>
+ runCliForTest([
+ 'auth',
+ 'login',
+ '--url',
+ server.url,
+ '--name',
+ 'cloud',
+ ...args,
+ ]);
+
+const stubStandardInput = ({ isTerminal }: { isTerminal: boolean }) =>
+ vi
+ .spyOn(process, 'stdin', 'get')
+ .mockReturnValue(createStandardInputStub({ isTerminal }));
+
+const countListeningServers = () =>
+ process
+ .getActiveResourcesInfo()
+ .filter((resource) => resource === 'TCPServerWrap').length;
+
+describe('browser sign-in and session refresh', () => {
+ let configPath: string;
+
+ const readConfigFile = async (): Promise<ConfigFile> =>
+ JSON.parse(await readFile(configPath, 'utf8'));
+
+ const expectNothingSaved = () =>
+ expect(readFile(configPath, 'utf8')).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+
+ const writeSession = async (accessToken: string, refreshToken: string) => {
+ await mkdir(dirname(configPath), { recursive: true });
+ await writeFile(
+ configPath,
+ JSON.stringify({
+ version: 1,
+ defaultRemote: 'cloud',
+ remotes: {
+ cloud: {
+ apiUrl: server.url,
+ twentyCLIAccessToken: accessToken,
+ twentyCLIRefreshToken: refreshToken,
+ twentyCLIRegistrationClientId: CLIENT_ID,
+ },
+ },
+ }),
+ );
+ };
+
+ beforeEach(async () => {
+ const home = await mkdtemp(join(tmpdir(), 'twenty-cli-oauth-'));
+
+ configPath = join(home, '.twenty', 'config.json');
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('CI', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ stubStandardInput({ isTerminal: true });
+ Object.assign(state, {
+ scenario: {},
+ codeChallenge: '',
+ isVerifierValid: false,
+ codeExchanges: 0,
+ currentRefreshToken: 'refresh-1',
+ refreshCalls: 0,
+ });
+ vi.mocked(openBrowser).mockImplementation((url) => {
+ fetch(url).catch(() => undefined);
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ vi.mocked(openBrowser).mockReset();
+ });
+
+ afterAll(async () => {
+ await server.close();
+ });
+
+ it('signs in with the browser using PKCE and saves the session', async () => {
+ const { stdout, stderr, exitCode } = await signIn();
+
+ expect(exitCode).toBe(0);
+ expect(state.isVerifierValid).toBe(true);
+ expect(stderr).toContain(
+ `If nothing opens, visit: ${server.url}/authorize?`,
+ );
+ expect(stdout).toContain('[email protected]');
+
+ const { remotes } = await readConfigFile();
+
+ expect(remotes.cloud).toMatchObject({
+ apiUrl: server.url,
+ twentyCLIRefreshToken: 'refresh-2',
+ twentyCLIRegistrationClientId: CLIENT_ID,
+ workspaceName: 'Cloud',
+ });
+ expect(remotes.cloud).not.toHaveProperty('apiKey');
+ });
+
+ it.each<[string, Scenario, string]>([
+ ['declines', { isDeclined: true }, 'Sign-in was declined in the browser.'],
+ [
+ 'answers another login attempt',
+ { returnedState: 'forged' },
+ 'The sign-in response does not match this login attempt.',
+ ],
+ [
+ 'answers for another server',
+ { returnedIssuer: 'https://elsewhere.example.com' },
+ `The sign-in response came from https://elsewhere.example.com instead of ${server.url}.`,
+ ],
+ [
+ 'answers without the issuer the server promised',
+ { returnedIssuer: null },
+ 'The sign-in response does not say which server sent it.',
+ ],
+ [
+ 'declines without the issuer the server promised',
+ { isDeclined: true, returnedIssuer: null },
+ 'The sign-in response does not say which server sent it.',
+ ],
+ [
+ 'declines another login attempt',
+ { isDeclined: true, returnedState: 'forged' },
+ 'The sign-in response does not match this login attempt.',
+ ],
+ ])('saves nothing when the browser %s', async (_, scenario, message) => {
+ state.scenario = scenario;
+
+ const { stderr, exitCode } = await signIn();
+
+ expect(exitCode).toBe(1);
+ expect(stderr).toContain(message);
+ expect(state.codeExchanges).toBe(0);
+ await expectNothingSaved();
+ });
+
+ it.each<[string, Scenario, string]>([
+ [
+ 'its token endpoint is on another server',
+ { tokenEndpointOrigin: 'https://elsewhere.example.com' },
+ 'its token endpoint https://elsewhere.example.com is on another server.',
+ ],
+ [
+ 'it identifies itself as another server',
+ { advertisedIssuer: 'https://foreign.example.com' },
+ 'it identifies itself as https://foreign.example.com.',
+ ],
+ ])('does not open the browser when %s', async (_, scenario, message) => {
+ state.scenario = scenario;
+
+ const { stderr, exitCode } = await signIn();
+
+ expect(exitCode).toBe(1);
+ expect(stderr).toContain(message);
+ expect(openBrowser).not.toHaveBeenCalled();
+ });
+
+ it.each<[string, RefusalCase]>([
+ ['with --no-input', { args: ['--no-input'] }],
+ ['with --json', { args: ['--json'] }],
+ ['in CI', { continuousIntegration: 'true' }],
+ ['when stdin is not a terminal', { isTerminal: false }],
+ ])(
+ 'refuses browser sign-in %s',
+ async (_, { args = [], continuousIntegration = '', isTerminal = true }) => {
+ vi.stubEnv('CI', continuousIntegration);
+ stubStandardInput({ isTerminal });
+
+ const { stdout, stderr, exitCode } = await signIn(args);
+
+ expect(exitCode).toBe(2);
+ expect(`${stdout}${stderr}`).toContain(
+ 'Browser sign-in only runs in an interactive terminal',
+ );
+ expect(openBrowser).not.toHaveBeenCalled();
+ },
+ );
+
+ it('stops waiting for the browser on Ctrl+C and closes the callback server', async () => {
+ let authorizationUrl = '';
+
+ vi.mocked(openBrowser).mockImplementation((url) => {
+ authorizationUrl = url;
+ setImmediate(() => process.emit('SIGINT'));
+ });
+
+ const { stderr, exitCode } = await signIn();
+ const redirectUri = new URL(authorizationUrl).searchParams.get(
+ 'redirect_uri',
+ );
+
+ expect(exitCode).toBe(130);
+ expect(stderr).toContain('Cancelled.');
+ await expect(fetch(redirectUri ?? '')).rejects.toThrow();
+ await expectNothingSaved();
+ });
+
+ it('does not leave a callback server listening when already cancelled', async () => {
+ const listeningServersBefore = countListeningServers();
+
+ await expect(
+ startCallbackServer({
+ state: 'state',
+ issuer: server.url,
+ isIssuerInResponse: true,
+ signal: AbortSignal.abort(),
+ }),
+ ).rejects.toMatchObject({ name: 'AbortError' });
+ await vi.waitFor(() =>
+ expect(countListeningServers()).toBe(listeningServersBefore),
+ );
+ });
+
+ it.each(['/oauth/token', '/custom/token'])(
+ 'refreshes an expiring session at the advertised %s endpoint and keeps the rotated tokens',
+ async (tokenEndpointPath) => {
+ state.scenario = { tokenEndpointPath };
+ await writeSession(createAccessToken(10, 'expiring'), 'refresh-1');
+
+ const { envelope, exitCode } = await runJson(['auth', 'status']);
+ const { remotes } = await readConfigFile();
+
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ credentials: 'oauth',
+ email: '[email protected]',
+ });
+ expect(state.refreshCalls).toBe(1);
+ expect(remotes.cloud.twentyCLIRefreshToken).toBe('refresh-3');
+ expect(
+ state.validAccessTokens.has(remotes.cloud.twentyCLIAccessToken ?? ''),
+ ).toBe(true);
+ },
+ );
+
+ it('rejects a foreign refresh endpoint without sending or changing credentials', async () => {
+ state.scenario = { tokenEndpointOrigin: 'https://elsewhere.example.com' };
+ await writeSession(createAccessToken(10, 'expiring'), 'refresh-1');
+
+ const configBefore = await readConfigFile();
+ const { envelope, exitCode } = await runJson(['auth', 'status']);
+
+ expect(exitCode).toBe(1);
+ expect(envelope.error).toMatchObject({ code: 'OAUTH_UNAVAILABLE' });
+ expect(state.refreshCalls).toBe(0);
+ expect(await readConfigFile()).toEqual(configBefore);
+ expect(openBrowser).not.toHaveBeenCalled();
+ });
+
+ it('asks to sign in again when the refresh is rejected, without a browser', async () => {
+ const expiredAccessToken = createAccessToken(-10, 'expired');
+
+ await writeSession(expiredAccessToken, 'revoked-refresh-token');
+
+ const { envelope, exitCode } = await runJson(['auth', 'status']);
+
+ expect(exitCode).toBe(3);
+ expect(envelope.error).toMatchObject({
+ code: 'AUTH_REQUIRED',
+ hint: 'Sign in again: twenty auth login --remote cloud',
+ });
+ expect(openBrowser).not.toHaveBeenCalled();
+ expect((await readConfigFile()).remotes.cloud.twentyCLIAccessToken).toBe(
+ expiredAccessToken,
+ );
+ });
+
+ it.each([0, 5_200])(
+ 'shares a refresh delayed by %s ms between concurrent commands',
+ async (delay) => {
+ state.scenario.refreshDelayMilliseconds = delay;
+ await writeSession(createAccessToken(10, 'expiring'), 'refresh-1');
+
+ const refresh = () =>
+ refreshOAuthSession({
+ configPath,
+ remoteName: 'cloud',
+ apiUrl: server.url,
+ signal: new AbortController().signal,
+ });
+ const [firstAccessToken, secondAccessToken] = await Promise.all([
+ refresh(),
+ refresh(),
+ ]);
+
+ expect(state.refreshCalls).toBe(1);
+ expect(firstAccessToken).toBe(secondAccessToken);
+ },
+ 15_000,
+ );
+
+ describe('when the remote changes while a refresh waits for the lock', () => {
+ const otherServerUrl = () => server.url.replace('127.0.0.1', 'localhost');
+
+ const writeRemote = async (remote: Record<string, unknown>) => {
+ await mkdir(dirname(configPath), { recursive: true });
+ await writeFile(
+ configPath,
+ JSON.stringify({ version: 1, remotes: { cloud: remote } }),
+ );
+ };
+
+ const refreshSelectedServer = () =>
+ refreshOAuthSession({
+ configPath,
+ remoteName: 'cloud',
+ apiUrl: server.url,
+ signal: new AbortController().signal,
+ });
+
+ it.each([
+ [
+ 'pointed at another server',
+ () => ({
+ apiUrl: otherServerUrl(),
+ twentyCLIAccessToken: createAccessToken(10, 'other-server'),
+ twentyCLIRefreshToken: 'refresh-1',
+ twentyCLIRegistrationClientId: CLIENT_ID,
+ }),
+ ],
+ [
+ 'switched to an API key',
+ () => ({ apiUrl: server.url, apiKey: 'api-key' }),
+ ],
+ ])(
+ 'refuses when the remote was %s, and sends nothing',
+ async (_, remote) => {
+ await writeRemote(remote());
+
+ await expect(refreshSelectedServer()).rejects.toMatchObject({
+ code: 'CONFLICT',
+ exitCode: 6,
+ });
+ expect(state.refreshCalls).toBe(0);
+ },
+ );
+
+ it('refuses when the remote was removed', async () => {
+ await mkdir(dirname(configPath), { recursive: true });
+ await writeFile(configPath, JSON.stringify({ version: 1, remotes: {} }));
+
+ await expect(refreshSelectedServer()).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ });
+
+ it('asks to sign in again when the remote was signed out', async () => {
+ await writeRemote({ apiUrl: server.url });
+
+ await expect(refreshSelectedServer()).rejects.toMatchObject({
+ code: 'AUTH_REQUIRED',
+ message: 'Remote cloud was signed out while this command was waiting.',
+ });
+ });
+
+ it('uses a session signed in again on the same server', async () => {
+ const freshAccessToken = createAccessToken(3600, 'signed-in-again');
+
+ await writeRemote({
+ apiUrl: server.url,
+ twentyCLIAccessToken: freshAccessToken,
+ twentyCLIRefreshToken: 'refresh-1',
+ twentyCLIRegistrationClientId: CLIENT_ID,
+ });
+
+ await expect(refreshSelectedServer()).resolves.toBe(freshAccessToken);
+ expect(state.refreshCalls).toBe(0);
+ });
+ });
+});
diff --git a/packages/twenty-cli/src/oauth/constants/oauth-timing.constant.ts b/packages/twenty-cli/src/oauth/constants/oauth-timing.constant.ts
new file mode 100644
index 00000000000..190312ed8ec
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/constants/oauth-timing.constant.ts
@@ -0,0 +1,4 @@
+export const OAUTH_TIMING = {
+ SIGN_IN_TIMEOUT_MILLISECONDS: 5 * 60_000,
+ REFRESH_MARGIN_MILLISECONDS: 60_000,
+} as const;
diff --git a/packages/twenty-cli/src/oauth/create-pkce-pair.ts b/packages/twenty-cli/src/oauth/create-pkce-pair.ts
new file mode 100644
index 00000000000..876bd376393
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/create-pkce-pair.ts
@@ -0,0 +1,12 @@
+import { createHash, randomBytes } from 'node:crypto';
+
+export const createPkcePair = () => {
+ const codeVerifier = randomBytes(32).toString('base64url');
+
+ return {
+ codeVerifier,
+ codeChallenge: createHash('sha256')
+ .update(codeVerifier)
+ .digest('base64url'),
+ };
+};
diff --git a/packages/twenty-cli/src/oauth/discover-oauth-server.ts b/packages/twenty-cli/src/oauth/discover-oauth-server.ts
new file mode 100644
index 00000000000..20101d8a1a1
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/discover-oauth-server.ts
@@ -0,0 +1,94 @@
+import { isArray, isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { type OAuthServer } from '@/oauth/types/oauth-server.type';
+import { CliError } from '@/output/cli-error';
+import { API_URL_PROTOCOLS } from '@/target/constants/api-url-protocols.constant';
+import { formatApiUrl } from '@/target/format-api-url';
+import { assertUrlWithinTarget } from '@/transport/assert-url-within-target';
+import { createBoundedFetch } from '@/transport/create-target-fetch';
+import { parseResponseBody } from '@/transport/parse-response-body';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+const DISCOVERY_PATH = '/.well-known/oauth-authorization-server';
+
+const createUnavailableError = (apiUrl: string, reason: string) =>
+ new CliError({
+ code: 'OAUTH_UNAVAILABLE',
+ message: `Browser sign-in is not available on ${apiUrl}: ${reason}`,
+ hint: `Use an API key instead: printf '%s' "$TWENTY_API_KEY" | twenty auth login --with-token --url ${apiUrl} --name <name>`,
+ });
+
+const parseHttpUrl = (value: unknown) => {
+ const url = isNonEmptyString(value) ? URL.parse(value) : null;
+
+ return isDefined(url) && API_URL_PROTOCOLS.includes(url.protocol)
+ ? url
+ : undefined;
+};
+
+export const discoverOAuthServer = async ({
+ apiUrl,
+ signal,
+}: {
+ apiUrl: string;
+ signal: AbortSignal;
+}): Promise<OAuthServer> => {
+ const response = await createBoundedFetch({ apiUrl, signal })(
+ resolveRequestUrl({ apiUrl, path: DISCOVERY_PATH }),
+ { headers: { Accept: 'application/json' } },
+ );
+ const metadata = await parseResponseBody(response);
+
+ if (!response.ok || !isPlainObject(metadata)) {
+ throw createUnavailableError(
+ apiUrl,
+ `the server answered ${response.status}.`,
+ );
+ }
+
+ const authorizationEndpoint = parseHttpUrl(metadata.authorization_endpoint);
+ const tokenEndpoint = parseHttpUrl(metadata.token_endpoint);
+ const challengeMethods = metadata.code_challenge_methods_supported;
+
+ if (
+ !isNonEmptyString(metadata.issuer) ||
+ !isNonEmptyString(metadata.cli_client_id) ||
+ !isDefined(authorizationEndpoint) ||
+ !isDefined(tokenEndpoint) ||
+ (isArray(challengeMethods) && !challengeMethods.includes('S256'))
+ ) {
+ throw createUnavailableError(apiUrl, 'its OAuth metadata is incomplete.');
+ }
+
+ const issuer = URL.parse(metadata.issuer);
+
+ if (!isDefined(issuer) || formatApiUrl(issuer) !== apiUrl) {
+ throw createUnavailableError(
+ apiUrl,
+ `it identifies itself as ${metadata.issuer}.`,
+ );
+ }
+
+ try {
+ assertUrlWithinTarget({
+ url: tokenEndpoint,
+ apiUrl,
+ requestedPath: tokenEndpoint.href,
+ });
+ } catch {
+ throw createUnavailableError(
+ apiUrl,
+ `its token endpoint ${tokenEndpoint.origin} is on another server.`,
+ );
+ }
+
+ return {
+ issuer: metadata.issuer,
+ isIssuerInResponse:
+ metadata.authorization_response_iss_parameter_supported === true,
+ authorizationEndpoint: authorizationEndpoint.href,
+ tokenEndpoint: tokenEndpoint.href,
+ clientId: metadata.cli_client_id,
+ };
+};
diff --git a/packages/twenty-cli/src/oauth/is-access-token-expiring.ts b/packages/twenty-cli/src/oauth/is-access-token-expiring.ts
new file mode 100644
index 00000000000..9f786f5bbb8
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/is-access-token-expiring.ts
@@ -0,0 +1,27 @@
+import { isNumber } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { OAUTH_TIMING } from '@/oauth/constants/oauth-timing.constant';
+
+export const getAccessTokenExpiry = (accessToken: string) => {
+ try {
+ const payload: unknown = JSON.parse(
+ Buffer.from(accessToken.split('.')[1] ?? '', 'base64url').toString(),
+ );
+
+ return isPlainObject(payload) && isNumber(payload.exp)
+ ? payload.exp * 1000
+ : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const isAccessTokenExpiring = (accessToken: string) => {
+ const expiry = getAccessTokenExpiry(accessToken);
+
+ return (
+ isDefined(expiry) &&
+ expiry - OAUTH_TIMING.REFRESH_MARGIN_MILLISECONDS < Date.now()
+ );
+};
diff --git a/packages/twenty-cli/src/oauth/open-browser.ts b/packages/twenty-cli/src/oauth/open-browser.ts
new file mode 100644
index 00000000000..8ede52dad06
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/open-browser.ts
@@ -0,0 +1,25 @@
+import { spawn } from 'node:child_process';
+
+const getOpenCommand = (url: string): [string, string[]] => {
+ if (process.platform === 'darwin') {
+ return ['open', [url]];
+ }
+
+ if (process.platform === 'win32') {
+ return ['rundll32', ['url.dll,FileProtocolHandler', url]];
+ }
+
+ return ['xdg-open', [url]];
+};
+
+export const openBrowser = (url: string) => {
+ const [command, args] = getOpenCommand(url);
+ const browserProcess = spawn(command, args, {
+ detached: true,
+ stdio: 'ignore',
+ windowsHide: true,
+ });
+
+ browserProcess.on('error', () => undefined);
+ browserProcess.unref();
+};
diff --git a/packages/twenty-cli/src/oauth/refresh-oauth-session.ts b/packages/twenty-cli/src/oauth/refresh-oauth-session.ts
new file mode 100644
index 00000000000..c35471999a0
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/refresh-oauth-session.ts
@@ -0,0 +1,142 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { getCredentialKind } from '@/config/get-credential-kind';
+import { readConfig } from '@/config/read-config';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { withConfigLock } from '@/config/with-config-lock';
+import { writeConfigAtomically } from '@/config/write-config-atomically';
+import { discoverOAuthServer } from '@/oauth/discover-oauth-server';
+import { isAccessTokenExpiring } from '@/oauth/is-access-token-expiring';
+import { requestOAuthTokens } from '@/oauth/request-oauth-tokens';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { parseApiUrl } from '@/target/parse-api-url';
+
+const createSessionExpiredError = (remoteName: string, details?: unknown) =>
+ new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `Your session on ${remoteName} expired and could not be refreshed.`,
+ hint: `Sign in again: twenty auth login --remote ${remoteName}`,
+ details: { remote: remoteName, refresh: details ?? null },
+ });
+
+const createChangedRemoteError = (remoteName: string, change: string) =>
+ new CliError({
+ code: 'CONFLICT',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `Remote ${remoteName} ${change} while this command was waiting to refresh its session. Nothing was sent.`,
+ hint: 'Run the command again.',
+ details: { remote: remoteName },
+ });
+
+const readUnchangedRemote = ({
+ config,
+ remoteName,
+ apiUrl,
+}: {
+ config: ConfigFile;
+ remoteName: string;
+ apiUrl: string;
+}) => {
+ if (!Object.hasOwn(config.remotes, remoteName)) {
+ throw createChangedRemoteError(remoteName, 'was renamed or removed');
+ }
+
+ const remote = config.remotes[remoteName];
+
+ if (
+ parseApiUrl({ rawUrl: remote.apiUrl, sourceName: remoteName }) !== apiUrl
+ ) {
+ throw createChangedRemoteError(remoteName, 'was pointed at another server');
+ }
+
+ const credentialKind = getCredentialKind(remote);
+
+ if (credentialKind === 'apiKey') {
+ throw createChangedRemoteError(remoteName, 'switched to an API key');
+ }
+
+ if (credentialKind === 'none') {
+ throw new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `Remote ${remoteName} was signed out while this command was waiting.`,
+ hint: `Sign in again: twenty auth login --remote ${remoteName}`,
+ details: { remote: remoteName },
+ });
+ }
+
+ return remote;
+};
+
+export const refreshOAuthSession = ({
+ configPath,
+ remoteName,
+ apiUrl,
+ signal,
+}: {
+ configPath: string;
+ remoteName: string;
+ apiUrl: string;
+ signal: AbortSignal;
+}) =>
+ withConfigLock({
+ configPath,
+ signal,
+ operation: async () => {
+ const config = await readConfig(configPath);
+ const remote = readUnchangedRemote({ config, remoteName, apiUrl });
+ const {
+ twentyCLIAccessToken: accessToken,
+ twentyCLIRefreshToken: refreshToken,
+ twentyCLIRegistrationClientId: clientId,
+ } = remote;
+
+ if (
+ isNonEmptyString(accessToken) &&
+ !isAccessTokenExpiring(accessToken)
+ ) {
+ return accessToken;
+ }
+
+ if (!isNonEmptyString(refreshToken) || !isNonEmptyString(clientId)) {
+ throw createSessionExpiredError(remoteName);
+ }
+
+ const { tokenEndpoint } = await discoverOAuthServer({ apiUrl, signal });
+ const tokens = await requestOAuthTokens({
+ apiUrl,
+ tokenEndpoint,
+ parameters: {
+ grant_type: 'refresh_token',
+ refresh_token: refreshToken,
+ client_id: clientId,
+ },
+ signal,
+ }).catch((error: unknown) => {
+ if (error instanceof CliError && error.code === 'OAUTH_FAILED') {
+ throw createSessionExpiredError(remoteName, error.details);
+ }
+
+ throw error;
+ });
+
+ signal.throwIfAborted();
+ await writeConfigAtomically(configPath, {
+ ...config,
+ remotes: {
+ ...config.remotes,
+ [remoteName]: {
+ ...remote,
+ twentyCLIAccessToken: tokens.accessToken,
+ ...(isNonEmptyString(tokens.refreshToken)
+ ? { twentyCLIRefreshToken: tokens.refreshToken }
+ : {}),
+ },
+ },
+ });
+
+ return tokens.accessToken;
+ },
+ });
diff --git a/packages/twenty-cli/src/oauth/request-oauth-tokens.ts b/packages/twenty-cli/src/oauth/request-oauth-tokens.ts
new file mode 100644
index 00000000000..b8091e38481
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/request-oauth-tokens.ts
@@ -0,0 +1,50 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type OAuthTokens } from '@/oauth/types/oauth-tokens.type';
+import { CliError } from '@/output/cli-error';
+import { createBoundedFetch } from '@/transport/create-target-fetch';
+import { parseResponseBody } from '@/transport/parse-response-body';
+
+export const requestOAuthTokens = async ({
+ apiUrl,
+ tokenEndpoint,
+ parameters,
+ signal,
+}: {
+ apiUrl: string;
+ tokenEndpoint: string;
+ parameters: Record<string, string>;
+ signal: AbortSignal;
+}): Promise<OAuthTokens> => {
+ const response = await createBoundedFetch({ apiUrl, signal })(tokenEndpoint, {
+ method: 'POST',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(parameters),
+ });
+ const body = await parseResponseBody(response);
+ const tokens = isPlainObject(body) ? body : {};
+
+ if (!response.ok || !isNonEmptyString(tokens.access_token)) {
+ throw new CliError({
+ code: 'OAUTH_FAILED',
+ message: isNonEmptyString(tokens.error_description)
+ ? tokens.error_description
+ : `The token endpoint answered ${response.status}.`,
+ details: {
+ status: response.status,
+ error: isNonEmptyString(tokens.error) ? tokens.error : null,
+ },
+ });
+ }
+
+ return {
+ accessToken: tokens.access_token,
+ ...(isNonEmptyString(tokens.refresh_token)
+ ? { refreshToken: tokens.refresh_token }
+ : {}),
+ };
+};
diff --git a/packages/twenty-cli/src/oauth/sign-in-to-remote-again.ts b/packages/twenty-cli/src/oauth/sign-in-to-remote-again.ts
new file mode 100644
index 00000000000..a761e5349d7
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/sign-in-to-remote-again.ts
@@ -0,0 +1,101 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { getCredentialKind } from '@/config/get-credential-kind';
+import { readConfig } from '@/config/read-config';
+import { replaceRemoteCredentials } from '@/config/replace-remote-credentials';
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { updateConfig } from '@/config/update-config';
+import { confirmInTerminal } from '@/input/confirm-in-terminal';
+import { signInWithBrowser } from '@/oauth/sign-in-with-browser';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { type Output } from '@/output/types/output.type';
+import { parseApiUrl } from '@/target/parse-api-url';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { fetchSignedInIdentity } from '@/transport/metadata/fetch-signed-in-identity';
+
+const readUnchangedRemote = (
+ config: ConfigFile,
+ target: ResolvedTarget,
+ remoteName: string,
+) => {
+ const remote = Object.hasOwn(config.remotes, remoteName)
+ ? config.remotes[remoteName]
+ : undefined;
+
+ if (
+ !isDefined(remote) ||
+ getCredentialKind(remote) !== 'oauth' ||
+ remote.twentyCLIAccessToken !== target.bearerToken ||
+ parseApiUrl({ rawUrl: remote.apiUrl, sourceName: remoteName }) !==
+ target.apiUrl
+ ) {
+ throw new CliError({
+ code: 'CONFLICT',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: `Remote ${remoteName} changed while signing in again. No credentials were saved.`,
+ hint: 'Run the command again.',
+ });
+ }
+
+ return remote;
+};
+
+export const signInToRemoteAgain = async ({
+ target,
+ remoteName,
+ error,
+ configPath,
+ output,
+ signal,
+}: {
+ target: ResolvedTarget;
+ remoteName: string;
+ error: CliError;
+ configPath: string;
+ output: Output;
+ signal: AbortSignal;
+}): Promise<ResolvedTarget> => {
+ readUnchangedRemote(await readConfig(configPath), target, remoteName);
+
+ if (
+ !(await confirmInTerminal({
+ question: `Your session on ${remoteName} is no longer valid. Sign in again now?`,
+ signal,
+ }))
+ ) {
+ throw error;
+ }
+
+ const credentials = await signInWithBrowser({
+ apiUrl: target.apiUrl,
+ output,
+ signal,
+ });
+ const signedInTarget = { ...target, bearerToken: credentials.accessToken };
+
+ await fetchSignedInIdentity({ target: signedInTarget, signal });
+ await updateConfig({
+ configPath,
+ signal,
+ update: (config) => {
+ const remote = readUnchangedRemote(config, target, remoteName);
+
+ return {
+ result: undefined,
+ config: {
+ ...config,
+ remotes: {
+ ...config.remotes,
+ [remoteName]: replaceRemoteCredentials({
+ remote,
+ credentials: { kind: 'oauth', ...credentials },
+ }),
+ },
+ },
+ };
+ },
+ });
+
+ return signedInTarget;
+};
diff --git a/packages/twenty-cli/src/oauth/sign-in-with-browser.ts b/packages/twenty-cli/src/oauth/sign-in-with-browser.ts
new file mode 100644
index 00000000000..02f01805094
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/sign-in-with-browser.ts
@@ -0,0 +1,70 @@
+import { randomBytes } from 'node:crypto';
+
+import { createPkcePair } from '@/oauth/create-pkce-pair';
+import { discoverOAuthServer } from '@/oauth/discover-oauth-server';
+import { openBrowser } from '@/oauth/open-browser';
+import { requestOAuthTokens } from '@/oauth/request-oauth-tokens';
+import { startCallbackServer } from '@/oauth/start-callback-server';
+import { type Output } from '@/output/types/output.type';
+
+export const signInWithBrowser = async ({
+ apiUrl,
+ output,
+ signal,
+}: {
+ apiUrl: string;
+ output: Output;
+ signal: AbortSignal;
+}) => {
+ const oauthServer = await discoverOAuthServer({ apiUrl, signal });
+ const { codeVerifier, codeChallenge } = createPkcePair();
+ const state = randomBytes(16).toString('base64url');
+ const callbackServer = await startCallbackServer({
+ state,
+ issuer: oauthServer.issuer,
+ isIssuerInResponse: oauthServer.isIssuerInResponse,
+ signal,
+ });
+
+ try {
+ const authorizationUrl = new URL(oauthServer.authorizationEndpoint);
+
+ authorizationUrl.searchParams.set('response_type', 'code');
+ authorizationUrl.searchParams.set('client_id', oauthServer.clientId);
+ authorizationUrl.searchParams.set('code_challenge', codeChallenge);
+ authorizationUrl.searchParams.set('code_challenge_method', 'S256');
+ authorizationUrl.searchParams.set(
+ 'redirect_uri',
+ callbackServer.redirectUri,
+ );
+ authorizationUrl.searchParams.set('state', state);
+
+ output.progress(
+ `Opening your browser to sign in to ${new URL(apiUrl).host}…`,
+ );
+
+ openBrowser(authorizationUrl.href);
+ output.progress(`If nothing opens, visit: ${authorizationUrl.href}`);
+ output.progress(
+ 'Waiting for you to approve in the browser. Press Ctrl+C to cancel.',
+ );
+
+ const code = await callbackServer.waitForCode();
+ const tokens = await requestOAuthTokens({
+ apiUrl,
+ tokenEndpoint: oauthServer.tokenEndpoint,
+ parameters: {
+ grant_type: 'authorization_code',
+ code,
+ code_verifier: codeVerifier,
+ redirect_uri: callbackServer.redirectUri,
+ client_id: oauthServer.clientId,
+ },
+ signal,
+ });
+
+ return { ...tokens, clientId: oauthServer.clientId };
+ } finally {
+ callbackServer.close();
+ }
+};
diff --git a/packages/twenty-cli/src/oauth/start-callback-server.ts b/packages/twenty-cli/src/oauth/start-callback-server.ts
new file mode 100644
index 00000000000..fa172c014d8
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/start-callback-server.ts
@@ -0,0 +1,171 @@
+import { createServer } from 'node:http';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { OAUTH_TIMING } from '@/oauth/constants/oauth-timing.constant';
+import { CliError } from '@/output/cli-error';
+import { getListeningPort } from '@/utils/get-listening-port';
+
+const CALLBACK_PATH = '/callback';
+
+const renderCallbackPage = (message: string) =>
+ `<!doctype html><meta charset="utf-8"><title>Twenty CLI</title><body style="margin:0;display:grid;place-items:center;min-height:100vh;font-family:system-ui,sans-serif"><p>${message}</p></body>`;
+
+const createSignInError = (message: string) =>
+ new CliError({
+ code: 'OAUTH_FAILED',
+ message,
+ hint: 'Run twenty auth login again.',
+ });
+
+const readAuthorizationCode = ({
+ url,
+ state,
+ issuer,
+ isIssuerInResponse,
+}: {
+ url: URL;
+ state: string;
+ issuer: string;
+ isIssuerInResponse: boolean;
+}) => {
+ const returnedIssuer = url.searchParams.get('iss');
+
+ if (isIssuerInResponse && !isDefined(returnedIssuer)) {
+ throw createSignInError(
+ 'The sign-in response does not say which server sent it.',
+ );
+ }
+
+ if (isDefined(returnedIssuer) && returnedIssuer !== issuer) {
+ throw createSignInError(
+ `The sign-in response came from ${returnedIssuer} instead of ${issuer}.`,
+ );
+ }
+
+ if (url.searchParams.get('state') !== state) {
+ throw createSignInError(
+ 'The sign-in response does not match this login attempt.',
+ );
+ }
+
+ const error = url.searchParams.get('error');
+
+ if (isNonEmptyString(error)) {
+ throw createSignInError(
+ error === 'access_denied'
+ ? 'Sign-in was declined in the browser.'
+ : `Sign-in failed: ${url.searchParams.get('error_description') ?? error}`,
+ );
+ }
+
+ const code = url.searchParams.get('code');
+
+ if (!isNonEmptyString(code)) {
+ throw createSignInError('The sign-in response has no authorization code.');
+ }
+
+ return code;
+};
+
+export const startCallbackServer = async ({
+ state,
+ issuer,
+ isIssuerInResponse,
+ signal,
+}: {
+ state: string;
+ issuer: string;
+ isIssuerInResponse: boolean;
+ signal: AbortSignal;
+}) => {
+ const {
+ promise: codePromise,
+ resolve,
+ reject,
+ } = Promise.withResolvers<string>();
+
+ codePromise.catch(() => undefined);
+
+ const server = createServer((request, response) => {
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
+
+ if (url.pathname !== CALLBACK_PATH) {
+ response.writeHead(404, { Connection: 'close' }).end();
+
+ return;
+ }
+
+ try {
+ const code = readAuthorizationCode({
+ url,
+ state,
+ issuer,
+ isIssuerInResponse,
+ });
+
+ response
+ .writeHead(200, {
+ 'Content-Type': 'text/html; charset=utf-8',
+ Connection: 'close',
+ })
+ .end(
+ renderCallbackPage(
+ 'Signed in. You can close this tab and go back to the terminal.',
+ ),
+ );
+ resolve(code);
+ } catch (error) {
+ response
+ .writeHead(400, {
+ 'Content-Type': 'text/html; charset=utf-8',
+ Connection: 'close',
+ })
+ .end(
+ renderCallbackPage(
+ 'Sign-in did not complete. Go back to the terminal for details.',
+ ),
+ );
+ reject(error);
+ }
+ });
+
+ await new Promise<void>((listening, failed) => {
+ server.once('error', failed);
+ server.listen(0, '127.0.0.1', () => listening());
+ });
+
+ const port = getListeningPort(server);
+ const timeout = setTimeout(
+ () =>
+ reject(
+ new CliError({
+ code: 'TIMEOUT',
+ message: `Sign-in was not completed within ${OAUTH_TIMING.SIGN_IN_TIMEOUT_MILLISECONDS / 60_000} minutes.`,
+ hint: 'Run twenty auth login again.',
+ }),
+ ),
+ OAUTH_TIMING.SIGN_IN_TIMEOUT_MILLISECONDS,
+ );
+ const rejectOnAbort = () => reject(signal.reason);
+ const close = () => {
+ clearTimeout(timeout);
+ signal.removeEventListener('abort', rejectOnAbort);
+ server.closeAllConnections();
+ server.close();
+ };
+
+ if (signal.aborted) {
+ close();
+ signal.throwIfAborted();
+ }
+
+ signal.addEventListener('abort', rejectOnAbort, { once: true });
+
+ return {
+ redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`,
+ waitForCode: () => codePromise,
+ close,
+ };
+};
diff --git a/packages/twenty-cli/src/oauth/types/oauth-server.type.ts b/packages/twenty-cli/src/oauth/types/oauth-server.type.ts
new file mode 100644
index 00000000000..922a4bbe1d9
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/types/oauth-server.type.ts
@@ -0,0 +1,7 @@
+export type OAuthServer = {
+ issuer: string;
+ isIssuerInResponse: boolean;
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ clientId: string;
+};
diff --git a/packages/twenty-cli/src/oauth/types/oauth-tokens.type.ts b/packages/twenty-cli/src/oauth/types/oauth-tokens.type.ts
new file mode 100644
index 00000000000..32fc33cc744
--- /dev/null
+++ b/packages/twenty-cli/src/oauth/types/oauth-tokens.type.ts
@@ -0,0 +1,4 @@
+export type OAuthTokens = {
+ accessToken: string;
+ refreshToken?: string;
+};
diff --git a/packages/twenty-cli/src/output/__tests__/detect-output-mode.spec.ts b/packages/twenty-cli/src/output/__tests__/detect-output-mode.spec.ts
new file mode 100644
index 00000000000..922ff84bb79
--- /dev/null
+++ b/packages/twenty-cli/src/output/__tests__/detect-output-mode.spec.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { detectOutputMode } from '@/output/detect-output-mode';
+
+describe('detectOutputMode', () => {
+ it('defaults to human output', () => {
+ expect(detectOutputMode(['version'])).toBe('human');
+ });
+
+ it('selects JSON with --json or --format json in either spelling', () => {
+ expect(detectOutputMode(['version', '--json'])).toBe('json');
+ expect(detectOutputMode(['--format', 'json', 'version'])).toBe('json');
+ expect(detectOutputMode(['version', '--format=json'])).toBe('json');
+ });
+
+ it('selects NDJSON with --format ndjson', () => {
+ expect(detectOutputMode(['--format=ndjson', 'version'])).toBe('ndjson');
+ });
+
+ it('uses the last --format value, like the option parser', () => {
+ expect(
+ detectOutputMode(['version', '--format', 'human', '--format', 'json']),
+ ).toBe('json');
+ expect(
+ detectOutputMode(['version', '--format=json', '--format=human']),
+ ).toBe('human');
+ expect(
+ detectOutputMode(['version', '--format=ndjson', '--format', 'json']),
+ ).toBe('json');
+ });
+
+ it('ignores arguments after --', () => {
+ expect(detectOutputMode(['api', '--', '--json'])).toBe('human');
+ });
+});
diff --git a/packages/twenty-cli/src/output/cli-error.ts b/packages/twenty-cli/src/output/cli-error.ts
new file mode 100644
index 00000000000..cf85600b337
--- /dev/null
+++ b/packages/twenty-cli/src/output/cli-error.ts
@@ -0,0 +1,35 @@
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { type CliErrorCode } from '@/output/types/cli-error-code.type';
+import { type ExitCode } from '@/output/types/exit-code.type';
+
+type CliErrorOptions = {
+ code: CliErrorCode;
+ message: string;
+ exitCode?: ExitCode;
+ hint?: string;
+ details?: Record<string, unknown>;
+ cause?: unknown;
+};
+
+export class CliError extends Error {
+ readonly code: CliErrorCode;
+ readonly exitCode: ExitCode;
+ readonly hint?: string;
+ readonly details?: Record<string, unknown>;
+
+ constructor({
+ code,
+ message,
+ exitCode = EXIT_CODE.FAILURE,
+ hint,
+ details,
+ cause,
+ }: CliErrorOptions) {
+ super(message, { cause });
+ this.name = 'CliError';
+ this.code = code;
+ this.exitCode = exitCode;
+ this.hint = hint;
+ this.details = details;
+ }
+}
diff --git a/packages/twenty-cli/src/output/constants/exit-code.constant.ts b/packages/twenty-cli/src/output/constants/exit-code.constant.ts
new file mode 100644
index 00000000000..897ab055067
--- /dev/null
+++ b/packages/twenty-cli/src/output/constants/exit-code.constant.ts
@@ -0,0 +1,10 @@
+export const EXIT_CODE = {
+ SUCCESS: 0,
+ FAILURE: 1,
+ USAGE: 2,
+ AUTHENTICATION: 3,
+ NOT_FOUND: 4,
+ PARTIAL_FAILURE: 5,
+ CONFLICT: 6,
+ CANCELLED: 130,
+} as const;
diff --git a/packages/twenty-cli/src/output/constants/json-schema-version.constant.ts b/packages/twenty-cli/src/output/constants/json-schema-version.constant.ts
new file mode 100644
index 00000000000..e23854b6255
--- /dev/null
+++ b/packages/twenty-cli/src/output/constants/json-schema-version.constant.ts
@@ -0,0 +1 @@
+export const JSON_SCHEMA_VERSION = 1;
diff --git a/packages/twenty-cli/src/output/constants/output-modes.constant.ts b/packages/twenty-cli/src/output/constants/output-modes.constant.ts
new file mode 100644
index 00000000000..ed2edb9a05d
--- /dev/null
+++ b/packages/twenty-cli/src/output/constants/output-modes.constant.ts
@@ -0,0 +1 @@
+export const OUTPUT_MODES = ['human', 'json', 'ndjson'] as const;
diff --git a/packages/twenty-cli/src/output/constants/table-layout.constant.ts b/packages/twenty-cli/src/output/constants/table-layout.constant.ts
new file mode 100644
index 00000000000..aed7689d01b
--- /dev/null
+++ b/packages/twenty-cli/src/output/constants/table-layout.constant.ts
@@ -0,0 +1,4 @@
+export const TABLE_LAYOUT = {
+ COLUMN_GAP: ' ',
+ ROW_INDENT: ' ',
+} as const;
diff --git a/packages/twenty-cli/src/output/create-cancelled-error.ts b/packages/twenty-cli/src/output/create-cancelled-error.ts
new file mode 100644
index 00000000000..e22e5eb2f12
--- /dev/null
+++ b/packages/twenty-cli/src/output/create-cancelled-error.ts
@@ -0,0 +1,9 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const createCancelledError = () =>
+ new CliError({
+ code: 'CANCELLED',
+ message: 'Cancelled.',
+ exitCode: EXIT_CODE.CANCELLED,
+ });
diff --git a/packages/twenty-cli/src/output/create-output.ts b/packages/twenty-cli/src/output/create-output.ts
new file mode 100644
index 00000000000..d1d8690cbc0
--- /dev/null
+++ b/packages/twenty-cli/src/output/create-output.ts
@@ -0,0 +1,158 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { JSON_SCHEMA_VERSION } from '@/output/constants/json-schema-version.constant';
+import { formatFailureLine, formatWarningLine } from '@/output/style';
+import { type CliWarning } from '@/output/types/cli-warning.type';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { type Output } from '@/output/types/output.type';
+import { writeStreamEvent } from '@/output/write-stream-event';
+import { type PublicTarget } from '@/target/types/public-target.type';
+
+const writeLine = (stream: NodeJS.WriteStream, text: string) => {
+ stream.write(text.endsWith('\n') ? text : `${text}\n`);
+};
+
+const writeJsonLine = (value: unknown) => {
+ writeLine(process.stdout, JSON.stringify(value));
+};
+
+const indentLines = (text: string) =>
+ text
+ .split('\n')
+ .map((line) => (isNonEmptyString(line) ? ` ${line}` : line))
+ .join('\n');
+
+const withTarget = (target: PublicTarget | undefined) =>
+ isDefined(target) ? { target } : {};
+
+export const createOutput = ({
+ mode,
+ command,
+}: {
+ mode: OutputMode;
+ command: string;
+}): Output => {
+ const warnings: CliWarning[] = [];
+ let eventSequence = 0;
+
+ const writeEvent = (type: string, data: unknown) => {
+ eventSequence += 1;
+ writeJsonLine({
+ schemaVersion: JSON_SCHEMA_VERSION,
+ command,
+ type,
+ sequence: eventSequence,
+ data,
+ });
+ };
+
+ const writeHumanWarnings = () => {
+ for (const warning of warnings) {
+ writeLine(process.stderr, formatWarningLine(warning.message));
+ }
+ };
+
+ return {
+ event: async (type, data, signal) => {
+ if (mode !== 'ndjson') {
+ return;
+ }
+
+ eventSequence += 1;
+ await writeStreamEvent(
+ {
+ schemaVersion: JSON_SCHEMA_VERSION,
+ command,
+ type,
+ sequence: eventSequence,
+ data,
+ },
+ signal,
+ );
+ },
+ progress: (message) => {
+ if (mode === 'ndjson') {
+ writeEvent('progress', { message });
+
+ return;
+ }
+
+ writeLine(process.stderr, message);
+ },
+ warn: (warning) => {
+ if (mode === 'ndjson') {
+ writeEvent('warning', warning);
+
+ return;
+ }
+
+ warnings.push(warning);
+ },
+ succeed: ({ data, human }, target) => {
+ if (mode === 'json') {
+ writeJsonLine({
+ schemaVersion: JSON_SCHEMA_VERSION,
+ ok: true,
+ command,
+ ...withTarget(target),
+ data,
+ warnings,
+ });
+
+ return;
+ }
+
+ if (mode === 'ndjson') {
+ writeEvent('result', data);
+
+ return;
+ }
+
+ const humanText = human ?? JSON.stringify(data, null, 2);
+
+ if (isNonEmptyString(humanText)) {
+ writeLine(process.stdout, humanText);
+ }
+
+ writeHumanWarnings();
+ },
+ fail: (error, target) => {
+ process.exitCode = error.exitCode;
+
+ const errorPayload = {
+ code: error.code,
+ message: error.message,
+ ...(isDefined(error.hint) ? { hint: error.hint } : {}),
+ ...(isDefined(error.details) ? { details: error.details } : {}),
+ };
+
+ if (mode === 'json') {
+ writeJsonLine({
+ schemaVersion: JSON_SCHEMA_VERSION,
+ ok: false,
+ command,
+ ...withTarget(target),
+ error: errorPayload,
+ warnings,
+ });
+
+ return;
+ }
+
+ if (mode === 'ndjson') {
+ writeEvent('error', errorPayload);
+
+ return;
+ }
+
+ writeLine(process.stderr, formatFailureLine(error.message));
+
+ if (isDefined(error.hint)) {
+ writeLine(process.stderr, indentLines(error.hint));
+ }
+
+ writeHumanWarnings();
+ },
+ };
+};
diff --git a/packages/twenty-cli/src/output/detect-output-mode.ts b/packages/twenty-cli/src/output/detect-output-mode.ts
new file mode 100644
index 00000000000..4947a8035f8
--- /dev/null
+++ b/packages/twenty-cli/src/output/detect-output-mode.ts
@@ -0,0 +1,33 @@
+import { type OutputMode } from '@/output/types/output-mode.type';
+
+const FORMAT_FLAG = '--format';
+
+const findLastFormatValue = (args: string[]) =>
+ args.reduce<string | undefined>((formatValue, argument, argumentIndex) => {
+ if (argument.startsWith(`${FORMAT_FLAG}=`)) {
+ return argument.slice(FORMAT_FLAG.length + 1);
+ }
+
+ if (argument === FORMAT_FLAG) {
+ return args[argumentIndex + 1];
+ }
+
+ return formatValue;
+ }, undefined);
+
+export const detectOutputMode = (args: string[]): OutputMode => {
+ const endOfOptionsIndex = args.indexOf('--');
+ const optionArguments =
+ endOfOptionsIndex === -1 ? args : args.slice(0, endOfOptionsIndex);
+ const formatValue = findLastFormatValue(optionArguments);
+
+ if (optionArguments.includes('--json') || formatValue === 'json') {
+ return 'json';
+ }
+
+ if (formatValue === 'ndjson') {
+ return 'ndjson';
+ }
+
+ return 'human';
+};
diff --git a/packages/twenty-cli/src/output/format-details.ts b/packages/twenty-cli/src/output/format-details.ts
new file mode 100644
index 00000000000..7a293f7ec3a
--- /dev/null
+++ b/packages/twenty-cli/src/output/format-details.ts
@@ -0,0 +1,9 @@
+import { dimText } from '@/output/style';
+
+export const formatDetails = (rows: [label: string, value: string][]) => {
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
+
+ return rows
+ .map(([label, value]) => `${dimText(label.padEnd(labelWidth))} ${value}`)
+ .join('\n');
+};
diff --git a/packages/twenty-cli/src/output/format-list.ts b/packages/twenty-cli/src/output/format-list.ts
new file mode 100644
index 00000000000..daded40ef11
--- /dev/null
+++ b/packages/twenty-cli/src/output/format-list.ts
@@ -0,0 +1,4 @@
+export const formatList = (items: string[]) =>
+ items.length <= 1
+ ? items.join('')
+ : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
diff --git a/packages/twenty-cli/src/output/format-table.ts b/packages/twenty-cli/src/output/format-table.ts
new file mode 100644
index 00000000000..f3339cd3650
--- /dev/null
+++ b/packages/twenty-cli/src/output/format-table.ts
@@ -0,0 +1,59 @@
+import { stripVTControlCharacters } from 'node:util';
+
+import { TABLE_LAYOUT } from '@/output/constants/table-layout.constant';
+import { dimText } from '@/output/style';
+
+type TableColumn<TRow> = {
+ header: string;
+ value: (row: TRow) => string;
+ align?: 'left' | 'right';
+};
+
+const getVisibleLength = (text: string) =>
+ stripVTControlCharacters(text).length;
+
+const pad = ({
+ cell,
+ width,
+ align,
+}: {
+ cell: string;
+ width: number;
+ align: 'left' | 'right';
+}) => {
+ const padding = ' '.repeat(Math.max(0, width - getVisibleLength(cell)));
+
+ return align === 'right' ? `${padding}${cell}` : `${cell}${padding}`;
+};
+
+export const formatTable = <TRow>({
+ rows,
+ columns,
+}: {
+ rows: TRow[];
+ columns: TableColumn<TRow>[];
+}) => {
+ const cells = rows.map((row) => columns.map((column) => column.value(row)));
+ const widths = columns.map((column, columnIndex) =>
+ Math.max(
+ column.header.length,
+ ...cells.map((rowCells) => getVisibleLength(rowCells[columnIndex])),
+ ),
+ );
+
+ const formatRow = (rowCells: string[]) =>
+ `${TABLE_LAYOUT.ROW_INDENT}${rowCells
+ .map((cell, columnIndex) =>
+ pad({
+ cell,
+ width: widths[columnIndex],
+ align: columns[columnIndex].align ?? 'left',
+ }),
+ )
+ .join(TABLE_LAYOUT.COLUMN_GAP)}`.trimEnd();
+
+ return [
+ dimText(formatRow(columns.map((column) => column.header))),
+ ...cells.map(formatRow),
+ ].join('\n');
+};
diff --git a/packages/twenty-cli/src/output/style.ts b/packages/twenty-cli/src/output/style.ts
new file mode 100644
index 00000000000..64b978415e1
--- /dev/null
+++ b/packages/twenty-cli/src/output/style.ts
@@ -0,0 +1,26 @@
+import { styleText } from 'node:util';
+
+export const dimText = (
+ text: string,
+ stream: NodeJS.WriteStream = process.stdout,
+) => styleText('dim', text, { stream });
+
+export const colorText = (
+ color: 'cyan' | 'green' | 'magenta' | 'red' | 'yellow',
+ text: string,
+ stream: NodeJS.WriteStream = process.stdout,
+) => styleText(color, text, { stream });
+
+export const boldText = (
+ text: string,
+ stream: NodeJS.WriteStream = process.stdout,
+) => styleText('bold', text, { stream });
+
+export const formatSuccessLine = (message: string) =>
+ `${styleText('green', '✓', { stream: process.stdout })} ${message}`;
+
+export const formatFailureLine = (message: string) =>
+ `${styleText('red', '✗', { stream: process.stderr })} ${message}`;
+
+export const formatWarningLine = (message: string) =>
+ `${styleText('yellow', '!', { stream: process.stderr })} ${message}`;
diff --git a/packages/twenty-cli/src/output/to-cli-error.ts b/packages/twenty-cli/src/output/to-cli-error.ts
new file mode 100644
index 00000000000..eaa2ba05456
--- /dev/null
+++ b/packages/twenty-cli/src/output/to-cli-error.ts
@@ -0,0 +1,17 @@
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+export const toCliError = (error: unknown, signal?: AbortSignal): CliError => {
+ if (error instanceof CliError) {
+ return error;
+ }
+
+ if (signal?.aborted === true) {
+ return createCancelledError();
+ }
+
+ return new CliError({
+ code: 'INTERNAL_ERROR',
+ message: error instanceof Error ? error.message : String(error),
+ });
+};
diff --git a/packages/twenty-cli/src/output/types/cli-error-code.type.ts b/packages/twenty-cli/src/output/types/cli-error-code.type.ts
new file mode 100644
index 00000000000..c0f62fc8194
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/cli-error-code.type.ts
@@ -0,0 +1,60 @@
+export type CliErrorCode =
+ | 'AMBIGUOUS_RESOURCE'
+ | 'APP_EXPORT_UNSUPPORTED'
+ | 'APP_INIT_FAILED'
+ | 'APP_NOT_EXPORTABLE'
+ | 'APP_NOT_FOUND'
+ | 'APP_NOT_INSTALLED'
+ | 'APP_NOT_UNINSTALLABLE'
+ | 'APP_PATH_REQUIRED'
+ | 'APP_PATH_UNAVAILABLE'
+ | 'AUTH_REQUIRED'
+ | 'BUILD_FAILED'
+ | 'CANCELLED'
+ | 'CLIENT_GENERATION_FAILED'
+ | 'CONFIG_LOCKED'
+ | 'CONFIRMATION_DECLINED'
+ | 'CONFIRMATION_REQUIRED'
+ | 'CONFLICT'
+ | 'CONFLICTING_TARGET'
+ | 'CREATE_REQUIRED'
+ | 'DOCTOR_FAILED'
+ | 'EXECUTION_FAILED'
+ | 'GRAPHQL_ERROR'
+ | 'HTTP_ERROR'
+ | 'IDENTITY_READ_FAILED'
+ | 'INCOMPLETE_TARGET'
+ | 'INTERNAL_ERROR'
+ | 'INVALID_API_URL'
+ | 'INVALID_APP_NAME'
+ | 'INVALID_CONFIG'
+ | 'INVALID_INPUT'
+ | 'INVALID_REMOTE_NAME'
+ | 'INVALID_REQUEST_PATH'
+ | 'INVALID_RESPONSE'
+ | 'NETWORK_ERROR'
+ | 'NODE_VERSION_UNSUPPORTED'
+ | 'NOT_FOUND'
+ | 'OAUTH_FAILED'
+ | 'OAUTH_UNAVAILABLE'
+ | 'PERMISSION_DENIED'
+ | 'PLAN_UNAVAILABLE'
+ | 'PULL_BASE_RECORD_FAILED'
+ | 'PULL_FAILED'
+ | 'REDIRECT_NOT_FOLLOWED'
+ | 'REMOTE_EXISTS'
+ | 'RESPONSE_LIMIT_EXCEEDED'
+ | 'RESULT_LIMIT_EXCEEDED'
+ | 'SDK_NOT_INSTALLED'
+ | 'SDK_SOURCE_UNSUPPORTED'
+ | 'SNAPSHOT_INVALID'
+ | 'TARGET_REQUIRED'
+ | 'TIMEOUT'
+ | 'TOOLING_UNSUPPORTED'
+ | 'TYPECHECK_FAILED'
+ | 'TYPESCRIPT_NOT_INSTALLED'
+ | 'UNKNOWN_REMOTE'
+ | 'UNSUPPORTED_RESPONSE_TYPE'
+ | 'UPLOAD_FAILED'
+ | 'USAGE'
+ | 'WORKER_FAILED';
diff --git a/packages/twenty-cli/src/output/types/cli-warning.type.ts b/packages/twenty-cli/src/output/types/cli-warning.type.ts
new file mode 100644
index 00000000000..c66d852f7ec
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/cli-warning.type.ts
@@ -0,0 +1,4 @@
+export type CliWarning = {
+ code: string;
+ message: string;
+};
diff --git a/packages/twenty-cli/src/output/types/command-result.type.ts b/packages/twenty-cli/src/output/types/command-result.type.ts
new file mode 100644
index 00000000000..7cde05c211b
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/command-result.type.ts
@@ -0,0 +1,4 @@
+export type CommandResult<TData = unknown> = {
+ data: TData;
+ human?: string;
+};
diff --git a/packages/twenty-cli/src/output/types/exit-code.type.ts b/packages/twenty-cli/src/output/types/exit-code.type.ts
new file mode 100644
index 00000000000..0ea899e0222
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/exit-code.type.ts
@@ -0,0 +1,3 @@
+import { type EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE];
diff --git a/packages/twenty-cli/src/output/types/output-mode.type.ts b/packages/twenty-cli/src/output/types/output-mode.type.ts
new file mode 100644
index 00000000000..723272e25a6
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/output-mode.type.ts
@@ -0,0 +1,3 @@
+import { type OUTPUT_MODES } from '@/output/constants/output-modes.constant';
+
+export type OutputMode = (typeof OUTPUT_MODES)[number];
diff --git a/packages/twenty-cli/src/output/types/output.type.ts b/packages/twenty-cli/src/output/types/output.type.ts
new file mode 100644
index 00000000000..533e4824e75
--- /dev/null
+++ b/packages/twenty-cli/src/output/types/output.type.ts
@@ -0,0 +1,16 @@
+import { type CliError } from '@/output/cli-error';
+import { type CliWarning } from '@/output/types/cli-warning.type';
+import { type CommandResult } from '@/output/types/command-result.type';
+import { type PublicTarget } from '@/target/types/public-target.type';
+
+export type Output = {
+ event: (
+ type: 'start' | 'record' | 'progress',
+ data: unknown,
+ signal: AbortSignal,
+ ) => Promise<void>;
+ warn: (warning: CliWarning) => void;
+ progress: (message: string) => void;
+ succeed: (result: CommandResult, target?: PublicTarget) => void;
+ fail: (error: CliError, target?: PublicTarget) => void;
+};
diff --git a/packages/twenty-cli/src/output/write-stream-event.ts b/packages/twenty-cli/src/output/write-stream-event.ts
new file mode 100644
index 00000000000..6d004511678
--- /dev/null
+++ b/packages/twenty-cli/src/output/write-stream-event.ts
@@ -0,0 +1,11 @@
+import { once } from 'node:events';
+
+export const writeStreamEvent = async (event: unknown, signal: AbortSignal) => {
+ signal.throwIfAborted();
+
+ if (!process.stdout.write(`${JSON.stringify(event)}\n`)) {
+ await once(process.stdout, 'drain', { signal });
+ }
+
+ signal.throwIfAborted();
+};
diff --git a/packages/twenty-cli/src/program/__tests__/reauthentication.spec.ts b/packages/twenty-cli/src/program/__tests__/reauthentication.spec.ts
new file mode 100644
index 00000000000..44e14d56633
--- /dev/null
+++ b/packages/twenty-cli/src/program/__tests__/reauthentication.spec.ts
@@ -0,0 +1,392 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import { runCliForTest } from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { confirmInTerminal } from '@/input/confirm-in-terminal';
+import { signInWithBrowser } from '@/oauth/sign-in-with-browser';
+import { type ConfigFile } from '@/config/types/config-file.type';
+
+vi.mock('@/input/confirm-in-terminal', () => ({ confirmInTerminal: vi.fn() }));
+vi.mock('@/oauth/sign-in-with-browser', () => ({ signInWithBrowser: vi.fn() }));
+
+const state = {
+ acceptsOldToken: false,
+ rejectsNewToken: false,
+ identityStatus: 401,
+ refreshStatus: 400,
+ graphqlError: '',
+ operationStatus: 200,
+};
+const server = await startTestServer((request, response) => {
+ if (request.path === '/.well-known/oauth-authorization-server') {
+ sendJson(response, 200, {
+ issuer: server.url,
+ authorization_endpoint: `${server.url}/authorize`,
+ token_endpoint: `${server.url}/oauth/token`,
+ cli_client_id: 'old-client',
+ code_challenge_methods_supported: ['S256'],
+ });
+
+ return;
+ }
+
+ if (request.path === '/oauth/token') {
+ sendJson(response, state.refreshStatus, { error: 'invalid_grant' });
+
+ return;
+ }
+
+ if (request.path === '/metadata') {
+ const isNewToken = request.headers.authorization === 'Bearer new-session';
+
+ if (
+ (isNewToken && !state.rejectsNewToken) ||
+ (!isNewToken && state.acceptsOldToken)
+ ) {
+ sendJson(response, 200, {
+ data: {
+ currentWorkspace: { displayName: 'Test workspace' },
+ currentUser: { email: '[email protected]' },
+ },
+ });
+ } else if (state.graphqlError) {
+ sendJson(response, 200, {
+ errors: [
+ {
+ message: 'Session rejected',
+ extensions: { code: state.graphqlError },
+ },
+ ],
+ });
+ } else {
+ sendJson(response, state.identityStatus, { error: 'Session rejected' });
+ }
+
+ return;
+ }
+
+ sendJson(response, state.operationStatus, { result: 'command-result' });
+});
+
+const runMutation = (flags: string[] = []) =>
+ runCliForTest([
+ 'api',
+ 'rest',
+ '/rest/companies',
+ '--method',
+ 'POST',
+ '--body',
+ '{"name":"New company"}',
+ ...flags,
+ ]);
+const operationRequests = () =>
+ server.requests.filter((request) => request.path === '/rest/companies');
+const setTerminal = (isTerminal: boolean) =>
+ vi
+ .spyOn(process, 'stdin', 'get')
+ .mockReturnValue(createStandardInputStub({ isTerminal }));
+
+describe('interactive OAuth session recovery', () => {
+ let home: string;
+ let configPath: string;
+ let initialConfig: ConfigFile;
+ const readSaved = async (): Promise<ConfigFile> =>
+ JSON.parse(await readFile(configPath, 'utf8'));
+ const save = (config: ConfigFile) =>
+ writeFile(configPath, JSON.stringify(config));
+
+ beforeEach(async () => {
+ home = await mkdtemp(join(tmpdir(), 'twenty-reauth-'));
+ await mkdir(join(home, '.twenty'));
+ configPath = join(home, '.twenty/config.json');
+ initialConfig = {
+ version: 1,
+ defaultRemote: 'work',
+ customSetting: 'keep-top-level',
+ remotes: {
+ work: {
+ apiUrl: server.url,
+ apiKey: 'stale-api-key',
+ twentyCLIAccessToken: 'old-session',
+ twentyCLIRefreshToken: 'old-refresh',
+ twentyCLIRegistrationClientId: 'old-client',
+ appRegistrationId: 'keep-registration',
+ workspaceName: 'keep-workspace',
+ },
+ other: { apiUrl: 'https://other.example', apiKey: 'other-key' },
+ },
+ };
+ await save(initialConfig);
+ vi.stubEnv('HOME', home);
+ vi.stubEnv('CI', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ setTerminal(true);
+ vi.mocked(confirmInTerminal).mockResolvedValue(true);
+ vi.mocked(signInWithBrowser).mockResolvedValue({
+ accessToken: 'new-session',
+ clientId: 'new-client',
+ });
+ Object.assign(state, {
+ acceptsOldToken: false,
+ rejectsNewToken: false,
+ identityStatus: 401,
+ refreshStatus: 400,
+ graphqlError: '',
+ operationStatus: 200,
+ });
+ server.requests.length = 0;
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ vi.mocked(confirmInTerminal).mockReset();
+ vi.mocked(signInWithBrowser).mockReset();
+ await rm(home, { recursive: true, force: true });
+ });
+
+ afterAll(() => server.close());
+
+ it.each(['http', 'graphql'])(
+ 'recovers a rejected session before executing a mutation (%s)',
+ async (kind) => {
+ if (kind === 'graphql') state.graphqlError = 'UNAUTHENTICATED';
+ vi.mocked(confirmInTerminal).mockImplementation(async () => {
+ expect(operationRequests()).toHaveLength(0);
+
+ return true;
+ });
+
+ const result = await runMutation();
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(vi.mocked(confirmInTerminal)).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(signInWithBrowser)).toHaveBeenCalledTimes(1);
+ expect(operationRequests()).toHaveLength(1);
+ expect(operationRequests()[0].headers.authorization).toBe(
+ 'Bearer new-session',
+ );
+ expect(await readSaved()).toEqual({
+ ...initialConfig,
+ remotes: {
+ ...initialConfig.remotes,
+ work: {
+ apiUrl: server.url,
+ twentyCLIAccessToken: 'new-session',
+ twentyCLIRegistrationClientId: 'new-client',
+ appRegistrationId: 'keep-registration',
+ workspaceName: 'keep-workspace',
+ },
+ },
+ });
+ },
+ );
+
+ it('recovers a failed refresh before the command runs', async () => {
+ const expiredToken = `header.${Buffer.from(JSON.stringify({ exp: 1 })).toString('base64url')}.signature`;
+ initialConfig.remotes.work.twentyCLIAccessToken = expiredToken;
+ await save(initialConfig);
+
+ const result = await runMutation();
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(server.requests.map((request) => request.path)).toContain(
+ '/oauth/token',
+ );
+ expect(vi.mocked(signInWithBrowser)).toHaveBeenCalledTimes(1);
+ expect(operationRequests()).toHaveLength(1);
+ expect(operationRequests()[0].headers.authorization).toBe(
+ 'Bearer new-session',
+ );
+ });
+
+ it.each([403, 503])(
+ 'does not turn refresh HTTP %s into a browser sign-in',
+ async (status) => {
+ initialConfig.remotes.work.twentyCLIAccessToken = `header.${Buffer.from(JSON.stringify({ exp: 1 })).toString('base64url')}.signature`;
+ await save(initialConfig);
+ state.refreshStatus = status;
+
+ expect((await runMutation()).exitCode).toBe(3);
+ expect(confirmInTerminal).not.toHaveBeenCalled();
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ expect(operationRequests()).toHaveLength(0);
+ expect(await readSaved()).toEqual(initialConfig);
+ },
+ );
+
+ it.each([
+ { name: 'JSON', flags: ['--json'], ci: '', terminal: true },
+ { name: 'no input', flags: ['--no-input'], ci: '', terminal: true },
+ { name: 'CI', flags: [], ci: 'true', terminal: true },
+ { name: 'redirected stdin', flags: [], ci: '', terminal: false },
+ ])('never prompts in $name mode', async ({ flags, ci, terminal }) => {
+ vi.stubEnv('CI', ci);
+ setTerminal(terminal);
+ state.operationStatus = 401;
+
+ const result = await runMutation(flags);
+
+ expect(result.exitCode).toBe(3);
+ expect(confirmInTerminal).not.toHaveBeenCalled();
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/rest/companies',
+ ]);
+ expect(await readSaved()).toEqual(initialConfig);
+ });
+
+ it('does not offer browser login for an API key', async () => {
+ initialConfig.remotes.work = { apiUrl: server.url, apiKey: 'api-key' };
+ await save(initialConfig);
+ state.operationStatus = 401;
+
+ expect((await runMutation()).exitCode).toBe(3);
+ expect(confirmInTerminal).not.toHaveBeenCalled();
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ expect(server.requests.map((request) => request.path)).toEqual([
+ '/rest/companies',
+ ]);
+ });
+
+ it('retains the login hint without saving or executing when sign-in is declined', async () => {
+ vi.mocked(confirmInTerminal).mockResolvedValue(false);
+
+ const result = await runMutation();
+
+ expect(result.exitCode).toBe(3);
+ expect(result.stderr).toContain('twenty auth login --remote work');
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ expect(operationRequests()).toHaveLength(0);
+ expect(await readSaved()).toEqual(initialConfig);
+ });
+
+ it('does not prompt again or save a newly rejected session', async () => {
+ state.rejectsNewToken = true;
+
+ expect((await runMutation()).exitCode).toBe(3);
+ expect(confirmInTerminal).toHaveBeenCalledTimes(1);
+ expect(signInWithBrowser).toHaveBeenCalledTimes(1);
+ expect(operationRequests()).toHaveLength(0);
+ expect(await readSaved()).toEqual(initialConfig);
+ });
+
+ it.each(['FORBIDDEN', 'INTERNAL_SERVER_ERROR'])(
+ 'does not treat %s as an expired session',
+ async (code) => {
+ state.graphqlError = code;
+
+ expect((await runMutation()).exitCode).not.toBe(0);
+ expect(confirmInTerminal).not.toHaveBeenCalled();
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ expect(operationRequests()).toHaveLength(0);
+ },
+ );
+
+ it('does not retry a mutation if authentication fails after the preflight', async () => {
+ state.acceptsOldToken = true;
+ state.operationStatus = 401;
+
+ expect((await runMutation()).exitCode).toBe(3);
+ expect(operationRequests()).toHaveLength(1);
+ expect(confirmInTerminal).not.toHaveBeenCalled();
+ expect(signInWithBrowser).not.toHaveBeenCalled();
+ });
+
+ it('does not restart a command when the replacement session later fails', async () => {
+ state.operationStatus = 401;
+
+ expect((await runMutation()).exitCode).toBe(3);
+ expect(operationRequests()).toHaveLength(1);
+ expect(confirmInTerminal).toHaveBeenCalledTimes(1);
+ expect(signInWithBrowser).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ 'removed',
+ 'retargeted',
+ 'signed out',
+ 'API key',
+ 'another session',
+ ])(
+ 'refuses to overwrite a remote changed during login: %s',
+ async (change) => {
+ vi.mocked(signInWithBrowser).mockImplementation(async () => {
+ const config = await readSaved();
+ if (change === 'removed') delete config.remotes.work;
+ if (change === 'retargeted')
+ config.remotes.work.apiUrl = 'https://another.example';
+ if (change === 'signed out')
+ config.remotes.work = { apiUrl: server.url };
+ if (change === 'API key')
+ config.remotes.work = {
+ apiUrl: server.url,
+ apiKey: 'replacement-key',
+ };
+ if (change === 'another session')
+ config.remotes.work.twentyCLIAccessToken = 'concurrent-session';
+ await save(config);
+ initialConfig = config;
+
+ return { accessToken: 'new-session', clientId: 'new-client' };
+ });
+
+ const result = await runMutation();
+
+ expect(result.exitCode).toBe(6);
+ expect(result.stderr).toContain('changed while signing in again');
+ expect(operationRequests()).toHaveLength(0);
+ expect(await readSaved()).toEqual(initialConfig);
+ },
+ );
+
+ it('preserves unrelated configuration changes made during login', async () => {
+ vi.mocked(signInWithBrowser).mockImplementation(async () => {
+ const config = await readSaved();
+ config.defaultRemote = 'other';
+ config.remotes.work.appRegistrationId = 'new-registration';
+ await save(config);
+
+ return {
+ accessToken: 'new-session',
+ refreshToken: 'new-refresh',
+ clientId: 'new-client',
+ };
+ });
+
+ expect((await runMutation()).exitCode).toBe(0);
+ const saved = await readSaved();
+
+ expect(saved.defaultRemote).toBe('other');
+ expect(saved.remotes.work.appRegistrationId).toBe('new-registration');
+ expect(saved.remotes.work.twentyCLIRefreshToken).toBe('new-refresh');
+ });
+
+ it('cancels before the command if interrupted during sign-in', async () => {
+ vi.mocked(signInWithBrowser).mockImplementation(async ({ signal }) => {
+ process.emit('SIGINT');
+ signal.throwIfAborted();
+
+ return { accessToken: 'new-session', clientId: 'new-client' };
+ });
+
+ expect((await runMutation()).exitCode).toBe(130);
+ expect(operationRequests()).toHaveLength(0);
+ expect(await readSaved()).toEqual(initialConfig);
+ });
+});
diff --git a/packages/twenty-cli/src/program/command-parse-error.ts b/packages/twenty-cli/src/program/command-parse-error.ts
new file mode 100644
index 00000000000..5aa099b4b8c
--- /dev/null
+++ b/packages/twenty-cli/src/program/command-parse-error.ts
@@ -0,0 +1,23 @@
+import { type CommanderError } from 'commander';
+
+export class CommandParseError extends Error {
+ readonly commanderError: CommanderError;
+ readonly commandName: string;
+ readonly operands: string[];
+
+ constructor({
+ commanderError,
+ commandName,
+ operands,
+ }: {
+ commanderError: CommanderError;
+ commandName: string;
+ operands: string[];
+ }) {
+ super(commanderError.message);
+ this.name = 'CommandParseError';
+ this.commanderError = commanderError;
+ this.commandName = commandName;
+ this.operands = operands;
+ }
+}
diff --git a/packages/twenty-cli/src/program/constants/global-flags.constant.ts b/packages/twenty-cli/src/program/constants/global-flags.constant.ts
new file mode 100644
index 00000000000..9103be6fa0d
--- /dev/null
+++ b/packages/twenty-cli/src/program/constants/global-flags.constant.ts
@@ -0,0 +1,8 @@
+export const GLOBAL_FLAGS = {
+ JSON: '--json',
+ FORMAT: '--format <format>',
+ REMOTE: '-r, --remote <name>',
+ NO_INPUT: '--no-input',
+ HELP: '-h, --help',
+ VERSION: '-v, --version',
+} as const;
diff --git a/packages/twenty-cli/src/program/constants/root-command-name.constant.ts b/packages/twenty-cli/src/program/constants/root-command-name.constant.ts
new file mode 100644
index 00000000000..20997f2e97e
--- /dev/null
+++ b/packages/twenty-cli/src/program/constants/root-command-name.constant.ts
@@ -0,0 +1 @@
+export const ROOT_COMMAND_NAME = 'twenty';
diff --git a/packages/twenty-cli/src/program/create-commander-output-capture.ts b/packages/twenty-cli/src/program/create-commander-output-capture.ts
new file mode 100644
index 00000000000..3d3816560a4
--- /dev/null
+++ b/packages/twenty-cli/src/program/create-commander-output-capture.ts
@@ -0,0 +1,19 @@
+import { type OutputConfiguration } from 'commander';
+
+export const createCommanderOutputCapture = () => {
+ const captured = { standardOutput: '', standardError: '' };
+
+ const configuration: OutputConfiguration = {
+ writeOut: (text) => {
+ captured.standardOutput += text;
+ },
+ writeErr: (text) => {
+ captured.standardError += text;
+ },
+ outputError: (text) => {
+ captured.standardError += text;
+ },
+ };
+
+ return { captured, configuration };
+};
diff --git a/packages/twenty-cli/src/program/create-program.ts b/packages/twenty-cli/src/program/create-program.ts
new file mode 100644
index 00000000000..458551e0b97
--- /dev/null
+++ b/packages/twenty-cli/src/program/create-program.ts
@@ -0,0 +1,53 @@
+import { Command, Option, type OutputConfiguration } from 'commander';
+
+import { COMMAND_CATALOG } from '@/catalog/command-catalog';
+import { COMMAND_TOPICS } from '@/catalog/command-topics';
+import { HELP_GROUP } from '@/catalog/constants/help-group.constant';
+import { CLI_VERSION } from '@/constants/cli-version.constant';
+import { OUTPUT_MODES } from '@/output/constants/output-modes.constant';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { GLOBAL_FLAGS } from '@/program/constants/global-flags.constant';
+import { ROOT_COMMAND_NAME } from '@/program/constants/root-command-name.constant';
+import { registerCommand } from '@/program/register-command';
+import { registerTopic } from '@/program/register-topic';
+import { throwParseErrorOnExit } from '@/program/throw-parse-error-on-exit';
+
+export const createProgram = ({
+ outputMode,
+ outputConfiguration,
+}: {
+ outputMode: OutputMode;
+ outputConfiguration: OutputConfiguration;
+}) => {
+ const program = new Command(ROOT_COMMAND_NAME)
+ .description('The Twenty command line')
+ .version(CLI_VERSION, GLOBAL_FLAGS.VERSION, 'Print the version')
+ .addOption(
+ new Option(
+ GLOBAL_FLAGS.JSON,
+ 'Print one JSON document on stdout',
+ ).conflicts('format'),
+ )
+ .addOption(
+ new Option(GLOBAL_FLAGS.FORMAT, 'Output format').choices(OUTPUT_MODES),
+ )
+ .option(GLOBAL_FLAGS.REMOTE, 'Saved remote to use for this command')
+ .option(GLOBAL_FLAGS.NO_INPUT, 'Never prompt or open a browser')
+ .helpOption(GLOBAL_FLAGS.HELP, 'Show help')
+ .commandsGroup(HELP_GROUP.TOOLS)
+ .helpCommand('help [command]', 'Show help for a command')
+ .configureHelp({ showGlobalOptions: true })
+ .configureOutput(outputConfiguration);
+
+ throwParseErrorOnExit(program, ROOT_COMMAND_NAME);
+
+ for (const topic of COMMAND_TOPICS) {
+ registerTopic({ program, topic });
+ }
+
+ for (const definition of COMMAND_CATALOG) {
+ registerCommand({ program, definition, outputMode });
+ }
+
+ return program;
+};
diff --git a/packages/twenty-cli/src/program/find-command-by-path.ts b/packages/twenty-cli/src/program/find-command-by-path.ts
new file mode 100644
index 00000000000..4fae1190dc1
--- /dev/null
+++ b/packages/twenty-cli/src/program/find-command-by-path.ts
@@ -0,0 +1,19 @@
+import { type Command } from 'commander';
+import { isDefined } from 'twenty-shared/utils';
+
+export const findCommandByPath = (program: Command, path: string[]) =>
+ path.reduce<Command | undefined>(
+ (parent, commandName) =>
+ parent?.commands.find((command) => command.name() === commandName),
+ program,
+ );
+
+export const getCommandByPath = (program: Command, path: string[]) => {
+ const command = findCommandByPath(program, path);
+
+ if (!isDefined(command)) {
+ throw new Error(`Topic "${path.join(' ')}" is not registered.`);
+ }
+
+ return command;
+};
diff --git a/packages/twenty-cli/src/program/handle-parse-error.ts b/packages/twenty-cli/src/program/handle-parse-error.ts
new file mode 100644
index 00000000000..8fbc0427ee8
--- /dev/null
+++ b/packages/twenty-cli/src/program/handle-parse-error.ts
@@ -0,0 +1,103 @@
+import { type CommanderError } from 'commander';
+import { isNonEmptyString } from '@sniptt/guards';
+import { capitalize, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { VERSION_COMMAND_DEFINITION } from '@/commands/version/version.command-definition';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { createOutput } from '@/output/create-output';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { type CommandParseError } from '@/program/command-parse-error';
+import { ROOT_COMMAND_NAME } from '@/program/constants/root-command-name.constant';
+import { runCommand } from '@/program/run-command';
+
+const HELP_COMMAND_NAME = 'help';
+
+const formatCommanderMessage = (message: string) => {
+ const flattenedMessage = message
+ .replace(/^error: /, '')
+ .replace(/\s*\n\s*/g, ' ')
+ .trim();
+
+ return capitalize(flattenedMessage);
+};
+
+const getFullCommandName = (commandName: string) =>
+ commandName === ROOT_COMMAND_NAME
+ ? ROOT_COMMAND_NAME
+ : `${ROOT_COMMAND_NAME} ${commandName}`;
+
+const createUsageError = ({
+ message,
+ commandName,
+}: {
+ message: string;
+ commandName: string;
+}) =>
+ new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message,
+ hint: `See: ${getFullCommandName(commandName)} --help`,
+ });
+
+const isHelpDisplay = (commanderError: CommanderError, operands: string[]) =>
+ commanderError.code === 'commander.helpDisplayed' ||
+ (commanderError.code === 'commander.help' &&
+ (commanderError.exitCode === 0 || !isNonEmptyArray(operands)));
+
+const getUnknownHelpTarget = (operands: string[]) =>
+ (operands[0] === HELP_COMMAND_NAME ? operands.slice(1) : operands).join(' ');
+
+export const handleParseError = async ({
+ error,
+ outputMode,
+ capturedOutput,
+}: {
+ error: CommandParseError;
+ outputMode: OutputMode;
+ capturedOutput: { standardOutput: string; standardError: string };
+}) => {
+ const { commanderError, commandName, operands } = error;
+
+ if (commanderError.code === 'commander.version') {
+ await runCommand({
+ definition: VERSION_COMMAND_DEFINITION,
+ outputMode,
+ commandArguments: [],
+ options: {},
+ });
+
+ return;
+ }
+
+ const output = createOutput({ mode: outputMode, command: commandName });
+
+ if (isHelpDisplay(commanderError, operands)) {
+ const help = isNonEmptyString(capturedOutput.standardOutput)
+ ? capturedOutput.standardOutput
+ : capturedOutput.standardError;
+
+ output.succeed({ data: { help }, human: help });
+
+ return;
+ }
+
+ if (commanderError.code === 'commander.help') {
+ output.fail(
+ createUsageError({
+ message: `Unknown command '${getUnknownHelpTarget(operands)}'`,
+ commandName,
+ }),
+ );
+
+ return;
+ }
+
+ output.fail(
+ createUsageError({
+ message: formatCommanderMessage(commanderError.message),
+ commandName,
+ }),
+ );
+};
diff --git a/packages/twenty-cli/src/program/is-interaction-allowed.ts b/packages/twenty-cli/src/program/is-interaction-allowed.ts
new file mode 100644
index 00000000000..40801635d61
--- /dev/null
+++ b/packages/twenty-cli/src/program/is-interaction-allowed.ts
@@ -0,0 +1,26 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type OutputMode } from '@/output/types/output-mode.type';
+
+const FALSE_VALUES = new Set(['0', 'false']);
+
+const isContinuousIntegration = () => {
+ const continuousIntegration = process.env.CI;
+
+ return (
+ isNonEmptyString(continuousIntegration) &&
+ !FALSE_VALUES.has(continuousIntegration.toLowerCase())
+ );
+};
+
+export const isInteractionAllowed = ({
+ options,
+ outputMode,
+}: {
+ options: Record<string, unknown>;
+ outputMode: OutputMode;
+}) =>
+ options.input !== false &&
+ outputMode === 'human' &&
+ process.stdin.isTTY === true &&
+ !isContinuousIntegration();
diff --git a/packages/twenty-cli/src/program/register-command.ts b/packages/twenty-cli/src/program/register-command.ts
new file mode 100644
index 00000000000..638c26e6a69
--- /dev/null
+++ b/packages/twenty-cli/src/program/register-command.ts
@@ -0,0 +1,82 @@
+import { Option, type Command } from 'commander';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { getCommandName } from '@/catalog/get-command-name';
+import { type CommandDefinition } from '@/catalog/types/command-definition.type';
+import { type CommandOptionDefinition } from '@/catalog/types/command-option-definition.type';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { getCommandByPath } from '@/program/find-command-by-path';
+import { runCommand } from '@/program/run-command';
+import { throwParseErrorOnExit } from '@/program/throw-parse-error-on-exit';
+
+const createOption = ({
+ flags,
+ description,
+ choices,
+ required,
+ hidden,
+}: CommandOptionDefinition) => {
+ const option = new Option(flags, description);
+
+ if (hidden === true) {
+ option.hideHelp();
+ }
+
+ if (isDefined(choices)) {
+ option.choices(choices);
+ }
+
+ if (required === true) {
+ option.makeOptionMandatory();
+ }
+
+ return option;
+};
+
+const formatExamples = (examples: string[]) =>
+ `\nExamples:\n${examples.map((example) => ` ${example}`).join('\n')}\n`;
+
+export const registerCommand = ({
+ program,
+ definition,
+ outputMode,
+}: {
+ program: Command;
+ definition: CommandDefinition;
+ outputMode: OutputMode;
+}) => {
+ const parent = getCommandByPath(program, definition.path.slice(0, -1));
+ const command = parent
+ .command(definition.path[definition.path.length - 1])
+ .description(definition.description);
+
+ if (isDefined(definition.helpGroup)) {
+ command.helpGroup(definition.helpGroup);
+ }
+
+ for (const argument of definition.arguments ?? []) {
+ command.argument(
+ argument.required ? `<${argument.name}>` : `[${argument.name}]`,
+ argument.description,
+ );
+ }
+
+ for (const optionDefinition of definition.options ?? []) {
+ command.addOption(createOption(optionDefinition));
+ }
+
+ if (isNonEmptyArray(definition.examples)) {
+ command.addHelpText('after', formatExamples(definition.examples));
+ }
+
+ throwParseErrorOnExit(command, getCommandName(definition));
+
+ command.action(() =>
+ runCommand({
+ definition,
+ outputMode,
+ commandArguments: command.processedArgs,
+ options: command.optsWithGlobals(),
+ }),
+ );
+};
diff --git a/packages/twenty-cli/src/program/register-topic.ts b/packages/twenty-cli/src/program/register-topic.ts
new file mode 100644
index 00000000000..c97fa82de01
--- /dev/null
+++ b/packages/twenty-cli/src/program/register-topic.ts
@@ -0,0 +1,25 @@
+import { type Command } from 'commander';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type CommandTopicDefinition } from '@/catalog/types/command-topic-definition.type';
+import { getCommandByPath } from '@/program/find-command-by-path';
+import { throwParseErrorOnExit } from '@/program/throw-parse-error-on-exit';
+
+export const registerTopic = ({
+ program,
+ topic,
+}: {
+ program: Command;
+ topic: CommandTopicDefinition;
+}) => {
+ const parent = getCommandByPath(program, topic.path.slice(0, -1));
+ const topicCommand = parent
+ .command(topic.path[topic.path.length - 1])
+ .description(topic.description);
+
+ if (isDefined(topic.helpGroup)) {
+ topicCommand.helpGroup(topic.helpGroup);
+ }
+
+ throwParseErrorOnExit(topicCommand, topic.path.join(' '));
+};
diff --git a/packages/twenty-cli/src/program/resolve-command-target.ts b/packages/twenty-cli/src/program/resolve-command-target.ts
new file mode 100644
index 00000000000..cbf1b5663e1
--- /dev/null
+++ b/packages/twenty-cli/src/program/resolve-command-target.ts
@@ -0,0 +1,90 @@
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { readStringOption } from '@/catalog/read-command-values';
+import { getConfigPath } from '@/config/get-config-path';
+import { CliError } from '@/output/cli-error';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { type Output } from '@/output/types/output.type';
+import { isInteractionAllowed } from '@/program/is-interaction-allowed';
+import { resolveTarget } from '@/target/resolve-target';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+export const resolveCommandTarget = async ({
+ options,
+ outputMode,
+ output,
+ signal,
+}: {
+ options: Record<string, unknown>;
+ outputMode: OutputMode;
+ output: Output;
+ signal: AbortSignal;
+}) => {
+ const configPath = getConfigPath();
+ const canInteract = isInteractionAllowed({ options, outputMode });
+ let attemptedSignIn = false;
+
+ const onAuthenticationRequired = async ({
+ target,
+ error,
+ }: {
+ target: ResolvedTarget;
+ error: unknown;
+ }) => {
+ const refreshFailure =
+ error instanceof CliError ? error.details?.refresh : undefined;
+
+ if (
+ !canInteract ||
+ attemptedSignIn ||
+ signal.aborted ||
+ target.source !== 'remote' ||
+ target.credentialKind !== 'oauth' ||
+ !isDefined(target.remoteName) ||
+ !(error instanceof CliError) ||
+ error.code !== 'AUTH_REQUIRED' ||
+ (isPlainObject(refreshFailure) &&
+ refreshFailure.status !== 400 &&
+ refreshFailure.status !== 401)
+ ) {
+ throw error;
+ }
+
+ attemptedSignIn = true;
+ const { signInToRemoteAgain } =
+ await import('@/oauth/sign-in-to-remote-again');
+
+ return signInToRemoteAgain({
+ target,
+ remoteName: target.remoteName,
+ error,
+ configPath,
+ output,
+ signal,
+ });
+ };
+
+ const target = await resolveTarget({
+ environment: process.env,
+ remoteFlag: readStringOption(options, 'remote'),
+ configPath,
+ signal,
+ warn: output.warn,
+ onAuthenticationRequired,
+ });
+
+ if (!canInteract || target.credentialKind !== 'oauth' || attemptedSignIn) {
+ return target;
+ }
+
+ const { fetchSignedInIdentity } =
+ await import('@/transport/metadata/fetch-signed-in-identity');
+
+ try {
+ await fetchSignedInIdentity({ target, signal });
+
+ return target;
+ } catch (error) {
+ return onAuthenticationRequired({ target, error });
+ }
+};
diff --git a/packages/twenty-cli/src/program/run-command.ts b/packages/twenty-cli/src/program/run-command.ts
new file mode 100644
index 00000000000..d1687b101de
--- /dev/null
+++ b/packages/twenty-cli/src/program/run-command.ts
@@ -0,0 +1,92 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { getCommandName } from '@/catalog/get-command-name';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { type CommandDefinition } from '@/catalog/types/command-definition.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { createOutput } from '@/output/create-output';
+import { toCliError } from '@/output/to-cli-error';
+import { type OutputMode } from '@/output/types/output-mode.type';
+import { resolveCommandTarget } from '@/program/resolve-command-target';
+import { toPublicTarget } from '@/target/to-public-target';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+const assertOutputModeSupported = (
+ definition: CommandDefinition,
+ outputMode: OutputMode,
+) => {
+ if (!definition.outputModes.includes(outputMode)) {
+ throw new CliError({
+ code: 'USAGE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `twenty ${getCommandName(definition)} does not support ${outputMode} output.`,
+ hint: `Supported: ${definition.outputModes.join(', ')}`,
+ });
+ }
+};
+
+export const runCommand = async ({
+ definition,
+ outputMode,
+ commandArguments,
+ options,
+}: {
+ definition: CommandDefinition;
+ outputMode: OutputMode;
+ commandArguments: unknown[];
+ options: Record<string, unknown>;
+}) => {
+ const command = getCommandName(definition);
+ const output = createOutput({ mode: outputMode, command });
+ const abortController = new AbortController();
+ const abortOnInterrupt = () => abortController.abort();
+ let target: ResolvedTarget | undefined;
+
+ process.once('SIGINT', abortOnInterrupt);
+
+ try {
+ assertOutputModeSupported(definition, outputMode);
+
+ const context: CommandContext = {
+ command,
+ arguments: commandArguments,
+ options,
+ output,
+ outputMode,
+ signal: abortController.signal,
+ };
+
+ if (!definition.needsTarget) {
+ const run = await definition.load();
+
+ output.succeed(await run(context));
+
+ return;
+ }
+
+ const resolvedTarget = await resolveCommandTarget({
+ options,
+ outputMode,
+ output,
+ signal: abortController.signal,
+ });
+
+ target = resolvedTarget;
+
+ const run = await definition.load();
+
+ output.succeed(
+ await run({ ...context, target: resolvedTarget }),
+ toPublicTarget(resolvedTarget),
+ );
+ } catch (error) {
+ output.fail(
+ toCliError(error, abortController.signal),
+ isDefined(target) ? toPublicTarget(target) : undefined,
+ );
+ } finally {
+ process.off('SIGINT', abortOnInterrupt);
+ abortController.abort();
+ }
+};
diff --git a/packages/twenty-cli/src/program/throw-parse-error-on-exit.ts b/packages/twenty-cli/src/program/throw-parse-error-on-exit.ts
new file mode 100644
index 00000000000..25430fbf1b6
--- /dev/null
+++ b/packages/twenty-cli/src/program/throw-parse-error-on-exit.ts
@@ -0,0 +1,12 @@
+import { type Command } from 'commander';
+
+import { CommandParseError } from '@/program/command-parse-error';
+
+export const throwParseErrorOnExit = (command: Command, commandName: string) =>
+ command.exitOverride((commanderError) => {
+ throw new CommandParseError({
+ commanderError,
+ commandName,
+ operands: command.args,
+ });
+ });
diff --git a/packages/twenty-cli/src/run-cli.ts b/packages/twenty-cli/src/run-cli.ts
new file mode 100644
index 00000000000..75ac4ed9b9c
--- /dev/null
+++ b/packages/twenty-cli/src/run-cli.ts
@@ -0,0 +1,35 @@
+import { createOutput } from '@/output/create-output';
+import { detectOutputMode } from '@/output/detect-output-mode';
+import { toCliError } from '@/output/to-cli-error';
+import { CommandParseError } from '@/program/command-parse-error';
+import { ROOT_COMMAND_NAME } from '@/program/constants/root-command-name.constant';
+import { createCommanderOutputCapture } from '@/program/create-commander-output-capture';
+import { createProgram } from '@/program/create-program';
+import { handleParseError } from '@/program/handle-parse-error';
+
+export const runCli = async (args: string[]) => {
+ const outputMode = detectOutputMode(args);
+ const commanderOutput = createCommanderOutputCapture();
+ const program = createProgram({
+ outputMode,
+ outputConfiguration: commanderOutput.configuration,
+ });
+
+ try {
+ await program.parseAsync(args, { from: 'user' });
+ } catch (error) {
+ if (error instanceof CommandParseError) {
+ await handleParseError({
+ error,
+ outputMode,
+ capturedOutput: commanderOutput.captured,
+ });
+
+ return;
+ }
+
+ createOutput({ mode: outputMode, command: ROOT_COMMAND_NAME }).fail(
+ toCliError(error),
+ );
+ }
+};
diff --git a/packages/twenty-cli/src/target/__tests__/resolve-target.spec.ts b/packages/twenty-cli/src/target/__tests__/resolve-target.spec.ts
new file mode 100644
index 00000000000..c4e19558320
--- /dev/null
+++ b/packages/twenty-cli/src/target/__tests__/resolve-target.spec.ts
@@ -0,0 +1,166 @@
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { type CliWarning } from '@/output/types/cli-warning.type';
+import { resolveTarget } from '@/target/resolve-target';
+
+const CONFIG = {
+ version: 1,
+ defaultRemote: 'prod',
+ remotes: {
+ prod: { apiUrl: 'https://acme.twenty.com/', apiKey: 'prod-key' },
+ staging: {
+ apiUrl: 'https://staging.twenty.com',
+ apiKey: 'staging-key',
+ twentyCLIAccessToken: 'staging-access-token',
+ },
+ signedOut: { apiUrl: 'https://old.twenty.com' },
+ },
+};
+
+describe('resolveTarget', () => {
+ let configPath: string;
+ let warnings: CliWarning[];
+
+ const resolve = (
+ environment: NodeJS.ProcessEnv,
+ remoteFlag?: string,
+ path = configPath,
+ ) =>
+ resolveTarget({
+ environment,
+ remoteFlag,
+ configPath: path,
+ signal: new AbortController().signal,
+ warn: (warning) => warnings.push(warning),
+ });
+
+ beforeEach(async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'twenty-cli-target-'));
+
+ configPath = join(directory, 'config.json');
+ warnings = [];
+ await writeFile(configPath, JSON.stringify(CONFIG));
+ });
+
+ it('uses the environment pair without reading the config', async () => {
+ await writeFile(configPath, '{ broken');
+
+ await expect(
+ resolve({
+ TWENTY_API_URL: 'https://Acme.Twenty.com/crm/',
+ TWENTY_API_KEY: 'secret',
+ }),
+ ).resolves.toEqual({
+ apiUrl: 'https://acme.twenty.com/crm',
+ bearerToken: 'secret',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ });
+ });
+
+ it('falls back to the saved default remote', async () => {
+ await expect(resolve({})).resolves.toEqual({
+ apiUrl: 'https://acme.twenty.com',
+ bearerToken: 'prod-key',
+ credentialKind: 'apiKey',
+ source: 'remote',
+ remoteName: 'prod',
+ });
+ });
+
+ it('selects a remote with TWENTY_REMOTE', async () => {
+ await expect(resolve({ TWENTY_REMOTE: 'staging' })).resolves.toMatchObject({
+ remoteName: 'staging',
+ });
+ });
+
+ it('prefers a saved OAuth access token over an API key, like twenty-sdk', async () => {
+ await expect(resolve({}, 'staging')).resolves.toMatchObject({
+ bearerToken: 'staging-access-token',
+ credentialKind: 'oauth',
+ });
+ });
+
+ it('lets --remote win over the environment and says so', async () => {
+ await expect(
+ resolve(
+ { TWENTY_API_URL: 'https://other.example.com', TWENTY_API_KEY: 'k' },
+ 'staging',
+ ),
+ ).resolves.toMatchObject({ remoteName: 'staging' });
+ expect(warnings).toEqual([
+ {
+ code: 'ENVIRONMENT_TARGET_IGNORED',
+ message:
+ 'Using remote staging. Ignoring TWENTY_API_URL and TWENTY_API_KEY.',
+ },
+ ]);
+ });
+
+ it.each([
+ [{}, undefined, 'TARGET_REQUIRED', 2, 'missing.json'],
+ [
+ { TWENTY_API_URL: ' ', TWENTY_API_KEY: '' },
+ undefined,
+ 'TARGET_REQUIRED',
+ 2,
+ 'missing.json',
+ ],
+ [
+ { TWENTY_API_URL: 'https://acme.twenty.com' },
+ undefined,
+ 'INCOMPLETE_TARGET',
+ 2,
+ undefined,
+ ],
+ [
+ { TWENTY_REMOTE: 'prod', TWENTY_API_KEY: 'k' },
+ undefined,
+ 'CONFLICTING_TARGET',
+ 2,
+ undefined,
+ ],
+ [{}, 'nope', 'UNKNOWN_REMOTE', 2, undefined],
+ [{}, 'signedOut', 'AUTH_REQUIRED', 3, undefined],
+ [
+ { TWENTY_API_URL: 'acme.twenty.com', TWENTY_API_KEY: 'k' },
+ undefined,
+ 'INVALID_API_URL',
+ 2,
+ undefined,
+ ],
+ [
+ {
+ TWENTY_API_URL: 'https://user:[email protected]',
+ TWENTY_API_KEY: 'k',
+ },
+ undefined,
+ 'INVALID_API_URL',
+ 2,
+ undefined,
+ ],
+ [
+ { TWENTY_API_URL: 'https://acme.twenty.com?x=1', TWENTY_API_KEY: 'k' },
+ undefined,
+ 'INVALID_API_URL',
+ 2,
+ undefined,
+ ],
+ ] as const)(
+ 'fails for %j with --remote %s as %s',
+ async (environment, remoteFlag, code, exitCode, configFileName) => {
+ const path = isDefined(configFileName)
+ ? join(configPath, '..', configFileName)
+ : configPath;
+
+ await expect(
+ resolve(environment, remoteFlag, path),
+ ).rejects.toMatchObject({ code, exitCode });
+ },
+ );
+});
diff --git a/packages/twenty-cli/src/target/constants/api-url-protocols.constant.ts b/packages/twenty-cli/src/target/constants/api-url-protocols.constant.ts
new file mode 100644
index 00000000000..d77dd574c9e
--- /dev/null
+++ b/packages/twenty-cli/src/target/constants/api-url-protocols.constant.ts
@@ -0,0 +1 @@
+export const API_URL_PROTOCOLS = ['http:', 'https:'];
diff --git a/packages/twenty-cli/src/target/constants/target-environment-variable.constant.ts b/packages/twenty-cli/src/target/constants/target-environment-variable.constant.ts
new file mode 100644
index 00000000000..228ae7b1786
--- /dev/null
+++ b/packages/twenty-cli/src/target/constants/target-environment-variable.constant.ts
@@ -0,0 +1,5 @@
+export const TARGET_ENVIRONMENT_VARIABLE = {
+ API_URL: 'TWENTY_API_URL',
+ API_KEY: 'TWENTY_API_KEY',
+ REMOTE: 'TWENTY_REMOTE',
+} as const;
diff --git a/packages/twenty-cli/src/target/find-remote.ts b/packages/twenty-cli/src/target/find-remote.ts
new file mode 100644
index 00000000000..d335e51fea6
--- /dev/null
+++ b/packages/twenty-cli/src/target/find-remote.ts
@@ -0,0 +1,17 @@
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const findRemote = (config: ConfigFile, remoteName: string) => {
+ if (!Object.hasOwn(config.remotes, remoteName)) {
+ throw new CliError({
+ code: 'UNKNOWN_REMOTE',
+ exitCode: EXIT_CODE.USAGE,
+ message: `No remote is named ${remoteName}.`,
+ hint: 'See saved remotes: twenty remote list',
+ details: { remote: remoteName },
+ });
+ }
+
+ return config.remotes[remoteName];
+};
diff --git a/packages/twenty-cli/src/target/format-api-url.ts b/packages/twenty-cli/src/target/format-api-url.ts
new file mode 100644
index 00000000000..c2d271af4ae
--- /dev/null
+++ b/packages/twenty-cli/src/target/format-api-url.ts
@@ -0,0 +1,2 @@
+export const formatApiUrl = (url: URL) =>
+ `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
diff --git a/packages/twenty-cli/src/target/get-authentication-hint.ts b/packages/twenty-cli/src/target/get-authentication-hint.ts
new file mode 100644
index 00000000000..c26534e7a8b
--- /dev/null
+++ b/packages/twenty-cli/src/target/get-authentication-hint.ts
@@ -0,0 +1,15 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+export const getAuthenticationHint = (target: ResolvedTarget) => {
+ if (!isDefined(target.remoteName)) {
+ return `Check ${TARGET_ENVIRONMENT_VARIABLE.API_KEY}.`;
+ }
+
+ const withTokenFlag =
+ target.credentialKind === 'apiKey' ? ' --with-token' : '';
+
+ return `Sign in again: twenty auth login --remote ${target.remoteName}${withTokenFlag}`;
+};
diff --git a/packages/twenty-cli/src/target/has-configured-target.ts b/packages/twenty-cli/src/target/has-configured-target.ts
new file mode 100644
index 00000000000..c5916ae0cf3
--- /dev/null
+++ b/packages/twenty-cli/src/target/has-configured-target.ts
@@ -0,0 +1,20 @@
+import { getConfigPath } from '@/config/get-config-path';
+import { readConfig } from '@/config/read-config';
+import { selectTarget } from '@/target/select-target';
+
+export const hasConfiguredTarget = ({
+ environment,
+ remoteFlag,
+}: {
+ environment: NodeJS.ProcessEnv;
+ remoteFlag: string | undefined;
+}) =>
+ selectTarget({
+ environment,
+ remoteFlag,
+ loadConfig: () => readConfig(getConfigPath()),
+ warn: () => undefined,
+ }).then(
+ () => true,
+ () => false,
+ );
diff --git a/packages/twenty-cli/src/target/parse-api-url.ts b/packages/twenty-cli/src/target/parse-api-url.ts
new file mode 100644
index 00000000000..35032734ac8
--- /dev/null
+++ b/packages/twenty-cli/src/target/parse-api-url.ts
@@ -0,0 +1,35 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { API_URL_PROTOCOLS } from '@/target/constants/api-url-protocols.constant';
+import { formatApiUrl } from '@/target/format-api-url';
+
+export const parseApiUrl = ({
+ rawUrl,
+ sourceName,
+}: {
+ rawUrl: string;
+ sourceName: string;
+}) => {
+ const url = URL.parse(rawUrl.trim());
+
+ const isValid =
+ isDefined(url) &&
+ API_URL_PROTOCOLS.includes(url.protocol) &&
+ url.username === '' &&
+ url.password === '' &&
+ url.search === '' &&
+ url.hash === '';
+
+ if (!isValid) {
+ throw new CliError({
+ code: 'INVALID_API_URL',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${sourceName} must be an http or https URL without credentials, query or fragment.`,
+ hint: 'For example: https://acme.twenty.com',
+ });
+ }
+
+ return formatApiUrl(url);
+};
diff --git a/packages/twenty-cli/src/target/resolve-target.ts b/packages/twenty-cli/src/target/resolve-target.ts
new file mode 100644
index 00000000000..147fae2b244
--- /dev/null
+++ b/packages/twenty-cli/src/target/resolve-target.ts
@@ -0,0 +1,133 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { readConfig } from '@/config/read-config';
+import { type RemoteEntry } from '@/config/types/config-file.type';
+import { isAccessTokenExpiring } from '@/oauth/is-access-token-expiring';
+import { refreshOAuthSession } from '@/oauth/refresh-oauth-session';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { type CliWarning } from '@/output/types/cli-warning.type';
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { parseApiUrl } from '@/target/parse-api-url';
+import { selectTarget } from '@/target/select-target';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+type AuthenticationRecovery = (context: {
+ target: ResolvedTarget;
+ error: unknown;
+}) => Promise<ResolvedTarget>;
+
+const toRemoteTarget = async ({
+ remoteName,
+ remote,
+ configPath,
+ signal,
+ onAuthenticationRequired,
+}: {
+ remoteName: string;
+ remote: RemoteEntry;
+ configPath: string;
+ signal: AbortSignal;
+ onAuthenticationRequired?: AuthenticationRecovery;
+}): Promise<ResolvedTarget> => {
+ const accessToken = remote.twentyCLIAccessToken;
+ const apiUrl = parseApiUrl({
+ rawUrl: remote.apiUrl,
+ sourceName: `The URL of remote ${remoteName}`,
+ });
+
+ if (isNonEmptyString(accessToken)) {
+ const target: ResolvedTarget = {
+ apiUrl,
+ bearerToken: accessToken,
+ credentialKind: 'oauth',
+ source: 'remote',
+ remoteName,
+ };
+
+ if (!isAccessTokenExpiring(accessToken)) {
+ return target;
+ }
+
+ try {
+ return {
+ ...target,
+ bearerToken: await refreshOAuthSession({
+ configPath,
+ remoteName,
+ apiUrl,
+ signal,
+ }),
+ };
+ } catch (error) {
+ if (onAuthenticationRequired) {
+ return onAuthenticationRequired({ target, error });
+ }
+
+ throw error;
+ }
+ }
+
+ const bearerToken = remote.apiKey;
+
+ if (!isNonEmptyString(bearerToken)) {
+ throw new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `Remote ${remoteName} has no saved credentials.`,
+ hint: `Sign in: twenty auth login --remote ${remoteName}`,
+ details: { remote: remoteName },
+ });
+ }
+
+ return {
+ apiUrl,
+ bearerToken,
+ credentialKind: 'apiKey',
+ source: 'remote',
+ remoteName,
+ };
+};
+
+export const resolveTarget = async ({
+ environment,
+ remoteFlag,
+ configPath,
+ signal,
+ warn,
+ onAuthenticationRequired,
+}: {
+ environment: NodeJS.ProcessEnv;
+ remoteFlag: string | undefined;
+ configPath: string;
+ signal: AbortSignal;
+ warn: (warning: CliWarning) => void;
+ onAuthenticationRequired?: AuthenticationRecovery;
+}): Promise<ResolvedTarget> => {
+ const selection = await selectTarget({
+ environment,
+ remoteFlag,
+ loadConfig: () => readConfig(configPath),
+ warn,
+ });
+
+ if (selection.source === 'remote') {
+ return toRemoteTarget({
+ remoteName: selection.remoteName,
+ remote: selection.remote,
+ configPath,
+ signal,
+ onAuthenticationRequired,
+ });
+ }
+
+ return {
+ apiUrl: parseApiUrl({
+ rawUrl: selection.apiUrl,
+ sourceName: TARGET_ENVIRONMENT_VARIABLE.API_URL,
+ }),
+ bearerToken: selection.apiKey,
+ credentialKind: 'apiKey',
+ source: 'environment',
+ };
+};
diff --git a/packages/twenty-cli/src/target/select-target.ts b/packages/twenty-cli/src/target/select-target.ts
new file mode 100644
index 00000000000..7344f04bedf
--- /dev/null
+++ b/packages/twenty-cli/src/target/select-target.ts
@@ -0,0 +1,113 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { type ConfigFile } from '@/config/types/config-file.type';
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatList } from '@/output/format-list';
+import { type CliWarning } from '@/output/types/cli-warning.type';
+import { TARGET_ENVIRONMENT_VARIABLE } from '@/target/constants/target-environment-variable.constant';
+import { findRemote } from '@/target/find-remote';
+import { type TargetSelection } from '@/target/types/target-selection.type';
+
+const readEnvironmentValue = (
+ environment: NodeJS.ProcessEnv,
+ variableName: string,
+) => {
+ const value = environment[variableName]?.trim();
+
+ return isNonEmptyString(value) ? value : undefined;
+};
+
+const selectRemote = (
+ config: ConfigFile,
+ remoteName: string,
+): TargetSelection => ({
+ source: 'remote',
+ remoteName,
+ remote: findRemote(config, remoteName),
+});
+
+export const selectTarget = async ({
+ environment,
+ remoteFlag,
+ loadConfig,
+ warn,
+}: {
+ environment: NodeJS.ProcessEnv;
+ remoteFlag: string | undefined;
+ loadConfig: () => Promise<ConfigFile>;
+ warn: (warning: CliWarning) => void;
+}): Promise<TargetSelection> => {
+ const environmentRemote = readEnvironmentValue(
+ environment,
+ TARGET_ENVIRONMENT_VARIABLE.REMOTE,
+ );
+ const apiUrl = readEnvironmentValue(
+ environment,
+ TARGET_ENVIRONMENT_VARIABLE.API_URL,
+ );
+ const apiKey = readEnvironmentValue(
+ environment,
+ TARGET_ENVIRONMENT_VARIABLE.API_KEY,
+ );
+
+ if (isDefined(remoteFlag)) {
+ const ignoredVariables = Object.values(TARGET_ENVIRONMENT_VARIABLE).filter(
+ (variableName) =>
+ isDefined(readEnvironmentValue(environment, variableName)),
+ );
+
+ if (isNonEmptyArray(ignoredVariables)) {
+ warn({
+ code: 'ENVIRONMENT_TARGET_IGNORED',
+ message: `Using remote ${remoteFlag}. Ignoring ${formatList(ignoredVariables)}.`,
+ });
+ }
+
+ return selectRemote(await loadConfig(), remoteFlag);
+ }
+
+ if (isDefined(environmentRemote)) {
+ if (isDefined(apiUrl) || isDefined(apiKey)) {
+ throw new CliError({
+ code: 'CONFLICTING_TARGET',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${TARGET_ENVIRONMENT_VARIABLE.REMOTE} cannot be combined with ${TARGET_ENVIRONMENT_VARIABLE.API_URL} or ${TARGET_ENVIRONMENT_VARIABLE.API_KEY}.`,
+ hint: 'Unset one of them, or choose with --remote.',
+ });
+ }
+
+ return selectRemote(await loadConfig(), environmentRemote);
+ }
+
+ if (isDefined(apiUrl) !== isDefined(apiKey)) {
+ const missingVariable = isDefined(apiUrl)
+ ? TARGET_ENVIRONMENT_VARIABLE.API_KEY
+ : TARGET_ENVIRONMENT_VARIABLE.API_URL;
+
+ throw new CliError({
+ code: 'INCOMPLETE_TARGET',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${missingVariable} is not set.`,
+ hint: `Set both ${TARGET_ENVIRONMENT_VARIABLE.API_URL} and ${TARGET_ENVIRONMENT_VARIABLE.API_KEY}, or neither.`,
+ });
+ }
+
+ if (isDefined(apiUrl) && isDefined(apiKey)) {
+ return { source: 'environment', apiUrl, apiKey };
+ }
+
+ const config = await loadConfig();
+
+ if (isDefined(config.defaultRemote)) {
+ return selectRemote(config, config.defaultRemote);
+ }
+
+ throw new CliError({
+ code: 'TARGET_REQUIRED',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'No workspace selected.',
+ hint: `Sign in with: twenty auth login --with-token --url <url> --name <name>. Or set ${TARGET_ENVIRONMENT_VARIABLE.API_URL} and ${TARGET_ENVIRONMENT_VARIABLE.API_KEY}.`,
+ });
+};
diff --git a/packages/twenty-cli/src/target/to-public-target.ts b/packages/twenty-cli/src/target/to-public-target.ts
new file mode 100644
index 00000000000..9a7beb30812
--- /dev/null
+++ b/packages/twenty-cli/src/target/to-public-target.ts
@@ -0,0 +1,14 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type PublicTarget } from '@/target/types/public-target.type';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+
+export const toPublicTarget = ({
+ apiUrl,
+ source,
+ remoteName,
+}: ResolvedTarget): PublicTarget => ({
+ ...(isDefined(remoteName) ? { remote: remoteName } : {}),
+ apiUrl,
+ source,
+});
diff --git a/packages/twenty-cli/src/target/types/credential-kind.type.ts b/packages/twenty-cli/src/target/types/credential-kind.type.ts
new file mode 100644
index 00000000000..fa4ed8cdffa
--- /dev/null
+++ b/packages/twenty-cli/src/target/types/credential-kind.type.ts
@@ -0,0 +1 @@
+export type CredentialKind = 'apiKey' | 'oauth';
diff --git a/packages/twenty-cli/src/target/types/public-target.type.ts b/packages/twenty-cli/src/target/types/public-target.type.ts
new file mode 100644
index 00000000000..a4d69561acb
--- /dev/null
+++ b/packages/twenty-cli/src/target/types/public-target.type.ts
@@ -0,0 +1,7 @@
+import { type TargetSource } from '@/target/types/target-source.type';
+
+export type PublicTarget = {
+ remote?: string;
+ apiUrl: string;
+ source: TargetSource;
+};
diff --git a/packages/twenty-cli/src/target/types/resolved-target.type.ts b/packages/twenty-cli/src/target/types/resolved-target.type.ts
new file mode 100644
index 00000000000..7856df37d8e
--- /dev/null
+++ b/packages/twenty-cli/src/target/types/resolved-target.type.ts
@@ -0,0 +1,10 @@
+import { type CredentialKind } from '@/target/types/credential-kind.type';
+import { type TargetSource } from '@/target/types/target-source.type';
+
+export type ResolvedTarget = {
+ apiUrl: string;
+ bearerToken: string;
+ credentialKind: CredentialKind;
+ source: TargetSource;
+ remoteName?: string;
+};
diff --git a/packages/twenty-cli/src/target/types/target-selection.type.ts b/packages/twenty-cli/src/target/types/target-selection.type.ts
new file mode 100644
index 00000000000..304da31e1a8
--- /dev/null
+++ b/packages/twenty-cli/src/target/types/target-selection.type.ts
@@ -0,0 +1,5 @@
+import { type RemoteEntry } from '@/config/types/config-file.type';
+
+export type TargetSelection =
+ | { source: 'environment'; apiUrl: string; apiKey: string }
+ | { source: 'remote'; remoteName: string; remote: RemoteEntry };
diff --git a/packages/twenty-cli/src/target/types/target-source.type.ts b/packages/twenty-cli/src/target/types/target-source.type.ts
new file mode 100644
index 00000000000..c38adcef49a
--- /dev/null
+++ b/packages/twenty-cli/src/target/types/target-source.type.ts
@@ -0,0 +1 @@
+export type TargetSource = 'environment' | 'remote';
diff --git a/packages/twenty-cli/src/transport/__tests__/fetch-request-timeout.spec.ts b/packages/twenty-cli/src/transport/__tests__/fetch-request-timeout.spec.ts
new file mode 100644
index 00000000000..bfeebb95843
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/fetch-request-timeout.spec.ts
@@ -0,0 +1,89 @@
+import { Agent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { createBoundedFetch } from '@/transport/create-target-fetch';
+import { subscribeGraphql } from '@/transport/graphql/subscribe-graphql';
+
+afterEach(() => vi.unstubAllEnvs());
+
+it('allows an execution to outlast the HTTP dispatcher header deadline', async () => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ const server = await startTestServer((_request, response) => {
+ setTimeout(() => sendJson(response, 200, { completed: true }), 2_000);
+ });
+ const originalDispatcher = getGlobalDispatcher();
+ const shortDeadlineDispatcher = new Agent({ headersTimeout: 1 });
+ setGlobalDispatcher(shortDeadlineDispatcher);
+
+ try {
+ await expect(fetch(server.url)).rejects.toMatchObject({
+ cause: { code: 'UND_ERR_HEADERS_TIMEOUT' },
+ });
+ const request = createBoundedFetch({
+ apiUrl: server.url,
+ signal: new AbortController().signal,
+ timeoutMilliseconds: 5_000,
+ });
+
+ const response = await request(server.url);
+
+ expect(await response.json()).toEqual({ completed: true });
+ } finally {
+ setGlobalDispatcher(originalDispatcher);
+ await shortDeadlineDispatcher.destroy();
+ await server.close();
+ }
+}, 10_000);
+
+it('keeps an idle subscription open past the HTTP dispatcher body deadline', async () => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.write(':\n\n');
+ setTimeout(() => response.end('event: complete\n\n'), 2_000);
+ });
+ const originalDispatcher = getGlobalDispatcher();
+ const shortDeadlineDispatcher = new Agent({ bodyTimeout: 1 });
+ setGlobalDispatcher(shortDeadlineDispatcher);
+
+ try {
+ const response = await fetch(server.url);
+ await expect(response.text()).rejects.toMatchObject({
+ cause: { code: 'UND_ERR_BODY_TIMEOUT' },
+ });
+ await expect(
+ subscribeGraphql({
+ target: {
+ apiUrl: server.url,
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected: async () => {},
+ onData: async () => {},
+ }),
+ ).resolves.toBeUndefined();
+ } finally {
+ setGlobalDispatcher(originalDispatcher);
+ await shortDeadlineDispatcher.destroy();
+ await server.close();
+ }
+}, 10_000);
diff --git a/packages/twenty-cli/src/transport/__tests__/fetch-with-proxy.spec.ts b/packages/twenty-cli/src/transport/__tests__/fetch-with-proxy.spec.ts
new file mode 100644
index 00000000000..3dcc513ff2c
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/fetch-with-proxy.spec.ts
@@ -0,0 +1,243 @@
+import { createServer } from 'node:http';
+import { connect, type Socket } from 'node:net';
+
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { getListeningPort } from '@/utils/get-listening-port';
+
+const proxyRequests: { authority: string; authorization?: string }[] = [];
+const sockets = new Set<Socket>();
+const target = await startTestServer((request, response) => {
+ if (request.headers.accept === 'text/event-stream') {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.end(
+ 'event: next\ndata: {"data":{"message":"hello"}}\n\nevent: complete\n\n',
+ );
+ return;
+ }
+ sendJson(response, 200, { ok: true });
+});
+const proxy = createServer();
+
+proxy.on('connection', (socket) => {
+ sockets.add(socket);
+ socket.on('close', () => sockets.delete(socket));
+});
+proxy.on('connect', (request, socket, head) => {
+ proxyRequests.push({
+ authority: request.url ?? '',
+ authorization: request.headers['proxy-authorization'],
+ });
+
+ if (request.url === 'secure.example:443') {
+ socket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
+
+ return;
+ }
+
+ const upstream = connect(
+ Number(new URL(target.url).port),
+ '127.0.0.1',
+ () => {
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ upstream.write(head);
+ socket.pipe(upstream);
+ upstream.pipe(socket);
+ },
+ );
+
+ socket.on('close', () => upstream.destroy());
+ upstream.on('error', () => socket.destroy());
+});
+await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve));
+const proxyUrl = `http://127.0.0.1:${getListeningPort(proxy)}`;
+
+const fetchThroughTransport = async (url: string) => {
+ const { createBoundedFetch } =
+ await import('@/transport/create-target-fetch');
+
+ return createBoundedFetch({
+ apiUrl: url,
+ bearerToken: 'workspace-secret',
+ signal: new AbortController().signal,
+ })(url);
+};
+
+describe('environment proxies', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'NO_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ 'no_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ proxyRequests.length = 0;
+ target.requests.length = 0;
+ });
+
+ afterEach(() => {
+ for (const socket of sockets) {
+ socket.destroy();
+ }
+ vi.unstubAllEnvs();
+ });
+
+ afterAll(async () => {
+ await target.close();
+ await new Promise<void>((resolve) => proxy.close(() => resolve()));
+ });
+
+ it.each(['HTTP_PROXY', 'http_proxy'])(
+ 'routes HTTP through %s',
+ async (name) => {
+ vi.stubEnv(name, proxyUrl);
+
+ const response = await fetchThroughTransport(
+ 'http://unresolvable.example',
+ );
+
+ expect(await response.json()).toEqual({ ok: true });
+ expect(proxyRequests).toEqual([
+ { authority: 'unresolvable.example:80', authorization: undefined },
+ ]);
+ expect(target.requests[0].headers.authorization).toBe(
+ 'Bearer workspace-secret',
+ );
+ },
+ );
+
+ it.each(['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY'])(
+ 'routes HTTPS CONNECT through %s',
+ async (name) => {
+ vi.stubEnv(name, proxyUrl);
+
+ await expect(
+ fetchThroughTransport('https://secure.example'),
+ ).rejects.toMatchObject({ code: 'NETWORK_ERROR' });
+ expect(proxyRequests).toEqual([
+ { authority: 'secure.example:443', authorization: undefined },
+ ]);
+ },
+ );
+
+ it.each(['NO_PROXY', 'no_proxy'])(
+ 'bypasses the proxy using %s',
+ async (name) => {
+ vi.stubEnv('HTTP_PROXY', proxyUrl);
+ vi.stubEnv(name, '127.0.0.1');
+
+ expect((await fetchThroughTransport(target.url)).status).toBe(200);
+ expect(proxyRequests).toEqual([]);
+ expect(target.requests).toHaveLength(1);
+ },
+ );
+
+ it('lets lowercase settings override uppercase settings', async () => {
+ vi.stubEnv('HTTP_PROXY', 'http://unreachable.invalid');
+ vi.stubEnv('http_proxy', proxyUrl);
+ vi.stubEnv('NO_PROXY', '*');
+ vi.stubEnv('no_proxy', '');
+
+ expect(
+ (await fetchThroughTransport('http://unresolvable.example')).status,
+ ).toBe(200);
+ expect(proxyRequests).toHaveLength(1);
+ });
+
+ it('sends proxy credentials only to the proxy', async () => {
+ vi.stubEnv(
+ 'HTTP_PROXY',
+ proxyUrl.replace('http://', 'http://proxy-user:proxy-secret@'),
+ );
+
+ expect(
+ (await fetchThroughTransport('http://unresolvable.example')).status,
+ ).toBe(200);
+ expect(proxyRequests[0].authorization).toBe(
+ `Basic ${Buffer.from('proxy-user:proxy-secret').toString('base64')}`,
+ );
+ expect(target.requests[0].headers['proxy-authorization']).toBeUndefined();
+ expect(target.requests[0].headers.authorization).toBe(
+ 'Bearer workspace-secret',
+ );
+ });
+
+ it('does not expose proxy credentials in invalid-configuration errors', async () => {
+ vi.stubEnv('HTTP_PROXY', 'http://proxy-user:proxy-secret@[');
+
+ await expect(fetchThroughTransport(target.url)).rejects.toMatchObject({
+ code: 'INVALID_CONFIG',
+ message: 'Could not configure the network proxy.',
+ details: undefined,
+ });
+ });
+
+ it('routes signed uploads through the same proxy', async () => {
+ vi.stubEnv('HTTP_PROXY', proxyUrl);
+ const { putUploadFile } = await import('@/app/deployment/put-upload-file');
+
+ expect(
+ await putUploadFile({
+ uploadUrl: 'http://uploads.example/file?signature=secret',
+ contentType: 'text/plain',
+ bytes: new TextEncoder().encode('file contents'),
+ signal: new AbortController().signal,
+ }),
+ ).toBe(200);
+ expect(proxyRequests[0].authority).toBe('uploads.example:80');
+ expect(target.requests[0]).toMatchObject({
+ method: 'PUT',
+ body: 'file contents',
+ });
+ expect(target.requests[0].headers.authorization).toBeUndefined();
+ });
+
+ it('streams subscriptions through the proxy without forwarding proxy credentials', async () => {
+ vi.stubEnv(
+ 'HTTP_PROXY',
+ proxyUrl.replace('http://', 'http://proxy-user:proxy-secret@'),
+ );
+ const { subscribeGraphql } =
+ await import('@/transport/graphql/subscribe-graphql');
+ const records: unknown[] = [];
+
+ await subscribeGraphql({
+ target: {
+ apiUrl: 'http://unresolvable.example',
+ bearerToken: 'workspace-secret',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { message }',
+ variables: {},
+ onConnected: async () => {},
+ onData: async (data) => {
+ records.push(data);
+ },
+ });
+
+ expect(records).toEqual([{ message: 'hello' }]);
+ expect(proxyRequests).toHaveLength(1);
+ expect(proxyRequests[0].authority).toBe('unresolvable.example:80');
+ expect(target.requests[0].path).toBe('/metadata');
+ expect(target.requests[0].headers.authorization).toBe(
+ 'Bearer workspace-secret',
+ );
+ expect(target.requests[0].headers['proxy-authorization']).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-cli/src/transport/__tests__/fetch-without-proxy.spec.ts b/packages/twenty-cli/src/transport/__tests__/fetch-without-proxy.spec.ts
new file mode 100644
index 00000000000..633821523a1
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/fetch-without-proxy.spec.ts
@@ -0,0 +1,32 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+
+vi.mock('undici', () => {
+ throw new Error('Proxy tooling must not load without a proxy setting');
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+it('uses native fetch without loading proxy tooling when no proxy is configured', async () => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ const response = new Response('direct');
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(response);
+
+ expect(await fetchWithProxy('https://api.example', { method: 'GET' })).toBe(
+ response,
+ );
+ expect(fetchSpy).toHaveBeenCalledWith('https://api.example', {
+ method: 'GET',
+ });
+});
diff --git a/packages/twenty-cli/src/transport/__tests__/read-event-stream.spec.ts b/packages/twenty-cli/src/transport/__tests__/read-event-stream.spec.ts
new file mode 100644
index 00000000000..41049996416
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/read-event-stream.spec.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+
+import { readEventStream } from '@/transport/graphql/read-event-stream';
+
+const collect = async (chunks: Uint8Array[], frameByteLimit?: number) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ chunks.forEach((chunk) => controller.enqueue(chunk));
+ controller.close();
+ },
+ });
+ const messages = [];
+ for await (const message of readEventStream({
+ body,
+ signal: new AbortController().signal,
+ frameByteLimit,
+ })) {
+ messages.push(message);
+ }
+ return messages;
+};
+
+describe('bounded event stream reader', () => {
+ it.each(['\n', '\r\n', '\r'])(
+ 'handles %j boundaries, pings, multiline data and split UTF-8',
+ async (newline) => {
+ const text = [
+ ': ping',
+ '',
+ 'event: next',
+ 'data: {"logs":',
+ 'data: "café 😀"}',
+ '',
+ 'event: complete',
+ '',
+ '',
+ ].join(newline);
+ const bytes = Buffer.from(text);
+ const chunks = Array.from(bytes, (byte) => Uint8Array.of(byte));
+
+ expect(await collect(chunks)).toEqual([
+ { event: 'next', data: '{"logs":\n"café 😀"}' },
+ { event: 'complete', data: '' },
+ ]);
+ },
+ );
+
+ it('bounds each frame rather than the full session', async () => {
+ const frame = Buffer.from('event: next\ndata: {}\n\n');
+ expect(
+ await collect(
+ Array.from({ length: 100 }, () => frame),
+ 64,
+ ),
+ ).toHaveLength(100);
+ });
+
+ it.each([
+ 'data: ' + 'x'.repeat(100),
+ Array.from({ length: 20 }, () => ': comment\n').join(''),
+ 'event: next\n' + Array.from({ length: 20 }, () => 'data: a\n').join(''),
+ ])('rejects oversized unfinished lines or frames', async (text) => {
+ await expect(
+ collect(
+ Array.from(Buffer.from(text), (byte) => Uint8Array.of(byte)),
+ 64,
+ ),
+ ).rejects.toMatchObject({
+ code: 'RESPONSE_LIMIT_EXCEEDED',
+ details: { byteLimit: 64 },
+ });
+ });
+
+ it('does not consume another network chunk while the consumer is paused', async () => {
+ let pulls = 0;
+ let cancelled = false;
+ const body = new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ pulls += 1;
+ controller.enqueue(Buffer.from('event: next\ndata: {}\n\n'));
+ },
+ cancel() {
+ cancelled = true;
+ },
+ },
+ { highWaterMark: 0 },
+ );
+ const messages = readEventStream({
+ body,
+ signal: new AbortController().signal,
+ });
+
+ expect((await messages.next()).done).toBe(false);
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(pulls).toBe(1);
+ await messages.return();
+ expect(cancelled).toBe(true);
+ expect(body.locked).toBe(false);
+ });
+
+ it('cancels an idle reader and releases it on interruption', async () => {
+ const controller = new AbortController();
+ let cancelled = false;
+ const body = new ReadableStream<Uint8Array>({
+ cancel() {
+ cancelled = true;
+ },
+ });
+ const messages = readEventStream({ body, signal: controller.signal });
+ const waiting = messages.next();
+ controller.abort();
+
+ await expect(waiting).rejects.toBe(controller.signal.reason);
+ expect(cancelled).toBe(true);
+ expect(body.locked).toBe(false);
+ });
+});
diff --git a/packages/twenty-cli/src/transport/__tests__/request-timeout.spec.ts b/packages/twenty-cli/src/transport/__tests__/request-timeout.spec.ts
new file mode 100644
index 00000000000..f3ccca970ce
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/request-timeout.spec.ts
@@ -0,0 +1,136 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createBoundedFetch } from '@/transport/create-target-fetch';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+import { subscribeGraphql } from '@/transport/graphql/subscribe-graphql';
+
+vi.mock('@/transport/fetch-with-proxy');
+afterEach(() => {
+ vi.resetAllMocks();
+ vi.useRealTimers();
+});
+
+describe('request-specific transport timeout', () => {
+ it('ends a request at its configured deadline and reports that deadline', async () => {
+ vi.mocked(fetchWithProxy).mockImplementation(
+ async (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ 'abort',
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ }),
+ );
+ const request = createBoundedFetch({
+ apiUrl: 'https://example.test',
+ signal: new AbortController().signal,
+ timeoutMilliseconds: 20,
+ });
+
+ await expect(
+ request('https://example.test/metadata'),
+ ).rejects.toMatchObject({
+ code: 'TIMEOUT',
+ message: 'https://example.test did not answer within 0.02 seconds.',
+ });
+ expect(fetchWithProxy).toHaveBeenCalledOnce();
+ });
+
+ it('still cancels a long-running request immediately on user interruption', async () => {
+ const controller = new AbortController();
+ vi.mocked(fetchWithProxy).mockImplementation(
+ async (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ 'abort',
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ }),
+ );
+ const request = createBoundedFetch({
+ apiUrl: 'https://example.test',
+ signal: controller.signal,
+ timeoutMilliseconds: 360_000,
+ });
+ const response = request('https://example.test/metadata');
+ controller.abort();
+
+ await expect(response).rejects.toBe(controller.signal.reason);
+ expect(fetchWithProxy).toHaveBeenCalledOnce();
+ });
+
+ it('limits subscription connection setup to 60 seconds', async () => {
+ vi.useFakeTimers();
+ vi.mocked(fetchWithProxy).mockImplementation(
+ async (_input, init) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener(
+ 'abort',
+ () => reject(init.signal?.reason),
+ { once: true },
+ );
+ }),
+ );
+ const subscription = subscribeGraphql({
+ target: {
+ apiUrl: 'https://example.test',
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected: async () => {},
+ onData: async () => {},
+ });
+ const assertion = expect(subscription).rejects.toMatchObject({
+ code: 'TIMEOUT',
+ });
+ await vi.advanceTimersByTimeAsync(60_000);
+ await assertion;
+ expect(fetchWithProxy).toHaveBeenCalledOnce();
+ });
+
+ it('clears the connection deadline while waiting for future log records', async () => {
+ vi.useFakeTimers();
+ const connected = Promise.withResolvers<void>();
+ const stream = new TransformStream<Uint8Array>();
+ const writer = stream.writable.getWriter();
+ vi.mocked(fetchWithProxy).mockResolvedValue(
+ new Response(stream.readable, {
+ headers: { 'content-type': 'text/event-stream' },
+ }),
+ );
+ const records: unknown[] = [];
+ const subscription = subscribeGraphql({
+ target: {
+ apiUrl: 'https://example.test',
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected: async () => {
+ connected.resolve();
+ },
+ onData: async (data) => {
+ records.push(data);
+ },
+ });
+ await connected.promise;
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ await writer.write(
+ Buffer.from(
+ 'event: next\ndata: {"data":{"logs":"late"}}\n\nevent: complete\n\n',
+ ),
+ );
+ await subscription;
+ expect(records).toEqual([{ logs: 'late' }]);
+ expect(fetchWithProxy).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/twenty-cli/src/transport/__tests__/resolve-request-url.spec.ts b/packages/twenty-cli/src/transport/__tests__/resolve-request-url.spec.ts
new file mode 100644
index 00000000000..6698248bdd9
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/resolve-request-url.spec.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+const API_URL = 'https://acme.twenty.com/crm';
+
+describe('resolveRequestUrl', () => {
+ it('resolves paths under the API URL, keeping its base path', () => {
+ expect(
+ resolveRequestUrl({ apiUrl: API_URL, path: '/rest/companies?limit=2' })
+ .href,
+ ).toBe('https://acme.twenty.com/crm/rest/companies?limit=2');
+ expect(
+ resolveRequestUrl({ apiUrl: API_URL, path: 'rest/people' }).href,
+ ).toBe('https://acme.twenty.com/crm/rest/people');
+ });
+
+ it.each([
+ 'https://elsewhere.example.com/rest/companies',
+ '//elsewhere.example.com/rest/companies',
+ 'javascript:alert(1)',
+ '\\\\elsewhere\\share',
+ '../other/rest/companies',
+ ])('refuses %s', (path) => {
+ expect(() => resolveRequestUrl({ apiUrl: API_URL, path })).toThrow(
+ expect.objectContaining({ code: 'INVALID_REQUEST_PATH', exitCode: 2 }),
+ );
+ });
+});
diff --git a/packages/twenty-cli/src/transport/__tests__/subscription-timeout.spec.ts b/packages/twenty-cli/src/transport/__tests__/subscription-timeout.spec.ts
new file mode 100644
index 00000000000..cfa0a6bd2d2
--- /dev/null
+++ b/packages/twenty-cli/src/transport/__tests__/subscription-timeout.spec.ts
@@ -0,0 +1,103 @@
+import { setTimeout as delay } from 'node:timers/promises';
+
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { startTestServer } from '@/__tests__/utils/start-test-server';
+import { subscribeGraphql } from '@/transport/graphql/subscribe-graphql';
+
+vi.mock('@/transport/constants/request-timeout-milliseconds.constant', () => ({
+ REQUEST_TIMEOUT_MILLISECONDS: 500,
+}));
+
+afterEach(() => vi.unstubAllEnvs());
+
+const subscribe = (url: string, onData: (data: unknown) => Promise<void>) => {
+ for (const name of [
+ 'HTTP_PROXY',
+ 'HTTPS_PROXY',
+ 'http_proxy',
+ 'https_proxy',
+ ]) {
+ vi.stubEnv(name, undefined);
+ }
+ return subscribeGraphql({
+ target: {
+ apiUrl: url,
+ bearerToken: 'test',
+ credentialKind: 'apiKey',
+ source: 'environment',
+ },
+ signal: new AbortController().signal,
+ query: 'subscription { logs }',
+ variables: {},
+ onConnected: async () => {},
+ onData,
+ });
+};
+
+it('reports a stalled connection after its last record without reconnecting', async () => {
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.write('event: next\ndata: {"data":{"logs":"first"}}\n\n');
+ });
+ const records: unknown[] = [];
+ try {
+ await expect(
+ subscribe(server.url, async (data) => {
+ records.push(data);
+ }),
+ ).rejects.toMatchObject({
+ code: 'NETWORK_ERROR',
+ details: { networkCode: 'UND_ERR_BODY_TIMEOUT' },
+ });
+ expect(records).toEqual([{ logs: 'first' }]);
+ expect(server.requests).toHaveLength(1);
+ } finally {
+ await server.close();
+ }
+}, 10_000);
+
+it('keeps a quiet subscription alive while receiving server heartbeat comments', async () => {
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.write(':\n\n');
+ const heartbeat = setInterval(() => response.write(':\n\n'), 100);
+ const completion = setTimeout(
+ () => response.end('event: complete\n\n'),
+ 2_000,
+ );
+ response.on('close', () => {
+ clearInterval(heartbeat);
+ clearTimeout(completion);
+ });
+ });
+ try {
+ await expect(
+ subscribe(server.url, async () => {}),
+ ).resolves.toBeUndefined();
+ expect(server.requests).toHaveLength(1);
+ } finally {
+ await server.close();
+ }
+}, 10_000);
+
+it('does not time out a body paused by slow output', async () => {
+ const server = await startTestServer((_request, response) => {
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.end(
+ 'event: next\ndata: {"data":{"logs":"first"}}\n\n:' +
+ 'x'.repeat(2 * 1024 * 1024) +
+ '\n\nevent: complete\n\n',
+ );
+ });
+ try {
+ await expect(
+ subscribe(server.url, async () => {
+ await delay(2_000);
+ }),
+ ).resolves.toBeUndefined();
+ expect(server.requests).toHaveLength(1);
+ } finally {
+ await server.close();
+ }
+}, 10_000);
diff --git a/packages/twenty-cli/src/transport/assert-url-within-target.ts b/packages/twenty-cli/src/transport/assert-url-within-target.ts
new file mode 100644
index 00000000000..3acb0c31d58
--- /dev/null
+++ b/packages/twenty-cli/src/transport/assert-url-within-target.ts
@@ -0,0 +1,27 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const assertUrlWithinTarget = ({
+ url,
+ apiUrl,
+ requestedPath,
+}: {
+ url: URL;
+ apiUrl: string;
+ requestedPath: string;
+}) => {
+ const baseUrl = new URL(`${apiUrl}/`);
+
+ if (
+ url.origin !== baseUrl.origin ||
+ !url.pathname.startsWith(baseUrl.pathname)
+ ) {
+ throw new CliError({
+ code: 'INVALID_REQUEST_PATH',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${requestedPath} is outside ${apiUrl}.`,
+ hint: 'Pass a path relative to the API URL, for example /rest/companies.',
+ details: { path: requestedPath },
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/transport/constants/request-timeout-milliseconds.constant.ts b/packages/twenty-cli/src/transport/constants/request-timeout-milliseconds.constant.ts
new file mode 100644
index 00000000000..422b868cd7d
--- /dev/null
+++ b/packages/twenty-cli/src/transport/constants/request-timeout-milliseconds.constant.ts
@@ -0,0 +1 @@
+export const REQUEST_TIMEOUT_MILLISECONDS = 60_000;
diff --git a/packages/twenty-cli/src/transport/constants/response-byte-limit.constant.ts b/packages/twenty-cli/src/transport/constants/response-byte-limit.constant.ts
new file mode 100644
index 00000000000..4a46b5e04d4
--- /dev/null
+++ b/packages/twenty-cli/src/transport/constants/response-byte-limit.constant.ts
@@ -0,0 +1 @@
+export const RESPONSE_BYTE_LIMIT = 16 * 1024 * 1024;
diff --git a/packages/twenty-cli/src/transport/constants/result-item-limit.constant.ts b/packages/twenty-cli/src/transport/constants/result-item-limit.constant.ts
new file mode 100644
index 00000000000..f4b025e6989
--- /dev/null
+++ b/packages/twenty-cli/src/transport/constants/result-item-limit.constant.ts
@@ -0,0 +1 @@
+export const RESULT_ITEM_LIMIT = 10_000;
diff --git a/packages/twenty-cli/src/transport/create-http-status-error.ts b/packages/twenty-cli/src/transport/create-http-status-error.ts
new file mode 100644
index 00000000000..2d8d52c0ea3
--- /dev/null
+++ b/packages/twenty-cli/src/transport/create-http-status-error.ts
@@ -0,0 +1,84 @@
+import { isArray, isNonEmptyString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { getAuthenticationHint } from '@/target/get-authentication-hint';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { pickSafeResponseHeaders } from '@/transport/pick-safe-response-headers';
+
+const findServerMessage = (body: unknown) => {
+ if (!isPlainObject(body)) {
+ return undefined;
+ }
+
+ const messages = body.messages;
+
+ if (isArray(messages) && isNonEmptyString(messages[0])) {
+ return messages[0];
+ }
+
+ return isNonEmptyString(body.message) ? body.message : undefined;
+};
+
+export const createHttpStatusError = ({
+ status,
+ headers,
+ body,
+ target,
+}: {
+ status: number;
+ headers: Headers;
+ body: unknown;
+ target: ResolvedTarget;
+}) => {
+ const serverMessage = findServerMessage(body);
+ const details = {
+ status,
+ headers: pickSafeResponseHeaders(headers),
+ body,
+ };
+
+ if (status === 401) {
+ return new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `${target.apiUrl} rejected the credentials.`,
+ hint: getAuthenticationHint(target),
+ details,
+ });
+ }
+
+ if (status === 403) {
+ return new CliError({
+ code: 'PERMISSION_DENIED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: serverMessage ?? 'Access denied.',
+ details,
+ });
+ }
+
+ if (status === 404) {
+ return new CliError({
+ code: 'NOT_FOUND',
+ exitCode: EXIT_CODE.NOT_FOUND,
+ message: serverMessage ?? 'Not found.',
+ details,
+ });
+ }
+
+ if (status === 409) {
+ return new CliError({
+ code: 'CONFLICT',
+ exitCode: EXIT_CODE.CONFLICT,
+ message: serverMessage ?? 'The request conflicts with the current state.',
+ details,
+ });
+ }
+
+ return new CliError({
+ code: 'HTTP_ERROR',
+ message: `The server answered ${status}${isNonEmptyString(serverMessage) ? `: ${serverMessage}` : '.'}`,
+ details,
+ });
+};
diff --git a/packages/twenty-cli/src/transport/create-target-fetch.ts b/packages/twenty-cli/src/transport/create-target-fetch.ts
new file mode 100644
index 00000000000..1764350144c
--- /dev/null
+++ b/packages/twenty-cli/src/transport/create-target-fetch.ts
@@ -0,0 +1,158 @@
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { assertUrlWithinTarget } from '@/transport/assert-url-within-target';
+import { REQUEST_TIMEOUT_MILLISECONDS } from '@/transport/constants/request-timeout-milliseconds.constant';
+import { RESPONSE_BYTE_LIMIT } from '@/transport/constants/response-byte-limit.constant';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+import { readBoundedBody } from '@/transport/read-bounded-body';
+
+const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
+
+const isRedirectStatus = (status: number) => status >= 300 && status < 400;
+
+const getRedirectOrigin = (response: Response, requestUrl: URL) => {
+ const location = response.headers.get('location');
+
+ return isDefined(location)
+ ? URL.parse(location, requestUrl.href)?.origin
+ : undefined;
+};
+
+export const toTransportError = ({
+ error,
+ signal,
+ url,
+ timeoutMilliseconds,
+}: {
+ error: unknown;
+ signal: AbortSignal;
+ url: URL;
+ timeoutMilliseconds: number;
+}) => {
+ if (error instanceof CliError || signal.aborted) {
+ return error;
+ }
+
+ if (error instanceof Error && error.name === 'TimeoutError') {
+ return new CliError({
+ code: 'TIMEOUT',
+ message: `${url.origin} did not answer within ${timeoutMilliseconds / 1000} seconds.`,
+ });
+ }
+
+ const reason =
+ error instanceof Error && error.cause instanceof Error
+ ? error.cause.message
+ : String(error);
+ const cause =
+ error instanceof Error && error.cause instanceof Error
+ ? error.cause
+ : error;
+ const networkCode =
+ cause instanceof Error && 'code' in cause && isString(cause.code)
+ ? cause.code
+ : undefined;
+
+ return new CliError({
+ code: 'NETWORK_ERROR',
+ message: `Could not reach ${url.origin}.`,
+ hint: 'Check the API URL and that the server is running.',
+ details: { reason, ...(isDefined(networkCode) ? { networkCode } : {}) },
+ });
+};
+
+export const createRedirectError = (response: Response, url: URL) => {
+ const redirectOrigin = getRedirectOrigin(response, url);
+
+ return new CliError({
+ code: 'REDIRECT_NOT_FOLLOWED',
+ message: `${url.origin} answered with a redirect (${response.status}), and redirects are not followed.`,
+ hint: isDefined(redirectOrigin)
+ ? `It redirects to ${redirectOrigin}. If that is the right server, use it as the API URL.`
+ : 'Check that the API URL points at the Twenty server itself.',
+ details: {
+ status: response.status,
+ redirectOrigin: redirectOrigin ?? null,
+ },
+ });
+};
+
+export const createBoundedFetch =
+ ({
+ apiUrl,
+ bearerToken,
+ signal,
+ timeoutMilliseconds = REQUEST_TIMEOUT_MILLISECONDS,
+ }: {
+ apiUrl: string;
+ bearerToken?: string;
+ signal: AbortSignal;
+ timeoutMilliseconds?: number;
+ }): typeof fetch =>
+ async (input, init = {}) => {
+ const url = new URL(input instanceof Request ? input.url : input);
+
+ assertUrlWithinTarget({ url, apiUrl, requestedPath: url.pathname });
+
+ const headers = new Headers(init.headers);
+
+ if (isDefined(bearerToken)) {
+ headers.set('Authorization', `Bearer ${bearerToken}`);
+ }
+
+ try {
+ const response = await fetchWithProxy(
+ url,
+ {
+ ...init,
+ headers,
+ redirect: 'manual',
+ signal: AbortSignal.any([
+ signal,
+ AbortSignal.timeout(timeoutMilliseconds),
+ ]),
+ },
+ timeoutMilliseconds === REQUEST_TIMEOUT_MILLISECONDS
+ ? undefined
+ : timeoutMilliseconds,
+ );
+
+ if (isRedirectStatus(response.status)) {
+ await response.body?.cancel();
+
+ throw createRedirectError(response, url);
+ }
+
+ const body = await readBoundedBody(response, RESPONSE_BYTE_LIMIT);
+
+ return new Response(
+ NULL_BODY_STATUSES.has(response.status) ? null : body,
+ {
+ status: response.status,
+ statusText: response.statusText,
+ headers: response.headers,
+ },
+ );
+ } catch (error) {
+ throw toTransportError({ error, signal, url, timeoutMilliseconds });
+ }
+ };
+
+export const createTargetFetch = ({
+ target,
+ signal,
+ timeoutMilliseconds,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ timeoutMilliseconds?: number;
+}) =>
+ createBoundedFetch({
+ apiUrl: target.apiUrl,
+ bearerToken: target.bearerToken,
+ signal,
+ timeoutMilliseconds,
+ });
diff --git a/packages/twenty-cli/src/transport/fetch-with-proxy.ts b/packages/twenty-cli/src/transport/fetch-with-proxy.ts
new file mode 100644
index 00000000000..aacbfae239a
--- /dev/null
+++ b/packages/twenty-cli/src/transport/fetch-with-proxy.ts
@@ -0,0 +1,58 @@
+import { type Dispatcher, type EnvHttpProxyAgent } from 'undici';
+
+import { CliError } from '@/output/cli-error';
+
+let proxyAgent: Promise<EnvHttpProxyAgent> | undefined;
+
+const createProxyAgent = async () => {
+ try {
+ const { EnvHttpProxyAgent } = await import('undici');
+
+ return new EnvHttpProxyAgent();
+ } catch {
+ throw new CliError({
+ code: 'INVALID_CONFIG',
+ message: 'Could not configure the network proxy.',
+ hint: 'Check HTTP_PROXY, HTTPS_PROXY, http_proxy and https_proxy.',
+ });
+ }
+};
+
+export const fetchWithProxy = async (
+ input: Parameters<typeof fetch>[0],
+ init?: Parameters<typeof fetch>[1],
+ timeoutMilliseconds?: number,
+): Promise<Response> => {
+ const httpProxy = process.env.http_proxy ?? process.env.HTTP_PROXY;
+ const httpsProxy = process.env.https_proxy ?? process.env.HTTPS_PROXY;
+
+ if (!httpProxy && !httpsProxy && timeoutMilliseconds === undefined) {
+ return fetch(input, init);
+ }
+
+ let dispatcher: Dispatcher;
+ if (httpProxy || httpsProxy) {
+ proxyAgent ??= createProxyAgent();
+ dispatcher = await proxyAgent;
+ } else {
+ dispatcher = (await import('undici')).getGlobalDispatcher();
+ }
+
+ const requestDispatcher: Pick<Dispatcher, 'dispatch'> =
+ timeoutMilliseconds === undefined
+ ? dispatcher
+ : {
+ dispatch: (options, handler) =>
+ dispatcher.dispatch(
+ {
+ ...options,
+ headersTimeout: timeoutMilliseconds,
+ bodyTimeout: timeoutMilliseconds,
+ },
+ handler,
+ ),
+ };
+ const options = { ...init, dispatcher: requestDispatcher };
+
+ return fetch(input, options);
+};
diff --git a/packages/twenty-cli/src/transport/graphql/constants/graphql-endpoint-paths.constant.ts b/packages/twenty-cli/src/transport/graphql/constants/graphql-endpoint-paths.constant.ts
new file mode 100644
index 00000000000..342e427c032
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/constants/graphql-endpoint-paths.constant.ts
@@ -0,0 +1,4 @@
+export const GRAPHQL_ENDPOINT_PATHS = {
+ core: '/graphql',
+ metadata: '/metadata',
+} as const;
diff --git a/packages/twenty-cli/src/transport/graphql/create-graphql-error.ts b/packages/twenty-cli/src/transport/graphql/create-graphql-error.ts
new file mode 100644
index 00000000000..4ad280c381b
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/create-graphql-error.ts
@@ -0,0 +1,77 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { getAuthenticationHint } from '@/target/get-authentication-hint';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { pickSafeResponseHeaders } from '@/transport/pick-safe-response-headers';
+
+const toPublicGraphqlError = (error: unknown) => {
+ const entry: Record<string, unknown> = isPlainObject(error) ? error : {};
+
+ return {
+ message: isString(entry.message) ? entry.message : 'Unknown GraphQL error',
+ path: isArray(entry.path) ? entry.path : null,
+ code:
+ isPlainObject(entry.extensions) && isString(entry.extensions.code)
+ ? entry.extensions.code
+ : null,
+ ...(isPlainObject(entry.extensions) && isString(entry.extensions.subCode)
+ ? { subCode: entry.extensions.subCode }
+ : {}),
+ };
+};
+
+const summarizeMessages = (errors: { message: string }[]) =>
+ errors.length === 1
+ ? errors[0].message
+ : `${errors[0].message} (and ${errors.length - 1} more errors)`;
+
+export const createGraphqlError = ({
+ errors,
+ data,
+ status,
+ headers,
+ target,
+}: {
+ errors: unknown[];
+ data: unknown;
+ status: number;
+ headers: Headers;
+ target: ResolvedTarget;
+}) => {
+ const publicErrors = errors.map(toPublicGraphqlError);
+ const errorCodes = publicErrors.map((error) => error.code);
+ const details = {
+ status,
+ headers: pickSafeResponseHeaders(headers),
+ errors: publicErrors,
+ data: data ?? null,
+ };
+
+ if (status === 401 || errorCodes.includes('UNAUTHENTICATED')) {
+ return new CliError({
+ code: 'AUTH_REQUIRED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: `${target.apiUrl} rejected the credentials.`,
+ hint: getAuthenticationHint(target),
+ details,
+ });
+ }
+
+ if (status === 403 || errorCodes.includes('FORBIDDEN')) {
+ return new CliError({
+ code: 'PERMISSION_DENIED',
+ exitCode: EXIT_CODE.AUTHENTICATION,
+ message: summarizeMessages(publicErrors),
+ details,
+ });
+ }
+
+ return new CliError({
+ code: 'GRAPHQL_ERROR',
+ message: summarizeMessages(publicErrors),
+ details,
+ });
+};
diff --git a/packages/twenty-cli/src/transport/graphql/parse-graphql-response.ts b/packages/twenty-cli/src/transport/graphql/parse-graphql-response.ts
new file mode 100644
index 00000000000..c827d84d62d
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/parse-graphql-response.ts
@@ -0,0 +1,53 @@
+import { isNonEmptyArray } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createHttpStatusError } from '@/transport/create-http-status-error';
+import { createGraphqlError } from '@/transport/graphql/create-graphql-error';
+import { parseResponseBody } from '@/transport/parse-response-body';
+import { pickSafeResponseHeaders } from '@/transport/pick-safe-response-headers';
+
+export const parseGraphqlResponse = async ({
+ response,
+ target,
+}: {
+ response: Response;
+ target: ResolvedTarget;
+}) => {
+ const body = await parseResponseBody(response);
+ const payload = isPlainObject(body) ? body : undefined;
+
+ if (isNonEmptyArray(payload?.errors)) {
+ throw createGraphqlError({
+ errors: payload.errors,
+ data: payload.data,
+ status: response.status,
+ headers: response.headers,
+ target,
+ });
+ }
+
+ if (!response.ok) {
+ throw createHttpStatusError({
+ status: response.status,
+ headers: response.headers,
+ body,
+ target,
+ });
+ }
+
+ if (!isDefined(payload) || !('data' in payload)) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'The server answered without a GraphQL result.',
+ details: {
+ status: response.status,
+ headers: pickSafeResponseHeaders(response.headers),
+ body,
+ },
+ });
+ }
+
+ return { data: isPlainObject(payload.data) ? payload.data : null };
+};
diff --git a/packages/twenty-cli/src/transport/graphql/read-event-stream.ts b/packages/twenty-cli/src/transport/graphql/read-event-stream.ts
new file mode 100644
index 00000000000..e77f495ebb4
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/read-event-stream.ts
@@ -0,0 +1,100 @@
+import { CliError } from '@/output/cli-error';
+import { RESPONSE_BYTE_LIMIT } from '@/transport/constants/response-byte-limit.constant';
+
+export async function* readEventStream({
+ body,
+ signal,
+ frameByteLimit = RESPONSE_BYTE_LIMIT,
+}: {
+ body: ReadableStream<Uint8Array>;
+ signal: AbortSignal;
+ frameByteLimit?: number;
+}) {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let line = '';
+ let event = '';
+ let data: string[] = [];
+ let frameBytes = 0;
+ let skipLineFeed = false;
+
+ const countBytes = (bytes: number) => {
+ frameBytes += bytes;
+ if (frameBytes > frameByteLimit) {
+ throw new CliError({
+ code: 'RESPONSE_LIMIT_EXCEEDED',
+ message: `A log stream frame exceeds ${frameByteLimit} bytes.`,
+ details: { byteLimit: frameByteLimit },
+ });
+ }
+ };
+ const cancel = () => {
+ void reader.cancel().catch(() => undefined);
+ };
+ signal.addEventListener('abort', cancel, { once: true });
+
+ try {
+ signal.throwIfAborted();
+ for (
+ let chunk = await reader.read();
+ !chunk.done;
+ chunk = await reader.read()
+ ) {
+ signal.throwIfAborted();
+
+ let start = 0;
+ for (let index = 0; index < chunk.value.length; index += 1) {
+ const byte = chunk.value[index];
+ if (skipLineFeed) {
+ skipLineFeed = false;
+ if (byte === 10) {
+ countBytes(1);
+ start = index + 1;
+ continue;
+ }
+ }
+ if (byte !== 10 && byte !== 13) {
+ continue;
+ }
+
+ countBytes(index - start + 1);
+ line += decoder.decode(chunk.value.subarray(start, index), {
+ stream: true,
+ });
+ line += decoder.decode();
+ start = index + 1;
+ skipLineFeed = byte === 13;
+
+ if (line.length === 0) {
+ const message = { event, data: data.join('\n') };
+ event = '';
+ data = [];
+ frameBytes = 0;
+ if (message.event.length > 0 || message.data.length > 0) {
+ yield message;
+ signal.throwIfAborted();
+ }
+ } else {
+ const colon = line.indexOf(':');
+ const field = colon === -1 ? line : line.slice(0, colon);
+ const value =
+ colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '');
+ if (field === 'event') {
+ event = value;
+ } else if (field === 'data') {
+ data.push(value);
+ }
+ }
+ line = '';
+ }
+
+ countBytes(chunk.value.length - start);
+ line += decoder.decode(chunk.value.subarray(start), { stream: true });
+ }
+ signal.throwIfAborted();
+ } finally {
+ signal.removeEventListener('abort', cancel);
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+}
diff --git a/packages/twenty-cli/src/transport/graphql/send-graphql-request.ts b/packages/twenty-cli/src/transport/graphql/send-graphql-request.ts
new file mode 100644
index 00000000000..9cd63d3c9d3
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/send-graphql-request.ts
@@ -0,0 +1,38 @@
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createTargetFetch } from '@/transport/create-target-fetch';
+import { GRAPHQL_ENDPOINT_PATHS } from '@/transport/graphql/constants/graphql-endpoint-paths.constant';
+import { parseGraphqlResponse } from '@/transport/graphql/parse-graphql-response';
+import { type GraphqlEndpoint } from '@/transport/graphql/types/graphql-endpoint.type';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+export const sendGraphqlRequest = async ({
+ target,
+ signal,
+ endpoint,
+ query,
+ variables,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ endpoint: GraphqlEndpoint;
+ query: string;
+ variables?: Record<string, unknown>;
+}) => {
+ const response = await createTargetFetch({ target, signal })(
+ resolveRequestUrl({
+ apiUrl: target.apiUrl,
+ path: GRAPHQL_ENDPOINT_PATHS[endpoint],
+ }),
+ {
+ method: 'POST',
+ headers: {
+ Accept: 'application/graphql-response+json, application/json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ query, variables }),
+ },
+ );
+ const payload = await parseGraphqlResponse({ response, target });
+
+ return payload.data ?? null;
+};
diff --git a/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts b/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts
new file mode 100644
index 00000000000..5eb6df2e5a0
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/subscribe-graphql.ts
@@ -0,0 +1,154 @@
+import { isArray } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { REQUEST_TIMEOUT_MILLISECONDS } from '@/transport/constants/request-timeout-milliseconds.constant';
+import { RESPONSE_BYTE_LIMIT } from '@/transport/constants/response-byte-limit.constant';
+import {
+ createRedirectError,
+ toTransportError,
+} from '@/transport/create-target-fetch';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+import { GRAPHQL_ENDPOINT_PATHS } from '@/transport/graphql/constants/graphql-endpoint-paths.constant';
+import { createGraphqlError } from '@/transport/graphql/create-graphql-error';
+import { parseGraphqlResponse } from '@/transport/graphql/parse-graphql-response';
+import { readEventStream } from '@/transport/graphql/read-event-stream';
+import { readBoundedBody } from '@/transport/read-bounded-body';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+const invalidStream = (message: string) =>
+ new CliError({ code: 'INVALID_RESPONSE', message });
+
+export const subscribeGraphql = async ({
+ target,
+ signal,
+ query,
+ variables,
+ onConnected,
+ onData,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ query: string;
+ variables: Record<string, unknown>;
+ onConnected: () => Promise<void>;
+ onData: (data: unknown) => Promise<void>;
+}) => {
+ const url = resolveRequestUrl({
+ apiUrl: target.apiUrl,
+ path: GRAPHQL_ENDPOINT_PATHS.metadata,
+ });
+ const controller = new AbortController();
+ const requestSignal = AbortSignal.any([signal, controller.signal]);
+ const timer = setTimeout(
+ () =>
+ controller.abort(
+ new DOMException('Connection timed out', 'TimeoutError'),
+ ),
+ REQUEST_TIMEOUT_MILLISECONDS,
+ );
+
+ try {
+ const response = await fetchWithProxy(
+ url,
+ {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${target.bearerToken}`,
+ 'Content-Type': 'application/json',
+ Accept: 'text/event-stream',
+ },
+ body: JSON.stringify({ query, variables }),
+ redirect: 'manual',
+ signal: requestSignal,
+ },
+ REQUEST_TIMEOUT_MILLISECONDS,
+ );
+
+ if (response.status >= 300 && response.status < 400) {
+ await response.body?.cancel();
+ throw createRedirectError(response, url);
+ }
+ if (
+ !response.ok ||
+ response.headers
+ .get('content-type')
+ ?.split(';')[0]
+ .trim()
+ .toLowerCase() !== 'text/event-stream'
+ ) {
+ const bytes = await readBoundedBody(response, RESPONSE_BYTE_LIMIT);
+ await parseGraphqlResponse({
+ response: new Response(
+ [204, 205].includes(response.status) ? null : bytes,
+ {
+ status: response.status,
+ headers: response.headers,
+ },
+ ),
+ target,
+ });
+ throw invalidStream('The server did not return a GraphQL event stream.');
+ }
+ if (!isDefined(response.body)) {
+ throw invalidStream('The server returned an empty log stream.');
+ }
+ clearTimeout(timer);
+ await onConnected();
+
+ for await (const message of readEventStream({
+ body: response.body,
+ signal: requestSignal,
+ })) {
+ if (message.event === 'complete') {
+ return;
+ }
+ if (message.event !== 'next') {
+ throw invalidStream(
+ 'The server returned an unsupported GraphQL stream event.',
+ );
+ }
+ let payload: unknown;
+ try {
+ payload = JSON.parse(message.data);
+ } catch {
+ throw invalidStream('The log stream contains invalid JSON.');
+ }
+ if (!isPlainObject(payload)) {
+ throw invalidStream(
+ 'The log stream contains an invalid GraphQL result.',
+ );
+ }
+ if (isArray(payload.errors) && payload.errors.length > 0) {
+ throw createGraphqlError({
+ errors: payload.errors,
+ data: payload.data,
+ status: response.status,
+ headers: response.headers,
+ target,
+ });
+ }
+ if (!('data' in payload)) {
+ throw invalidStream('The log stream contains no GraphQL data.');
+ }
+ await onData(payload.data);
+ }
+
+ throw new CliError({
+ code: 'NETWORK_ERROR',
+ message: 'The log stream ended without a completion event.',
+ hint: 'Restart twenty app logs to resume watching. Logs produced while disconnected cannot be replayed.',
+ });
+ } catch (error) {
+ throw toTransportError({
+ error,
+ signal,
+ url,
+ timeoutMilliseconds: REQUEST_TIMEOUT_MILLISECONDS,
+ });
+ } finally {
+ clearTimeout(timer);
+ controller.abort();
+ }
+};
diff --git a/packages/twenty-cli/src/transport/graphql/types/graphql-endpoint.type.ts b/packages/twenty-cli/src/transport/graphql/types/graphql-endpoint.type.ts
new file mode 100644
index 00000000000..6c8bd0ecd1e
--- /dev/null
+++ b/packages/twenty-cli/src/transport/graphql/types/graphql-endpoint.type.ts
@@ -0,0 +1,3 @@
+import { type GRAPHQL_ENDPOINT_PATHS } from '@/transport/graphql/constants/graphql-endpoint-paths.constant';
+
+export type GraphqlEndpoint = keyof typeof GRAPHQL_ENDPOINT_PATHS;
diff --git a/packages/twenty-cli/src/transport/metadata/create-metadata-client.ts b/packages/twenty-cli/src/transport/metadata/create-metadata-client.ts
new file mode 100644
index 00000000000..e9d032717ae
--- /dev/null
+++ b/packages/twenty-cli/src/transport/metadata/create-metadata-client.ts
@@ -0,0 +1,40 @@
+import { MetadataApiClient } from 'twenty-client-sdk/metadata';
+
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createTargetFetch } from '@/transport/create-target-fetch';
+import { GRAPHQL_ENDPOINT_PATHS } from '@/transport/graphql/constants/graphql-endpoint-paths.constant';
+import { parseGraphqlResponse } from '@/transport/graphql/parse-graphql-response';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+export const createMetadataClient = ({
+ target,
+ signal,
+ timeoutMilliseconds,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ timeoutMilliseconds?: number;
+}) => {
+ const targetFetch = createTargetFetch({
+ target,
+ signal,
+ timeoutMilliseconds,
+ });
+
+ const fetchValidGraphqlResponse: typeof fetch = async (input, init) => {
+ const response = await targetFetch(input, init);
+
+ await parseGraphqlResponse({ response: response.clone(), target });
+
+ return response;
+ };
+
+ return new MetadataApiClient({
+ url: resolveRequestUrl({
+ apiUrl: target.apiUrl,
+ path: GRAPHQL_ENDPOINT_PATHS.metadata,
+ }).href,
+ headers: { Authorization: `Bearer ${target.bearerToken}` },
+ fetch: fetchValidGraphqlResponse,
+ });
+};
diff --git a/packages/twenty-cli/src/transport/metadata/fetch-signed-in-identity.ts b/packages/twenty-cli/src/transport/metadata/fetch-signed-in-identity.ts
new file mode 100644
index 00000000000..09081432579
--- /dev/null
+++ b/packages/twenty-cli/src/transport/metadata/fetch-signed-in-identity.ts
@@ -0,0 +1,30 @@
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+
+export const fetchSignedInIdentity = async ({
+ target,
+ signal,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const client = createMetadataClient({ target, signal });
+
+ if (target.credentialKind === 'apiKey') {
+ const { currentWorkspace } = await client.query({
+ currentWorkspace: { displayName: true },
+ });
+
+ return { workspaceName: currentWorkspace.displayName ?? null, email: null };
+ }
+
+ const { currentWorkspace, currentUser } = await client.query({
+ currentWorkspace: { displayName: true },
+ currentUser: { email: true },
+ });
+
+ return {
+ workspaceName: currentWorkspace.displayName ?? null,
+ email: currentUser.email,
+ };
+};
diff --git a/packages/twenty-cli/src/transport/metadata/fetch-workspace-url.ts b/packages/twenty-cli/src/transport/metadata/fetch-workspace-url.ts
new file mode 100644
index 00000000000..e8443854fa0
--- /dev/null
+++ b/packages/twenty-cli/src/transport/metadata/fetch-workspace-url.ts
@@ -0,0 +1,63 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { API_URL_PROTOCOLS } from '@/target/constants/api-url-protocols.constant';
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createBoundedFetch } from '@/transport/create-target-fetch';
+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';
+import { parseResponseBody } from '@/transport/parse-response-body';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+const parseWorkspaceUrl = (value: unknown, apiUrl: string) => {
+ const url = isNonEmptyString(value) ? URL.parse(value) : null;
+
+ if (!isDefined(url) || !API_URL_PROTOCOLS.includes(url.protocol)) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `${apiUrl} did not return a web address for this workspace.`,
+ });
+ }
+
+ return url;
+};
+
+export const fetchWorkspaceUrl = async ({
+ target,
+ signal,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const client = createMetadataClient({ target, signal });
+ const { currentWorkspace } = await client.query({
+ currentWorkspace: {
+ workspaceUrls: { customUrl: true, subdomainUrl: true },
+ },
+ });
+ const urls = currentWorkspace?.workspaceUrls;
+ const workspaceUrl = isNonEmptyString(urls?.customUrl)
+ ? urls.customUrl
+ : urls?.subdomainUrl;
+
+ if (isNonEmptyString(workspaceUrl)) {
+ return parseWorkspaceUrl(workspaceUrl, target.apiUrl);
+ }
+
+ const response = await createBoundedFetch({ apiUrl: target.apiUrl, signal })(
+ resolveRequestUrl({
+ apiUrl: target.apiUrl,
+ path: '/.well-known/oauth-authorization-server',
+ }),
+ { headers: { Accept: 'application/json' } },
+ );
+ const metadata = await parseResponseBody(response);
+ const authorizationEndpoint = parseWorkspaceUrl(
+ response.ok && isPlainObject(metadata)
+ ? metadata.authorization_endpoint
+ : undefined,
+ target.apiUrl,
+ );
+
+ return new URL(authorizationEndpoint.origin);
+};
diff --git a/packages/twenty-cli/src/transport/parse-response-body.ts b/packages/twenty-cli/src/transport/parse-response-body.ts
new file mode 100644
index 00000000000..2756581e23d
--- /dev/null
+++ b/packages/twenty-cli/src/transport/parse-response-body.ts
@@ -0,0 +1,36 @@
+import { CliError } from '@/output/cli-error';
+
+const JSON_CONTENT_TYPE_PATTERN = /^application\/([\w.+-]+\+)?json/i;
+
+const TEXT_CONTENT_TYPE_PATTERN =
+ /^(text\/|application\/([\w.+-]+\+)?(json|xml)|application\/javascript)/i;
+
+export const parseResponseBody = async (
+ response: Response,
+): Promise<unknown> => {
+ const contentType = response.headers.get('content-type') ?? '';
+
+ if (contentType !== '' && !TEXT_CONTENT_TYPE_PATTERN.test(contentType)) {
+ throw new CliError({
+ code: 'UNSUPPORTED_RESPONSE_TYPE',
+ message: `The response is ${contentType}, and binary bodies are not supported yet.`,
+ details: { status: response.status, contentType },
+ });
+ }
+
+ const text = await response.text();
+
+ if (text === '') {
+ return null;
+ }
+
+ if (!JSON_CONTENT_TYPE_PATTERN.test(contentType)) {
+ return text;
+ }
+
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+};
diff --git a/packages/twenty-cli/src/transport/pick-safe-response-headers.ts b/packages/twenty-cli/src/transport/pick-safe-response-headers.ts
new file mode 100644
index 00000000000..ecba31e0c16
--- /dev/null
+++ b/packages/twenty-cli/src/transport/pick-safe-response-headers.ts
@@ -0,0 +1,19 @@
+import { isDefined } from 'twenty-shared/utils';
+
+const SAFE_RESPONSE_HEADERS = [
+ 'content-type',
+ 'retry-after',
+ 'x-request-id',
+ 'x-ratelimit-limit',
+ 'x-ratelimit-remaining',
+ 'x-ratelimit-reset',
+];
+
+export const pickSafeResponseHeaders = (headers: Headers) =>
+ Object.fromEntries(
+ SAFE_RESPONSE_HEADERS.flatMap((headerName) => {
+ const value = headers.get(headerName);
+
+ return isDefined(value) ? [[headerName, value]] : [];
+ }),
+ );
diff --git a/packages/twenty-cli/src/transport/read-bounded-body.ts b/packages/twenty-cli/src/transport/read-bounded-body.ts
new file mode 100644
index 00000000000..94a1482c0a5
--- /dev/null
+++ b/packages/twenty-cli/src/transport/read-bounded-body.ts
@@ -0,0 +1,48 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+
+const createResponseLimitError = (byteLimit: number) =>
+ new CliError({
+ code: 'RESPONSE_LIMIT_EXCEEDED',
+ message: `The response is larger than ${byteLimit / 1024 / 1024} MiB.`,
+ hint: 'Ask for less data, for example a smaller page or fewer fields.',
+ details: { byteLimit },
+ });
+
+export const readBoundedBody = async (
+ response: Response,
+ byteLimit: number,
+) => {
+ const declaredLength = Number(response.headers.get('content-length'));
+
+ if (Number.isFinite(declaredLength) && declaredLength > byteLimit) {
+ await response.body?.cancel();
+
+ throw createResponseLimitError(byteLimit);
+ }
+
+ if (!isDefined(response.body)) {
+ return new Uint8Array();
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let receivedBytes = 0;
+ let readResult = await reader.read();
+
+ while (!readResult.done) {
+ receivedBytes += readResult.value.byteLength;
+
+ if (receivedBytes > byteLimit) {
+ await reader.cancel();
+
+ throw createResponseLimitError(byteLimit);
+ }
+
+ chunks.push(readResult.value);
+ readResult = await reader.read();
+ }
+
+ return Buffer.concat(chunks);
+};
diff --git a/packages/twenty-cli/src/transport/resolve-request-url.ts b/packages/twenty-cli/src/transport/resolve-request-url.ts
new file mode 100644
index 00000000000..5da9aeeb562
--- /dev/null
+++ b/packages/twenty-cli/src/transport/resolve-request-url.ts
@@ -0,0 +1,35 @@
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { assertUrlWithinTarget } from '@/transport/assert-url-within-target';
+
+const ABSOLUTE_URL_PATTERN = /^[a-z][a-z\d+.-]*:/i;
+
+export const resolveRequestUrl = ({
+ apiUrl,
+ path,
+}: {
+ apiUrl: string;
+ path: string;
+}) => {
+ const trimmedPath = path.trim();
+
+ if (
+ ABSOLUTE_URL_PATTERN.test(trimmedPath) ||
+ trimmedPath.startsWith('//') ||
+ trimmedPath.includes('\\')
+ ) {
+ throw new CliError({
+ code: 'INVALID_REQUEST_PATH',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${path} is not a relative path.`,
+ hint: 'Pass the path only, for example /rest/companies. Requests always go to the selected workspace.',
+ details: { path },
+ });
+ }
+
+ const url = new URL(trimmedPath.replace(/^\/+/, ''), `${apiUrl}/`);
+
+ assertUrlWithinTarget({ url, apiUrl, requestedPath: path });
+
+ return url;
+};
diff --git a/packages/twenty-cli/src/transport/rest/create-rest-client.ts b/packages/twenty-cli/src/transport/rest/create-rest-client.ts
new file mode 100644
index 00000000000..ce5710b0d0f
--- /dev/null
+++ b/packages/twenty-cli/src/transport/rest/create-rest-client.ts
@@ -0,0 +1,37 @@
+import { RestApiClient } from 'twenty-client-sdk/rest';
+
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createHttpStatusError } from '@/transport/create-http-status-error';
+import { createTargetFetch } from '@/transport/create-target-fetch';
+import { parseResponseBody } from '@/transport/parse-response-body';
+
+export const createRestClient = ({
+ target,
+ signal,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+}) => {
+ const targetFetch = createTargetFetch({ target, signal });
+ const fetchValidRestResponse: typeof fetch = async (input, init) => {
+ const response = await targetFetch(input, init);
+
+ if (!response.ok) {
+ throw createHttpStatusError({
+ status: response.status,
+ headers: response.headers,
+ body: await parseResponseBody(response),
+ target,
+ });
+ }
+
+ return response;
+ };
+
+ return new RestApiClient({
+ baseUrl: target.apiUrl,
+ token: target.bearerToken,
+ fetch: fetchValidRestResponse,
+ defaultHeaders: { Accept: 'application/json' },
+ });
+};
diff --git a/packages/twenty-cli/src/transport/send-rest-request.ts b/packages/twenty-cli/src/transport/send-rest-request.ts
new file mode 100644
index 00000000000..51c6ce74c66
--- /dev/null
+++ b/packages/twenty-cli/src/transport/send-rest-request.ts
@@ -0,0 +1,50 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ResolvedTarget } from '@/target/types/resolved-target.type';
+import { createHttpStatusError } from '@/transport/create-http-status-error';
+import { createTargetFetch } from '@/transport/create-target-fetch';
+import { parseResponseBody } from '@/transport/parse-response-body';
+import { pickSafeResponseHeaders } from '@/transport/pick-safe-response-headers';
+import { resolveRequestUrl } from '@/transport/resolve-request-url';
+
+export const sendRestRequest = async ({
+ target,
+ signal,
+ method,
+ path,
+ body,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ method: string;
+ path: string;
+ body?: string;
+}) => {
+ const response = await createTargetFetch({ target, signal })(
+ resolveRequestUrl({ apiUrl: target.apiUrl, path }),
+ {
+ method,
+ headers: {
+ Accept: 'application/json',
+ ...(isDefined(body) ? { 'Content-Type': 'application/json' } : {}),
+ },
+ body,
+ },
+ );
+ const responseBody = await parseResponseBody(response);
+
+ if (!response.ok) {
+ throw createHttpStatusError({
+ status: response.status,
+ headers: response.headers,
+ body: responseBody,
+ target,
+ });
+ }
+
+ return {
+ status: response.status,
+ headers: pickSafeResponseHeaders(response.headers),
+ body: responseBody,
+ };
+};
diff --git a/packages/twenty-cli/src/utils/__tests__/read-blob-chunks.spec.ts b/packages/twenty-cli/src/utils/__tests__/read-blob-chunks.spec.ts
new file mode 100644
index 00000000000..67787209beb
--- /dev/null
+++ b/packages/twenty-cli/src/utils/__tests__/read-blob-chunks.spec.ts
@@ -0,0 +1,30 @@
+import { expect, it, vi } from 'vitest';
+
+import { readBlobChunks } from '@/utils/read-blob-chunks';
+
+it.each(['break', 'throw'] as const)(
+ 'cancels the stream when its consumer exits via %s',
+ async (exit) => {
+ const cancel = vi.fn();
+ const stream = new ReadableStream<Uint8Array<ArrayBuffer>>({
+ start(controller) {
+ controller.enqueue(new Uint8Array([1]));
+ },
+ cancel,
+ });
+ const blob = new Blob();
+ vi.spyOn(blob, 'stream').mockReturnValue(stream);
+ const failure = new Error('copy failed');
+ const consume = async () => {
+ for await (const chunk of readBlobChunks(blob)) {
+ expect(chunk).toEqual(new Uint8Array([1]));
+ if (exit === 'throw') throw failure;
+ break;
+ }
+ };
+ if (exit === 'throw') await expect(consume()).rejects.toBe(failure);
+ else await consume();
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(stream.locked).toBe(false);
+ },
+);
diff --git a/packages/twenty-cli/src/utils/get-listening-port.ts b/packages/twenty-cli/src/utils/get-listening-port.ts
new file mode 100644
index 00000000000..7bbad0fdc1f
--- /dev/null
+++ b/packages/twenty-cli/src/utils/get-listening-port.ts
@@ -0,0 +1,14 @@
+import { type Server } from 'node:net';
+
+import { isString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+export const getListeningPort = (server: Server) => {
+ const address = server.address();
+
+ if (!isDefined(address) || isString(address)) {
+ throw new Error('The server is not listening on a TCP port.');
+ }
+
+ return address.port;
+};
diff --git a/packages/twenty-cli/src/utils/has-error-code.ts b/packages/twenty-cli/src/utils/has-error-code.ts
new file mode 100644
index 00000000000..0921c1a83e8
--- /dev/null
+++ b/packages/twenty-cli/src/utils/has-error-code.ts
@@ -0,0 +1,2 @@
+export const hasErrorCode = (error: unknown, code: string) =>
+ error instanceof Error && 'code' in error && error.code === code;
diff --git a/packages/twenty-cli/src/utils/hash-content.ts b/packages/twenty-cli/src/utils/hash-content.ts
new file mode 100644
index 00000000000..a3dd9111d22
--- /dev/null
+++ b/packages/twenty-cli/src/utils/hash-content.ts
@@ -0,0 +1,4 @@
+import { createHash } from 'node:crypto';
+
+export const hashContent = (content: string | Buffer) =>
+ createHash('sha256').update(content).digest('hex');
diff --git a/packages/twenty-cli/src/utils/is-inside-directory.ts b/packages/twenty-cli/src/utils/is-inside-directory.ts
new file mode 100644
index 00000000000..56ca01cd017
--- /dev/null
+++ b/packages/twenty-cli/src/utils/is-inside-directory.ts
@@ -0,0 +1,20 @@
+import { isAbsolute, relative, sep } from 'node:path';
+
+import { isNonEmptyString } from '@sniptt/guards';
+
+export const isInsideDirectory = ({
+ filePath,
+ directory,
+}: {
+ filePath: string;
+ directory: string;
+}) => {
+ const relativePath = relative(directory, filePath);
+
+ return (
+ isNonEmptyString(relativePath) &&
+ relativePath !== '..' &&
+ !relativePath.startsWith(`..${sep}`) &&
+ !isAbsolute(relativePath)
+ );
+};
diff --git a/packages/twenty-cli/src/utils/read-blob-chunks.ts b/packages/twenty-cli/src/utils/read-blob-chunks.ts
new file mode 100644
index 00000000000..7ac2231ab6a
--- /dev/null
+++ b/packages/twenty-cli/src/utils/read-blob-chunks.ts
@@ -0,0 +1,21 @@
+export async function* readBlobChunks(blob: Blob) {
+ const reader = blob.stream().getReader();
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+
+ if (done) return;
+
+ yield value;
+ }
+ } finally {
+ try {
+ await reader.cancel();
+ } catch {
+ // Preserve the original read or consumer error.
+ } finally {
+ reader.releaseLock();
+ }
+ }
+}
diff --git a/packages/twenty-cli/tsconfig.json b/packages/twenty-cli/tsconfig.json
new file mode 100644
index 00000000000..a5499218b31
--- /dev/null
+++ b/packages/twenty-cli/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "allowJs": false,
+ "esModuleInterop": false,
+ "allowSyntheticDefaultImports": true,
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noEmit": true,
+ "target": "es2024",
+ "lib": ["es2024"],
+ "types": ["node"],
+ "paths": {
+ "@/*": ["./src/*"],
+ "@create-twenty-app/*": ["../create-twenty-app/src/*"]
+ }
+ },
+ "include": ["src/**/*.ts", "vite.config.ts", "vitest.config.ts"]
+}
diff --git a/packages/twenty-cli/vite.config.ts b/packages/twenty-cli/vite.config.ts
new file mode 100644
index 00000000000..03394a2b14c
--- /dev/null
+++ b/packages/twenty-cli/vite.config.ts
@@ -0,0 +1,62 @@
+import { cp } from 'node:fs/promises';
+import { builtinModules } from 'node:module';
+import path from 'node:path';
+import { defineConfig } from 'vite';
+
+const NODE_BUILTIN_MODULES = new Set([
+ ...builtinModules,
+ ...builtinModules.map((moduleName) => `node:${moduleName}`),
+]);
+
+export default defineConfig({
+ root: __dirname,
+ plugins: [
+ {
+ name: 'copy-app-template',
+ closeBundle: async () => {
+ await cp(
+ path.resolve(
+ __dirname,
+ '../create-twenty-app/src/constants/template',
+ ),
+ path.resolve(__dirname, 'dist/app-template'),
+ { recursive: true },
+ );
+ await cp(
+ path.resolve(__dirname, 'app-template-overlay'),
+ path.resolve(__dirname, 'dist/app-template-overlay'),
+ { recursive: true },
+ );
+ },
+ },
+ ],
+ cacheDir: '../../node_modules/.vite/packages/twenty-cli',
+ resolve: {
+ alias: {
+ '@/': `${path.resolve(__dirname, 'src')}/`,
+ '@create-twenty-app/': `${path.resolve(__dirname, '../create-twenty-app/src')}/`,
+ },
+ },
+ build: {
+ outDir: 'dist',
+ emptyOutDir: true,
+ target: 'node24',
+ lib: {
+ entry: {
+ cli: 'src/cli.ts',
+ 'app-worker': 'src/app/worker/app-worker.ts',
+ },
+ formats: ['cjs'],
+ },
+ rollupOptions: {
+ external: (id: string) =>
+ NODE_BUILTIN_MODULES.has(id) ||
+ ['chokidar', 'esbuild', 'typescript', 'tinyglobby'].includes(id),
+ output: {
+ entryFileNames: '[name].cjs',
+ chunkFileNames: 'chunks/[name]-[hash].cjs',
+ },
+ },
+ },
+ logLevel: 'warn',
+});
diff --git a/packages/twenty-cli/vitest.config.ts b/packages/twenty-cli/vitest.config.ts
new file mode 100644
index 00000000000..99c7fc76ced
--- /dev/null
+++ b/packages/twenty-cli/vitest.config.ts
@@ -0,0 +1,16 @@
+import path from 'node:path';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ resolve: {
+ alias: {
+ '@/': `${path.resolve(__dirname, 'src')}/`,
+ '@create-twenty-app/': `${path.resolve(__dirname, '../create-twenty-app/src')}/`,
+ },
+ },
+ test: {
+ name: 'twenty-cli',
+ environment: 'node',
+ include: ['src/**/__tests__/**/*.spec.ts'],
+ },
+});
diff --git a/yarn.lock b/yarn.lock
index e914cd9cc34..e2279b6eb8f 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -51040,6 +51040,25 @@ __metadata:
"twenty@workspace:packages/twenty-cli":
version: 0.0.0-use.local
resolution: "twenty@workspace:packages/twenty-cli"
+ dependencies:
+ "@sniptt/guards": "npm:^0.2.0"
+ "@types/node": "npm:^24.0.0"
+ "@types/semver": "npm:^7.5.8"
+ chokidar: "npm:^3.6.0"
+ cjs-module-lexer: "npm:^2.2.0"
+ commander: "npm:^14.0.3"
+ esbuild: "npm:^0.28.1"
+ semver: "npm:7.6.3"
+ tinyglobby: "npm:^0.2.15"
+ twenty-client-sdk: "workspace:*"
+ twenty-shared: "workspace:*"
+ typescript: "npm:^5.9.3"
+ undici: "npm:^7.29.0"
+ uuid: "npm:^13.0.2"
+ vite: "npm:^8.0.0"
+ vitest: "npm:^4.1.0"
+ bin:
+ twenty: dist/cli.cjs
languageName: unknown
linkType: soft