The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(cli): add local environment upgrade and reset (#29302)
Weiko102dd6999f3b
diff --git a/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md b/packages/twenty-agent-skills/references/manage-app/cli-and-sync.mdindex fc18fb1b2bf..430c3e47826 100644--- a/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md+++ b/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md@@ -170,9 +170,13 @@ No app directory or saved remote is required. Login remains separate:Use `local status`, `local logs` and `local stop` to inspect and stop it.`start [version]` preserves existing instances. New instances use the explicitversion, the highest published match for `engines.twenty`, or `latest` when no-range exists.+range exists. `local upgrade [version]` replaces the image while preserving+ports, data volumes and environment overrides. It rejects downgrades and images+without a valid `APP_VERSION` before replacing the existing instance.Use `--test` consistently for the separate test instance on port `2021`.+`local reset` deletes that selected instance and its data, and requires explicit+approval; do not supply `--yes` without the user's authorization to delete it.Stopping an instance preserves data. None of these commands changes remotes.## CI/CDdiff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex d287d89eae4..3a40f19a036 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -41,8 +41,12 @@ to five minutes for `/healthz`. For a new instance, version selection is:explicit version or image tag, the highest published version matching the nearest`package.json`'s `engines.twenty`, then `latest` when no range exists. A failedlookup or unmatched range is an error, never a fallback to another version.+Versions such as `2.53` and `2.53.1` select `v2.53` and `v2.53.1`, respectively;+`2.53` keeps the floating minor tag. Other image tags are used as given.New instances pull the selected image before creation, including when the tag-is cached locally. Existing instances keep their image and port.+is cached locally. Existing instances keep their image and port; use `upgrade` to change versions.+Compatibility with `engines.twenty` uses the existing image's `APP_VERSION`.+A missing, invalid or incompatible version warns without preventing startup.A readiness failure leaves the container and data in place for diagnosis.New instances bind to loopback on port `2020`. Use `--port <port>` when creating@@ -54,6 +58,8 @@ volumes are reused.```bashtwenty local start 2.53.1 --testtwenty local logs --test --lines 100 --no-follow+twenty local upgrade 2.53.1 --test+twenty local reset --test --yes````status` reports `not-created`, `stopped`, `starting` or `healthy`; unavailable@@ -62,8 +68,19 @@ and exits. It supports human or NDJSON output, with a terminal result or error;other local commands support human or JSON output. Ctrl+C cancels the CLIoperation, without stopping the environment or deleting data.-`stop` preserves the container and all data. This development environment is-not a production deployment tool.+`stop` preserves the container and all data. `upgrade [version]` uses the same+version selection as a new start. It pulls the image before stopping the old+instance, then recreates it with the same ports, named volumes and user-provided+environment overrides. The old container is kept until the replacement is created.+If creation fails or is cancelled, the CLI restores the old container and its+previous running state. If the image digest is unchanged, no restart occurs.+Custom storage layouts are rejected. Data volumes survive a failed upgrade,+but database migrations are not automatically rolled back.++`reset` removes the selected container and its database, analytics and file+volumes. It requires confirmation, or `--yes` in scripts. It does not affect+other containers or saved remote credentials. Run `start` afterward for a fresh+instance. This development environment is not a production deployment tool.## Connections and authenticationdiff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.tsindex 9304aeb4a6d..b0482238f35 100644--- a/packages/twenty-cli/src/catalog/command-catalog.ts+++ b/packages/twenty-cli/src/catalog/command-catalog.ts@@ -2,6 +2,8 @@ import { LOCAL_START_COMMAND_DEFINITION } from '@/commands/local/start/local-staimport { LOCAL_STOP_COMMAND_DEFINITION } from '@/commands/local/stop/local-stop.command-definition';import { LOCAL_STATUS_COMMAND_DEFINITION } from '@/commands/local/status/local-status.command-definition';import { LOCAL_LOGS_COMMAND_DEFINITION } from '@/commands/local/environment-logs/local-logs.command-definition';+import { LOCAL_RESET_COMMAND_DEFINITION } from '@/commands/local/reset/local-reset.command-definition';+import { LOCAL_UPGRADE_COMMAND_DEFINITION } from '@/commands/local/upgrade/local-upgrade.command-definition';import { APP_INSTALL_COMMAND_DEFINITION } from '@/commands/app/install/app-install.command-definition';import { APP_PUBLISH_COMMAND_DEFINITION } from '@/commands/app/publish/app-publish.command-definition';import { APP_DEV_COMMAND_DEFINITION } from '@/commands/app/dev/app-dev.command-definition';@@ -44,6 +46,8 @@ export const COMMAND_CATALOG: CommandDefinition[] = [LOCAL_STOP_COMMAND_DEFINITION,LOCAL_STATUS_COMMAND_DEFINITION,LOCAL_LOGS_COMMAND_DEFINITION,+ LOCAL_RESET_COMMAND_DEFINITION,+ LOCAL_UPGRADE_COMMAND_DEFINITION,APP_ADD_COMMAND_DEFINITION,APP_APPLY_COMMAND_DEFINITION,diff --git a/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts b/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.tsindex ddf5c1b9758..e785b06ba91 100644--- a/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts+++ b/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts@@ -5,6 +5,7 @@ import {parseSingleJsonLine,runCliForTest,} from '@/__tests__/utils/run-cli-for-test';+import { getEngineVersionRange } from '@/app/manifest/get-engine-version-range';import { checkLocalHealth } from '@/local/check-local-health';import { waitForLocalHealth } from '@/local/wait-for-local-health';import { getLocalEnvironment } from '@/local/get-local-environment';@@ -12,6 +13,9 @@ import { runDocker } from '@/local/run-docker';import { CliError } from '@/output/cli-error';vi.mock('@/local/run-docker', () => ({ runDocker: vi.fn() }));+vi.mock('@/app/manifest/get-engine-version-range', () => ({+ getEngineVersionRange: vi.fn(),+}));vi.mock('@/local/check-local-health', () => ({checkLocalHealth: vi.fn(),}));@@ -26,17 +30,34 @@ const makeContainer = (isRunning = true) => {};return {Id: 'test-container',+ Image: 'old-image',Config: {Image: 'twentycrm/twenty-app-dev:v2.53.0',+ Env: [+ 'APP_VERSION=2.53.0',+ 'NODE_PORT=2021',+ 'SERVER_URL=http://localhost:12021',+ 'CUSTOM_SETTING=enabled',+ ],},State: { Running: isRunning },HostConfig: {PortBindings: portBindings,},+ Mounts: Object.entries(environment.volumes).map(([Destination, Name]) => ({+ Type: 'volume',+ Destination,+ Name,+ })),};};let container: ReturnType<typeof makeContainer> | undefined;+let previousContainer: ReturnType<typeof makeContainer> | undefined;let failure: string | undefined;+let shouldCancelCreation = false;+let nextImageId: string;+let currentImageVersion: string | undefined;+let nextImageVersion: string | undefined;const runJson = async (args: string[]) => {const result = await runCliForTest(['local', ...args, '--test', '--json']);@@ -46,13 +67,28 @@ const dockerArguments = () =>vi.mocked(runDocker).mock.calls.map(([{ args }]) => args);const mutations = () =>dockerArguments().filter(([command]) =>- ['run', 'start', 'stop', 'pull'].includes(command),+ [+ 'run',+ 'create',+ 'rename',+ 'start',+ 'stop',+ 'pull',+ 'rm',+ 'volume',+ ].includes(command),);describe('local commands', () => {beforeEach(() => {container = makeContainer();+ previousContainer = undefined;failure = undefined;+ shouldCancelCreation = false;+ nextImageId = 'new-image';+ currentImageVersion = '2.53.0';+ nextImageVersion = '2.54.0';+ vi.mocked(getEngineVersionRange).mockReturnValue(null);vi.stubEnv('DOCKER_HOST', '');vi.stubEnv('DOCKER_CONTEXT', '');vi.stubEnv('TWENTY_REMOTE', '');@@ -60,47 +96,99 @@ describe('local commands', () => {vi.stubEnv('TWENTY_API_KEY', '');vi.mocked(checkLocalHealth).mockResolvedValue(true);vi.mocked(waitForLocalHealth).mockResolvedValue(undefined);- vi.mocked(runDocker).mockImplementation(async ({ args, onOutput }) => {- if (args[0] === failure || args.slice(0, 2).join(' ') === failure) {- throw new CliError({- code: 'LOCAL_ENVIRONMENT_FAILED',- message: 'Docker failed',- });- }- if (args[0] === 'context') {- return 'unix:///var/run/docker.sock';- }- if (args[0] === 'info') {- return '28.0';- }- if (args[0] === 'container' && args[1] === 'ls') {- return container?.Id ?? '';- }- if (args[0] === 'container') {- return JSON.stringify(container);- }- if (args[0] === 'start' && isDefined(container)) {- container.State.Running = true;- }- if (args[0] === 'stop' && isDefined(container)) {- container.State.Running = false;- }- if (args[0] === 'run') {- container = makeContainer();- container.Config.Image = args.at(-1)!;- const [, hostPort, internalPort] =- args[args.indexOf('--publish') + 1].split(':');- container.HostConfig.PortBindings = {- [`${internalPort}/tcp`]: [- { HostIp: '127.0.0.1', HostPort: hostPort },- ],- };- }- if (args[0] === 'logs') {- await onOutput?.('server started\nworker ready\n');- }- return '';- });+ vi.mocked(runDocker).mockImplementation(+ async ({ args, onOutput, signal }) => {+ if (args[0] === failure || args.slice(0, 2).join(' ') === failure) {+ throw new CliError({+ code: 'LOCAL_ENVIRONMENT_FAILED',+ message: 'Docker failed',+ });+ }+ if (args[0] === 'context') {+ return 'unix:///var/run/docker.sock';+ }+ if (args[0] === 'info') {+ return '28.0';+ }+ if (args[0] === 'container' && args[1] === 'ls') {+ return container?.Id ?? '';+ }+ if (args[0] === 'container') {+ return JSON.stringify(container);+ }+ if (args[0] === 'image') {+ if (args[3] === '{{.Id}}') {+ return nextImageId;+ }+ if (args.at(-1) === 'old-image') {+ return JSON.stringify([+ ...(isDefined(currentImageVersion)+ ? [`APP_VERSION=${currentImageVersion}`]+ : []),+ 'NODE_PORT=3000',+ ]);+ }+ return JSON.stringify(+ isDefined(nextImageVersion)+ ? [`APP_VERSION=${nextImageVersion}`]+ : [],+ );+ }+ if (args[0] === 'rename') {+ if (args[2] === environment.name) {+ container = previousContainer;+ previousContainer = undefined;+ } else {+ previousContainer = container;+ container = undefined;+ }+ }+ const target =+ args.at(-1) === previousContainer?.Id ? previousContainer : container;+ if (args[0] === 'start' && isDefined(target)) {+ target.State.Running = true;+ }+ if (args[0] === 'stop' && isDefined(target)) {+ target.State.Running = false;+ }+ if (args[0] === 'rm' && target === previousContainer) {+ previousContainer = undefined;+ return '';+ }+ if (args[0] === 'rm') {+ container = undefined;+ return '';+ }+ if (args[0] === 'run' || args[0] === 'create') {+ container = makeContainer(args[0] === 'run');+ container.Id = 'replacement-container';+ container.Config.Image = args.at(-1)!;+ container.Image = nextImageId;+ const [, hostPort, internalPort] =+ args[args.indexOf('--publish') + 1].split(':');+ container.HostConfig.PortBindings = {+ [`${internalPort}/tcp`]: [+ { HostIp: '127.0.0.1', HostPort: hostPort },+ ],+ };+ if (shouldCancelCreation) {+ process.emit('SIGINT');+ signal.throwIfAborted();+ }+ }+ if (args[0] === 'volume' && args[1] === 'ls') {+ return [+ ...Object.values(environment.volumes),+ 'twenty-app-dev-data',+ 'unrelated',+ ].join('\n');+ }+ if (args[0] === 'logs') {+ await onOutput?.('server started\nworker ready\n');+ }+ return '';+ },+ );});afterEach(() => {vi.unstubAllEnvs();@@ -123,11 +211,11 @@ describe('local commands', () => {});const run = mutations().find(([command]) => command === 'run')!;expect(run).toContain('127.0.0.1:12021:12021');- expect(run).toContain('twentycrm/twenty-app-dev:v2.54.0');- expect(run).toContain('twenty-app-dev-test-data:/data/postgres');expect(run).toContain('API_RATE_LIMITING_SHORT_LIMIT=100000');expect(run).toContain('API_RATE_LIMITING_LONG_LIMIT=100000');expect(run).toContain('MARKETPLACE_CATALOG_SYNC_CRON_ENABLED=false');+ expect(run).toContain('twentycrm/twenty-app-dev:v2.54.0');+ expect(run).toContain('twenty-app-dev-test-data:/data/postgres');expect(run).not.toContain('twenty-app-dev-data:/data/postgres');});@@ -146,6 +234,60 @@ describe('local commands', () => {expect(mutations()).toEqual([]);});+ it.each(['start', 'upgrade'])(+ 'uses the floating minor tag for %s 2.53',+ async (command) => {+ if (command === 'start') {+ container = undefined;+ }+ nextImageVersion = '2.53.1';+ expect((await runJson([command, '2.53'])).exitCode).toBe(0);+ expect(mutations()[0]).toEqual([+ 'pull',+ 'twentycrm/twenty-app-dev:v2.53',+ ]);+ expect(container?.Config.Image).toBe('twentycrm/twenty-app-dev:v2.53');+ },+ );++ it.each(['latest', 'v2.53', 'v2.40.0'])(+ 'checks the actual image version behind %s instead of the tag or container overrides',+ async (tag) => {+ vi.mocked(getEngineVersionRange).mockReturnValue('^2.53.0');+ container!.Config.Image = `twentycrm/twenty-app-dev:${tag}`;+ container!.Config.Env[0] = 'APP_VERSION=2.40.0';+ const { exitCode, envelope } = await runJson(['start']);+ expect(exitCode).toBe(0);+ expect(envelope.warnings).toEqual([]);+ expect(mutations()).toEqual([]);+ },+ );++ it.each(['2.52.0', undefined, 'not-a-version'])(+ 'warns without blocking startup when the image version is %s',+ async (version) => {+ vi.mocked(getEngineVersionRange).mockReturnValue('^2.53.0');+ currentImageVersion = version;+ container = makeContainer(false);+ container.Config.Image = 'twentycrm/twenty-app-dev:latest';+ const { exitCode, envelope } = await runJson(['start']);+ expect(exitCode).toBe(0);+ expect(envelope.warnings).toEqual([+ expect.objectContaining({ code: 'LOCAL_VERSION_MISMATCH' }),+ ]);+ expect(mutations()).toEqual([['start', 'test-container']]);+ },+ );++ it('reports Docker inspection failures during the compatibility check', async () => {+ vi.mocked(getEngineVersionRange).mockReturnValue('^2.53.0');+ failure = 'image inspect';+ const { exitCode, envelope } = await runJson(['start']);+ expect(exitCode).toBe(1);+ expect(envelope.error.code).toBe('LOCAL_ENVIRONMENT_FAILED');+ expect(mutations()).toEqual([]);+ });+it('restarts a stopped instance without replacing it or changing its port', async () => {container = makeContainer(false);const { exitCode, envelope } = await runJson(['start']);@@ -201,6 +343,209 @@ describe('local commands', () => {expect(mutations()).toEqual([['stop', 'test-container']]);});+ it('requires explicit approval before reset in JSON mode', async () => {+ const { exitCode, envelope } = await runJson(['reset']);+ expect(exitCode).toBe(2);+ expect(envelope.error.code).toBe('CONFIRMATION_REQUIRED');+ expect(runDocker).not.toHaveBeenCalled();+ });++ it('resets only the selected instance and its known volumes', async () => {+ expect((await runJson(['reset', '--yes'])).exitCode).toBe(0);+ expect(mutations()).toEqual([+ ['rm', '--force', 'test-container'],+ ['volume', 'ls', '--format', '{{.Name}}'],+ ['volume', 'rm', ...Object.values(environment.volumes)],+ ]);+ });++ it.each(['reset', 'upgrade'])(+ 'refuses custom storage before %s changes anything',+ async (command) => {+ container!.Mounts[0].Type = 'bind';+ const { envelope } = await runJson([+ command,+ ...(command === 'reset' ? ['--yes'] : ['2.54.0']),+ ]);+ expect(envelope.error.code).toBe('CONFLICT');+ expect(mutations()).toEqual([]);+ },+ );++ it('refuses to reset a same-name container owned by another image', async () => {+ container!.Config.Image = 'another/service:latest';+ expect((await runJson(['reset', '--yes'])).envelope.error.code).toBe(+ 'CONFLICT',+ );+ expect(mutations()).toEqual([]);+ });++ it('refuses a remote Docker endpoint even for an approved reset', async () => {+ vi.stubEnv('DOCKER_HOST', 'ssh://production');+ expect((await runJson(['reset', '--yes'])).envelope.error.code).toBe(+ 'INVALID_CONFIG',+ );+ expect(runDocker).not.toHaveBeenCalled();+ });++ it('leaves the running instance untouched if the upgrade image cannot be pulled', async () => {+ failure = 'pull';+ expect((await runJson(['upgrade', '2.54.0'])).exitCode).toBe(1);+ expect(mutations()).toEqual([['pull', 'twentycrm/twenty-app-dev:v2.54.0']]);+ expect(container?.State.Running).toBe(true);+ });++ it('does not recreate an instance already on the requested image digest', async () => {+ nextImageId = 'old-image';+ expect(+ (await runJson(['upgrade', '2.54.0'])).envelope.data.isUpgraded,+ ).toBe(false);+ expect(mutations()).toEqual([['pull', 'twentycrm/twenty-app-dev:v2.54.0']]);+ });++ it.each(['2.50.0', 'latest'])(+ 'refuses an older version behind %s before replacing the container',+ async (version) => {+ container!.Config.Image = 'twentycrm/twenty-app-dev:latest';+ container!.Config.Env[0] = 'APP_VERSION=2.40.0';+ const previousSettings = structuredClone(container);+ nextImageVersion = '2.50.0';+ const { exitCode, envelope } = await runJson(['upgrade', version]);+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'CONFLICT',+ message:+ 'Cannot downgrade the local environment from 2.53.0 to 2.50.0.',+ });+ expect(mutations()).toEqual([+ [+ 'pull',+ `twentycrm/twenty-app-dev:${version === 'latest' ? version : `v${version}`}`,+ ],+ ]);+ expect(container).toEqual(previousSettings);+ },+ );++ it.each([undefined, 'not-a-version'])(+ 'leaves the instance untouched if the image version is %s',+ async (version) => {+ const previousSettings = structuredClone(container);+ nextImageVersion = version;+ const { envelope } = await runJson(['upgrade', 'latest']);+ expect(envelope.error.code).toBe('INVALID_RESPONSE');+ expect(container).toEqual(previousSettings);+ expect(mutations()).toEqual([+ ['pull', 'twentycrm/twenty-app-dev:latest'],+ ]);+ },+ );++ it('allows a rebuilt image of the same version', async () => {+ nextImageVersion = '2.53.0';+ expect(+ (await runJson(['upgrade', '2.53.0'])).envelope.data.isUpgraded,+ ).toBe(true);+ });++ it('upgrades gracefully, preserving volumes, port mapping and user overrides without stale image defaults', async () => {+ container!.Config.Env.push(+ 'API_RATE_LIMITING_SHORT_LIMIT=50',+ 'MARKETPLACE_CATALOG_SYNC_CRON_ENABLED=true',+ );+ const { exitCode, envelope } = await runJson(['upgrade', '2.54.0']);+ expect(exitCode).toBe(0);+ expect(envelope.data).toMatchObject({+ isUpgraded: true,+ isDataPreserved: true,+ url: 'http://localhost:12021',+ });+ expect(mutations().slice(0, 3)).toEqual([+ ['pull', 'twentycrm/twenty-app-dev:v2.54.0'],+ ['rename', 'test-container', 'twenty-app-dev-test-previous'],+ ['stop', '--time', '30', 'test-container'],+ ]);+ expect(mutations().slice(-2)).toEqual([+ ['rm', 'test-container'],+ ['start', environment.name],+ ]);+ const run = mutations()[3];+ expect(run[0]).toBe('create');+ expect(run).toContain('127.0.0.1:12021:2021');+ expect(run).toContain('twenty-app-dev-test-data:/data/postgres');+ expect(run).toContain('CUSTOM_SETTING=enabled');+ expect(run).toContain('API_RATE_LIMITING_SHORT_LIMIT=50');+ expect(run).toContain('MARKETPLACE_CATALOG_SYNC_CRON_ENABLED=true');+ expect(run).not.toContain('API_RATE_LIMITING_SHORT_LIMIT=100000');+ expect(run.filter((value) => value.startsWith('SERVER_URL='))).toEqual([+ 'SERVER_URL=http://localhost:12021',+ ]);+ expect(run).not.toContain('APP_VERSION=2.53.0');+ expect(run).not.toContain('APP_VERSION=2.54.0');+ });++ it.each([true, false])(+ 'restores the previous settings after creation fails (running: %s)',+ async (isRunning) => {+ container = makeContainer(isRunning);+ const previousSettings = structuredClone(container);+ failure = 'create';+ expect((await runJson(['upgrade', '2.54.0'])).exitCode).toBe(1);+ expect(container).toEqual(previousSettings);+ expect(previousContainer).toBeUndefined();+ expect(mutations()).not.toContainEqual(['rm', 'test-container']);+ },+ );++ it('restores the old container after cancellation during replacement creation', async () => {+ const previousSettings = structuredClone(container);+ shouldCancelCreation = true;+ const { exitCode, envelope } = await runJson(['upgrade', '2.54.0']);+ expect(exitCode).toBe(130);+ expect(envelope.error.code).toBe('CANCELLED');+ expect(container).toEqual(previousSettings);+ expect(previousContainer).toBeUndefined();+ expect(mutations()).toContainEqual(['rm', 'replacement-container']);+ const recoveryCalls = vi+ .mocked(runDocker)+ .mock.calls.filter(+ ([{ args }]) =>+ args[0] === 'rm' ||+ (args[0] === 'rename' && args[2] === environment.name),+ );+ expect(recoveryCalls.every(([{ signal }]) => !signal.aborted)).toBe(true);+ });++ it('does not roll back to the old image after starting new database migrations', async () => {+ vi.mocked(waitForLocalHealth).mockRejectedValue(+ new CliError({ code: 'TIMEOUT', message: 'Not ready' }),+ );+ expect((await runJson(['upgrade', '2.54.0'])).envelope.error.code).toBe(+ 'TIMEOUT',+ );+ expect(container?.Config.Image).toBe('twentycrm/twenty-app-dev:v2.54.0');+ expect(previousContainer).toBeUndefined();+ expect(mutations()).not.toContainEqual(['start', 'test-container']);+ });++ it('preserves older SDK volumes while adding storage for the current image', async () => {+ container!.Mounts = container!.Mounts.filter(+ (mount) => mount.Destination !== '/data/clickhouse',+ );+ expect((await runJson(['upgrade', '2.54.0'])).exitCode).toBe(0);+ const run = mutations().find(([command]) => command === 'create')!;+ expect(run).toContain('twenty-app-dev-test-data:/data/postgres');+ expect(run).toContain(+ 'twenty-app-dev-test-storage:/app/packages/twenty-server/.local-storage',+ );+ expect(run).toContain('twenty-app-dev-test-clickhouse:/data/clickhouse');+ });++ it('does not report reset success when Docker cannot delete a volume', async () => {+ failure = 'volume rm';+ expect((await runJson(['reset', '--yes'])).exitCode).toBe(1);+ });+it('rejects malformed port bindings before changing the container', async () => {container!.HostConfig.PortBindings = {};expect((await runJson(['start'])).envelope.error.code).toBe('CONFLICT');diff --git a/packages/twenty-cli/src/commands/local/reset/local-reset.command-definition.ts b/packages/twenty-cli/src/commands/local/reset/local-reset.command-definition.tsnew file mode 100644index 00000000000..2cbf47b4069--- /dev/null+++ b/packages/twenty-cli/src/commands/local/reset/local-reset.command-definition.ts@@ -0,0 +1,24 @@+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';++export const LOCAL_RESET_COMMAND_DEFINITION: LocalCommandDefinition = {+ path: ['local', 'reset'],+ description: 'Delete the local environment and all its data',+ options: [+ {+ flags: '--yes',+ description: 'Delete the local environment and its data without asking',+ },+ {+ flags: '--test',+ description: 'Use the separate local test instance',+ },+ ],+ examples: ['twenty local reset', 'twenty local reset --test --yes'],+ outputModes: ['human', 'json'],+ writes: true,+ needsProject: false,+ needsTarget: false,+ load: async () =>+ (await import('@/commands/local/reset/run-local-reset-command'))+ .runLocalResetCommand,+};diff --git a/packages/twenty-cli/src/commands/local/reset/run-local-reset-command.ts b/packages/twenty-cli/src/commands/local/reset/run-local-reset-command.tsnew file mode 100644index 00000000000..0a63ef9cd1c--- /dev/null+++ b/packages/twenty-cli/src/commands/local/reset/run-local-reset-command.ts@@ -0,0 +1,53 @@+import { isDefined } from 'twenty-shared/utils';++import { readBooleanOption } from '@/catalog/read-command-values';+import { type CommandRun } from '@/catalog/types/command-run.type';+import { type CommandContext } from '@/catalog/types/command-context.type';+import { requireApproval } from '@/app/deployment/require-approval';+import { checkLocalRuntime } from '@/local/check-local-runtime';+import { readLocalOptions } from '@/local/read-local-options';+import {+ assertLocalStorage,+ readLocalContainer,+} from '@/local/read-local-container';+import { runDocker } from '@/local/run-docker';+import { isInteractionAllowed } from '@/program/is-interaction-allowed';++export const runLocalResetCommand: CommandRun<CommandContext> = async ({+ options,+ outputMode,+ signal,+}) => {+ const { environment } = readLocalOptions(options);+ await requireApproval({+ isApproved: readBooleanOption(options, 'yes'),+ canPrompt: isInteractionAllowed({ options, outputMode }),+ question: `Delete ${environment.name} and all its database, file and analytics data?`,+ code: 'CONFIRMATION_REQUIRED',+ message: `Reset permanently deletes all data in ${environment.name}.`,+ hint: 'Pass --yes to delete this local environment and its data.',+ declinedMessage: 'Local environment reset cancelled.',+ signal,+ });+ await checkLocalRuntime(signal);+ const container = await readLocalContainer({ environment, signal });+ if (isDefined(container)) {+ assertLocalStorage({ environment, container });+ await runDocker({ args: ['rm', '--force', container.id], signal });+ }+ const existingVolumes = (+ await runDocker({ args: ['volume', 'ls', '--format', '{{.Name}}'], signal })+ )+ .trim()+ .split('\n');+ const volumes = Object.values(environment.volumes).filter((name) =>+ existingVolumes.includes(name),+ );+ if (volumes.length > 0) {+ await runDocker({ args: ['volume', 'rm', ...volumes], signal });+ }+ return {+ data: { name: environment.name, reset: true, removedVolumes: volumes },+ human: `Local environment data deleted. Run twenty local start${options.test ? ' --test' : ''} to create a fresh instance.`,+ };+};diff --git a/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts b/packages/twenty-cli/src/commands/local/start/run-local-start-command.tsindex e6a6cdd1faf..9669482ad4f 100644--- a/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts+++ b/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts@@ -1,5 +1,4 @@import satisfies from 'semver/functions/satisfies';-import valid from 'semver/functions/valid';import { isDefined } from 'twenty-shared/utils';import { readStringArgument } from '@/catalog/read-command-values';@@ -9,6 +8,7 @@ import { checkLocalRuntime } from '@/local/check-local-runtime';import { createLocalContainer } from '@/local/create-local-container';import { readLocalOptions } from '@/local/read-local-options';import { readLocalContainer } from '@/local/read-local-container';+import { readLocalImageVersion } from '@/local/read-local-image-version';import { getLocalEngineRange } from '@/local/get-local-engine-range';import { getLocalImage } from '@/local/get-local-image';import { resolveLocalImage } from '@/local/resolve-local-image';@@ -40,21 +40,31 @@ export const runLocalStartCommand: CommandRun<CommandContext> = async ({throw new CliError({code: 'CONFLICT',message: `${environment.name} already uses ${existing.image} on port ${existing.port}.`,- hint: 'Omit the version and --port options to reuse this instance.',+ hint: 'Omit --port to reuse this instance. Use twenty local upgrade to change its version.',});}const range = isDefined(existing) ? getLocalEngineRange() : undefined;- const existingVersion = valid(existing?.image.split(':').at(-1));- if (- isDefined(existing) &&- isDefined(range) &&- (!isDefined(existingVersion) || !satisfies(existingVersion, range))- ) {- output.warn({- code: 'LOCAL_VERSION_MISMATCH',- message: `The existing image ${existing.image} does not establish compatibility with engines.twenty ${range}.`,- });+ if (isDefined(existing) && isDefined(range)) {+ let existingVersion: string | undefined;+ try {+ existingVersion = await readLocalImageVersion({+ imageId: existing.imageId,+ signal,+ });+ } catch (error) {+ signal.throwIfAborted();+ if (!(error instanceof CliError) || error.code !== 'INVALID_RESPONSE') {+ throw error;+ }+ }++ if (!isDefined(existingVersion) || !satisfies(existingVersion, range)) {+ output.warn({+ code: 'LOCAL_VERSION_MISMATCH',+ message: `The existing image ${existing.image} does not establish compatibility with engines.twenty ${range}. Use twenty local upgrade to change version.`,+ });+ }}if (isDefined(existing) && !existing.isRunning) {diff --git a/packages/twenty-cli/src/commands/local/upgrade/local-upgrade.command-definition.ts b/packages/twenty-cli/src/commands/local/upgrade/local-upgrade.command-definition.tsnew file mode 100644index 00000000000..afd8e9f8dd1--- /dev/null+++ b/packages/twenty-cli/src/commands/local/upgrade/local-upgrade.command-definition.ts@@ -0,0 +1,28 @@+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';++export const LOCAL_UPGRADE_COMMAND_DEFINITION: LocalCommandDefinition = {+ path: ['local', 'upgrade'],+ description: 'Upgrade the local environment, preserving its data volumes',+ options: [+ {+ flags: '--test',+ description: 'Use the separate local test instance',+ },+ ],+ arguments: [+ {+ name: 'version',+ description:+ 'Twenty version or image tag (default: engines.twenty, then latest)',+ required: false,+ },+ ],+ examples: ['twenty local upgrade', 'twenty local upgrade 2.53.1 --test'],+ outputModes: ['human', 'json'],+ writes: true,+ needsProject: false,+ needsTarget: false,+ load: async () =>+ (await import('@/commands/local/upgrade/run-local-upgrade-command'))+ .runLocalUpgradeCommand,+};diff --git a/packages/twenty-cli/src/commands/local/upgrade/run-local-upgrade-command.ts b/packages/twenty-cli/src/commands/local/upgrade/run-local-upgrade-command.tsnew file mode 100644index 00000000000..9311dc67912--- /dev/null+++ b/packages/twenty-cli/src/commands/local/upgrade/run-local-upgrade-command.ts@@ -0,0 +1,96 @@+import isLessThan from 'semver/functions/lt';+import { isDefined } from 'twenty-shared/utils';+import { readStringArgument } from '@/catalog/read-command-values';+import { type CommandRun } from '@/catalog/types/command-run.type';+import { type CommandContext } from '@/catalog/types/command-context.type';+import { checkLocalRuntime } from '@/local/check-local-runtime';+import { readLocalImageVersion } from '@/local/read-local-image-version';+import { replaceLocalContainer } from '@/local/replace-local-container';+import { getLocalStatus } from '@/local/get-local-status';+import { readLocalOptions } from '@/local/read-local-options';+import {+ assertLocalStorage,+ readLocalContainer,+} from '@/local/read-local-container';+import { readLocalEnvironmentOverrides } from '@/local/read-local-environment-overrides';+import { waitForLocalEnvironment } from '@/local/wait-for-local-environment';+import { resolveLocalImage } from '@/local/resolve-local-image';+import { runDocker } from '@/local/run-docker';+import { CliError } from '@/output/cli-error';++export const runLocalUpgradeCommand: CommandRun<CommandContext> = async ({+ options,+ arguments: commandArguments,+ output,+ signal,+}) => {+ const { environment } = readLocalOptions(options);+ await checkLocalRuntime(signal);+ const existing = await readLocalContainer({ environment, signal });+ if (!isDefined(existing)) {+ throw new CliError({+ code: 'NOT_FOUND',+ message: 'No local environment has been created.',+ hint: 'Use twenty local start with the desired version first.',+ });+ }+ assertLocalStorage({ environment, container: existing });+ const image = await resolveLocalImage({+ version: readStringArgument(commandArguments, 0),+ signal,+ });+ output.progress({ message: `Pulling ${image}…` });+ await runDocker({ args: ['pull', image], signal });+ const nextImageId = (+ await runDocker({+ args: ['image', 'inspect', '--format', '{{.Id}}', image],+ signal,+ })+ ).trim();+ if (existing.imageId === nextImageId) {+ return {+ data: {+ ...(await getLocalStatus({ environment, container: existing, signal })),+ isUpgraded: false,+ },+ human: `Already using ${image}.`,+ };+ }+ const currentVersion = await readLocalImageVersion({+ imageId: existing.imageId,+ signal,+ });+ const nextVersion = await readLocalImageVersion({+ imageId: nextImageId,+ signal,+ });+ if (isLessThan(nextVersion, currentVersion)) {+ throw new CliError({+ code: 'CONFLICT',+ message: `Cannot downgrade the local environment from ${currentVersion} to ${nextVersion}.`,+ hint: 'Database migrations cannot be rolled back. Keep the current version or use a newer one.',+ });+ }+ const environmentVariables = await readLocalEnvironmentOverrides({+ container: existing,+ signal,+ });+ output.progress({+ message: 'Replacing the local environment, preserving its data volumes…',+ });+ await replaceLocalContainer({+ environment,+ existing,+ image,+ environmentVariables,+ signal,+ });+ const data = await waitForLocalEnvironment({+ environment: { ...environment, port: existing.port },+ signal,+ });+ return {+ data: { ...data, isUpgraded: true, isDataPreserved: true },+ human: `Local environment upgraded to ${image} at ${data.url}. Data volumes preserved.`,+ };+};diff --git a/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts b/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.tsindex a6bf35d9f35..908dd7cdacb 100644--- a/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts+++ b/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts@@ -18,6 +18,21 @@ afterEach(() => {});describe('local image selection', () => {+ it.each([+ ['2.53', 'v2.53'],+ ['v2.53', 'v2.53'],+ ['2.53.1', 'v2.53.1'],+ ['v2.53.1', 'v2.53.1'],+ ['2.54.0-beta.1', 'v2.54.0-beta.1'],+ ['latest', 'latest'],+ ['nightly', 'nightly'],+ ])('resolves explicit version %s to tag %s', async (version, tag) => {+ expect(await resolveLocalImage({ version, signal })).toBe(+ `twentycrm/twenty-app-dev:${tag}`,+ );+ expect(fetchWithProxy).not.toHaveBeenCalled();+ });+it('selects the highest compatible published version across pages', async () => {vi.mocked(getEngineVersionRange).mockReturnValue('^2.52.0');vi.mocked(fetchWithProxy)diff --git a/packages/twenty-cli/src/local/create-local-container.ts b/packages/twenty-cli/src/local/create-local-container.tsindex d6bd87f0fce..a93c6605115 100644--- a/packages/twenty-cli/src/local/create-local-container.ts+++ b/packages/twenty-cli/src/local/create-local-container.ts@@ -5,6 +5,9 @@ export const createLocalContainer = async ({environment,image,port,+ containerPort = port,+ environmentVariables = environment.environmentVariables,+ shouldStart = true,signal,}: {environment: Pick<@@ -13,21 +16,24 @@ export const createLocalContainer = async ({>;image: string;port: number;+ containerPort?: number;+ environmentVariables?: string[];+ shouldStart?: boolean;signal: AbortSignal;-}) =>- runDocker({+}) => {+ const variables = [`NODE_PORT=${containerPort}`, ...environmentVariables];+ if (!environmentVariables.some((value) => value.startsWith('SERVER_URL='))) {+ variables.push(`SERVER_URL=http://localhost:${port}`);+ }++ return runDocker({args: [- 'run',- '--detach',+ ...(shouldStart ? ['run', '--detach'] : ['create']),'--name',environment.name,'--publish',- `127.0.0.1:${port}:${port}`,- '--env',- `NODE_PORT=${port}`,- '--env',- `SERVER_URL=http://localhost:${port}`,- ...environment.environmentVariables.flatMap((value) => ['--env', value]),+ `127.0.0.1:${port}:${containerPort}`,+ ...variables.flatMap((value) => ['--env', value]),...Object.entries(environment.volumes).flatMap(([destination, name]) => ['--volume',`${name}:${destination}`,@@ -36,3 +42,4 @@ export const createLocalContainer = async ({],signal,});+};diff --git a/packages/twenty-cli/src/local/get-local-environment.ts b/packages/twenty-cli/src/local/get-local-environment.tsindex 95c5083ded4..620f6662a93 100644--- a/packages/twenty-cli/src/local/get-local-environment.ts+++ b/packages/twenty-cli/src/local/get-local-environment.ts@@ -8,6 +8,16 @@ const LOCAL_TEST_ENVIRONMENT_VARIABLES = ['API_RATE_LIMITING_LONG_LIMIT=100000',];+const LOCAL_VOLUME_DEFINITIONS = [+ { destination: '/data/postgres', suffix: 'data', isRequired: true },+ { destination: '/data/clickhouse', suffix: 'clickhouse', isRequired: false },+ {+ destination: '/app/packages/twenty-server/.local-storage',+ suffix: 'storage',+ isRequired: true,+ },+];+export const getLocalEnvironment = (isTest: boolean): LocalEnvironment => {const name = isTest ? 'twenty-app-dev-test' : 'twenty-app-dev';@@ -15,10 +25,14 @@ export const getLocalEnvironment = (isTest: boolean): LocalEnvironment => {name,port: isTest ? 2021 : 2020,environmentVariables: isTest ? [...LOCAL_TEST_ENVIRONMENT_VARIABLES] : [],- volumes: {- '/data/postgres': `${name}-data`,- '/data/clickhouse': `${name}-clickhouse`,- '/app/packages/twenty-server/.local-storage': `${name}-storage`,- },+ volumes: Object.fromEntries(+ LOCAL_VOLUME_DEFINITIONS.map(({ destination, suffix }) => [+ destination,+ `${name}-${suffix}`,+ ]),+ ),+ requiredVolumeDestinations: LOCAL_VOLUME_DEFINITIONS.filter(+ ({ isRequired }) => isRequired,+ ).map(({ destination }) => destination),};};diff --git a/packages/twenty-cli/src/local/get-local-image.ts b/packages/twenty-cli/src/local/get-local-image.tsindex ef133b42e5c..62ced4dab12 100644--- a/packages/twenty-cli/src/local/get-local-image.ts+++ b/packages/twenty-cli/src/local/get-local-image.ts@@ -5,7 +5,8 @@ import { LOCAL_IMAGE_REPOSITORY } from '@/local/get-local-environment';import { CliError } from '@/output/cli-error';export const getLocalImage = (version: string) => {- const normalized = valid(version);+ const normalized =+ valid(version) ?? (/^\d+\.\d+$/.test(version) ? version : undefined);const tag = isDefined(normalized) ? `v${normalized}` : version;if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/.test(tag)) {diff --git a/packages/twenty-cli/src/local/read-local-container.ts b/packages/twenty-cli/src/local/read-local-container.tsindex 6008fd3373c..143c011ef76 100644--- a/packages/twenty-cli/src/local/read-local-container.ts+++ b/packages/twenty-cli/src/local/read-local-container.ts@@ -1,5 +1,5 @@-import { isBoolean, isNonEmptyString, isString } from '@sniptt/guards';-import { isPlainObject } from 'twenty-shared/utils';+import { isArray, isBoolean, isNonEmptyString, isString } from '@sniptt/guards';+import { isDefined, isPlainObject } from 'twenty-shared/utils';import { LOCAL_IMAGE_REPOSITORY } from '@/local/get-local-environment';import { readLocalContainerPorts } from '@/local/read-local-container-ports';@@ -46,12 +46,16 @@ export const readLocalContainer = async ({if (!isPlainObject(value) ||!isString(value.Id) ||+ !isString(value.Image) ||!isPlainObject(value.Config) ||!isString(value.Config.Image) ||+ !isArray(value.Config.Env) ||+ !value.Config.Env.every(isString) ||!isPlainObject(value.State) ||!isBoolean(value.State.Running) ||!isPlainObject(value.HostConfig) ||- !isPlainObject(value.HostConfig.PortBindings)+ !isPlainObject(value.HostConfig.PortBindings) ||+ !isArray(value.Mounts)) {throw new CliError({code: 'INVALID_RESPONSE',@@ -72,15 +76,66 @@ export const readLocalContainer = async ({});}- const { port } = readLocalContainerPorts({+ const { port, containerPort } = readLocalContainerPorts({containerName: environment.name,portBindings: value.HostConfig.PortBindings,});+ const mounts = value.Mounts.map((mount: unknown) => {+ if (+ !isPlainObject(mount) ||+ !isString(mount.Type) ||+ !isString(mount.Destination) ||+ (isDefined(mount.Name) && !isString(mount.Name))+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'Docker returned an invalid mount description.',+ });+ }+ return {+ Type: mount.Type,+ Destination: mount.Destination,+ Name: isString(mount.Name) ? mount.Name : undefined,+ };+ });+return {id: value.Id,image,+ imageId: value.Image,+ environmentVariables: value.Config.Env,isRunning: value.State.Running,port,+ containerPort,+ mounts,};};++export const assertLocalStorage = ({+ environment,+ container,+}: {+ environment: Pick<+ LocalEnvironment,+ 'name' | 'volumes' | 'requiredVolumeDestinations'+ >;+ container: Pick<LocalContainer, 'mounts'>;+}) => {+ if (+ !environment.requiredVolumeDestinations.every((destination) =>+ container.mounts.some((mount) => mount.Destination === destination),+ ) ||+ container.mounts.some(+ (mount) =>+ mount.Type !== 'volume' ||+ environment.volumes[mount.Destination] !== mount.Name,+ )+ ) {+ throw new CliError({+ code: 'CONFLICT',+ message: `${environment.name} uses custom storage.`,+ hint: 'Manage this container directly with Docker to preserve its storage configuration.',+ });+ }+};diff --git a/packages/twenty-cli/src/local/read-local-environment-overrides.ts b/packages/twenty-cli/src/local/read-local-environment-overrides.tsnew file mode 100644index 00000000000..392da698c12--- /dev/null+++ b/packages/twenty-cli/src/local/read-local-environment-overrides.ts@@ -0,0 +1,19 @@+import { readLocalImageEnvironment } from '@/local/read-local-image-environment';+import { type LocalContainer } from '@/local/types/local-environment.type';++export const readLocalEnvironmentOverrides = async ({+ container,+ signal,+}: {+ container: Pick<LocalContainer, 'imageId' | 'environmentVariables'>;+ signal: AbortSignal;+}): Promise<string[]> => {+ const defaults = await readLocalImageEnvironment({+ imageId: container.imageId,+ signal,+ });++ return container.environmentVariables.filter(+ (value) => !value.startsWith('NODE_PORT=') && !defaults.includes(value),+ );+};diff --git a/packages/twenty-cli/src/local/read-local-image-environment.ts b/packages/twenty-cli/src/local/read-local-image-environment.tsnew file mode 100644index 00000000000..9014c3c81a1--- /dev/null+++ b/packages/twenty-cli/src/local/read-local-image-environment.ts@@ -0,0 +1,27 @@+import { isArray, isString } from '@sniptt/guards';++import { runDocker } from '@/local/run-docker';+import { CliError } from '@/output/cli-error';++export const readLocalImageEnvironment = async ({+ imageId,+ signal,+}: {+ imageId: string;+ signal: AbortSignal;+}): Promise<string[]> => {+ const defaults: unknown = JSON.parse(+ await runDocker({+ args: ['image', 'inspect', '--format', '{{json .Config.Env}}', imageId],+ signal,+ }),+ );+ if (!isArray(defaults) || !defaults.every(isString)) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'Docker returned invalid image environment variables.',+ });+ }++ return defaults;+};diff --git a/packages/twenty-cli/src/local/read-local-image-version.ts b/packages/twenty-cli/src/local/read-local-image-version.tsnew file mode 100644index 00000000000..76996757e48--- /dev/null+++ b/packages/twenty-cli/src/local/read-local-image-version.ts@@ -0,0 +1,33 @@+import valid from 'semver/functions/valid';+import { isDefined } from 'twenty-shared/utils';++import { readLocalImageEnvironment } from '@/local/read-local-image-environment';+import { CliError } from '@/output/cli-error';++export const readLocalImageVersion = async ({+ imageId,+ signal,+}: {+ imageId: string;+ signal: AbortSignal;+}) => {+ const environmentVariables = await readLocalImageEnvironment({+ imageId,+ signal,+ });+ const version = valid(+ environmentVariables+ .find((value) => value.startsWith('APP_VERSION='))+ ?.slice('APP_VERSION='.length),+ );++ if (!isDefined(version)) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: `Cannot determine the Twenty version of image ${imageId}.`,+ hint: 'Upgrade requires images with a valid APP_VERSION to prevent database downgrades. The existing instance is unchanged.',+ });+ }++ return version;+};diff --git a/packages/twenty-cli/src/local/replace-local-container.ts b/packages/twenty-cli/src/local/replace-local-container.tsnew file mode 100644index 00000000000..4b2882ac45c--- /dev/null+++ b/packages/twenty-cli/src/local/replace-local-container.ts@@ -0,0 +1,82 @@+import { isDefined } from 'twenty-shared/utils';++import { createLocalContainer } from '@/local/create-local-container';+import { readLocalContainer } from '@/local/read-local-container';+import { runDocker } from '@/local/run-docker';+import {+ type LocalContainer,+ type LocalEnvironment,+} from '@/local/types/local-environment.type';+import { CliError } from '@/output/cli-error';++export const replaceLocalContainer = async ({+ environment,+ existing,+ image,+ environmentVariables,+ signal,+}: {+ environment: LocalEnvironment;+ existing: Pick<LocalContainer, 'id' | 'isRunning' | 'port' | 'containerPort'>;+ image: string;+ environmentVariables: string[];+ signal: AbortSignal;+}) => {+ const previousName = `${environment.name}-previous`;+ try {+ await runDocker({ args: ['rename', existing.id, previousName], signal });+ if (existing.isRunning) {+ await runDocker({ args: ['stop', '--time', '30', existing.id], signal });+ }+ await createLocalContainer({+ environment,+ image,+ port: existing.port,+ containerPort: existing.containerPort,+ environmentVariables,+ shouldStart: false,+ signal,+ });+ } catch (error) {+ const recoverySignal = AbortSignal.timeout(60_000);+ try {+ const current = await readLocalContainer({+ environment,+ signal: recoverySignal,+ });+ if (isDefined(current) && current.id !== existing.id) {+ await runDocker({ args: ['rm', current.id], signal: recoverySignal });+ }+ if (current?.id !== existing.id) {+ await runDocker({+ args: ['rename', existing.id, environment.name],+ signal: recoverySignal,+ });+ }+ if (existing.isRunning) {+ await runDocker({+ args: ['start', existing.id],+ signal: recoverySignal,+ });+ }+ } catch (recoveryError) {+ throw new CliError({+ code: 'LOCAL_ENVIRONMENT_FAILED',+ message:+ 'Upgrade failed and the previous container could not be restored automatically.',+ hint: `The previous settings remain in container ${existing.id}. Inspect it with docker inspect before retrying.`,+ cause: recoveryError,+ details: {+ originalError: error instanceof Error ? error.message : String(error),+ },+ });+ }+ throw error;+ }++ await runDocker({+ args: ['rm', existing.id],+ signal: AbortSignal.timeout(60_000),+ });+ await runDocker({ args: ['start', environment.name], signal });+};diff --git a/packages/twenty-cli/src/local/types/local-environment.type.ts b/packages/twenty-cli/src/local/types/local-environment.type.tsindex fcd56c082c7..6e68fc5edff 100644--- a/packages/twenty-cli/src/local/types/local-environment.type.ts+++ b/packages/twenty-cli/src/local/types/local-environment.type.ts@@ -2,12 +2,17 @@ export type LocalEnvironment = {name: string;port: number;volumes: Record<string, string>;+ requiredVolumeDestinations: string[];environmentVariables: string[];};export type LocalContainer = {id: string;image: string;+ imageId: string;+ environmentVariables: string[];isRunning: boolean;port: number;+ containerPort: number;+ mounts: { Type: string; Name?: string; Destination: string }[];};diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdxindex 072ba0798ce..f48833e069c 100644--- a/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx+++ b/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx@@ -22,6 +22,9 @@ separate step. To install your app afterward, run `twenty app apply --createFor a new instance, pass a version explicitly or let the CLI select the highestpublished version matching your app's `engines.twenty`. Outside an app with thatsetting, it uses `latest`. Existing instances keep their version and data.+For an existing instance, compatibility with `engines.twenty` is checked using+the image's `APP_VERSION`, including when its tag is `latest`. A missing, invalid+or incompatible version produces a warning and startup continues.```bashtwenty local start 2.53.1@@ -35,7 +38,36 @@ New instances listen only on loopback, on port `2020`. Use `--port <port>` whencreating an instance to choose another port. Use a local Docker socket context;remote Docker engines are not supported by these commands.-`stop` keeps the container and all data.+## Upgrade or reset++```bash+twenty local upgrade 2.53.1+```++Upgrade pulls the requested image before replacing the instance. It preserves+its ports, database and file volumes, and environment overrides. New CLI defaults+apply to newly created instances; upgrades preserve existing environment values.+Without a version, it follows the same version selection as a new start. Custom storage+layouts are rejected. Downgrades are rejected before replacing the container,+including when using a tag such as `latest`. Both images must declare a valid+`APP_VERSION` so the CLI can compare their actual versions.++Pass `2.53` to start or upgrade using the floating `v2.53` image tag, or `2.53.1`+to select a specific patch version.++If replacement creation fails or is cancelled, the CLI+restores the previous container and settings. Once the new version starts,+failed upgrades retain data volumes but do not roll back database migrations.++`stop` keeps all data. To permanently delete the instance and its data, run:++```bash+twenty local reset+twenty local start+```++Reset asks for confirmation. Scripts must pass `--yes`. Saved remotes and+credentials are not removed.## Integration tests@@ -49,7 +81,7 @@ TWENTY_API_URL=http://localhost:2021 yarn testSet `TWENTY_API_KEY` to a key for that instance. Integration tests install anduninstall an app, so keep them separate from your development workspace.-Pass `--test` to logs or stop when managing this instance.+Pass `--test` to logs, stop, upgrade or reset when managing this instance.The generated CI workflow provisions an isolated instance through`twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test@main` and installs thediff --git a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx b/packages/twenty-docs/developers/extend/apps/operations/cli.mdxindex 2e9f52a072e..9456b6866cb 100644--- a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx+++ b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx@@ -33,7 +33,7 @@ The examples below use `twenty`. Prefix them with `npx twenty@latest` if you did| `api` | Send raw REST or GraphQL requests || `open` | Open the workspace in your browser || `app` | Create, build, sync, debug and uninstall apps |-| `local` | Start, inspect and stop a local development environment |+| `local` | Start, inspect, stop, upgrade and reset a local development environment || `doctor` | Diagnose the CLI, app SDK and workspace connection |Every command that talks to a workspace accepts `--remote <name>` to target a saved connection other than the default one, and `--json` for structured output.