The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Only delete workspace Custom application entities on an explicit --prune (#29047)
Félix Malfait3f5fb1978d91
diff --git a/packages/twenty-cli/README.md b/packages/twenty-cli/README.mdindex 7ff41223a36..29746687958 100644--- a/packages/twenty-cli/README.md+++ b/packages/twenty-cli/README.md@@ -53,8 +53,8 @@ app, uploads its build and synchronizes its metadata. Once registered, inspectchanges with `twenty app plan` before applying them. `app dev` watches inputs andsyncs successful builds.-Missing definitions imply remote deletions by default. Pass `--no-delete` to-preserve them. Object and field deletions require confirmation because they+Missing definitions imply remote deletions by default. Pass `--no-prune` to+preserve them. The workspace custom application only deletes them with `--prune`. Object and field deletions require confirmation because theyalso delete stored data. Pull can overwrite local edits; read its[reconciliation rules](docs/commands.md#pull-an-app) before using it.diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex fbccbf5f591..f3da5b3d2da 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -310,27 +310,29 @@ and inspect the changes before applying an app with a different tooling version.```bashtwenty app plan --remote dev-twenty app plan --path ./apps/billing --no-delete --json+twenty app plan --path ./apps/billing --no-prune --json+twenty app plan --prune````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 plan.+Entities missing from source are included as deletions by default, except for the workspace custom application, which keeps them unless you pass `--prune`. `--no-prune` passes `inferDeletionFromMissingEntities: false` to the preview and `--prune` passes `true`; without either the argument is omitted and the server decides. Servers released before `--prune` existed treat an omitted argument as `true`, so pass `--no-prune` to keep entities against them. The deprecated `--no-delete` still works as `--no-prune` with a `DEPRECATED_OPTION` warning; an explicit `--prune` or `--no-prune` takes precedence over it. 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 plan.## Apply an app```bashtwenty app apply --remote devtwenty app apply --create --json-twenty app apply --no-delete+twenty app apply --no-prune+twenty app apply --prune````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 plan, 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 plans its changes 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 plan 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.+- **Deletions.** Entities missing from source are deleted by default (except in the workspace custom application), as in `app plan`; `--no-prune` keeps them, `--prune` deletes them in every app, and the choice is sent to both the plan and the sync. JSON reports `inferDeletionFromMissingEntities: null` when neither flag is passed. 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.@@ -342,8 +344,8 @@ Remote changes made between the plan and the sync can change what the sync does.```bashtwenty app dev --remote dev-twenty app dev --create --no-delete-twenty app dev --path ./apps/billing --format ndjson --no-delete+twenty app dev --create --no-prune+twenty app dev --path ./apps/billing --format ndjson --no-prune````app dev` builds and syncs once, then watches for edits. Each attempt uses the@@ -368,7 +370,8 @@ snapshot was acknowledged by the workspace. This is eventual convergence afteredits 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+on by default except for the workspace custom application, with `--no-prune`+to keep missing entities and `--prune` to delete them in every app. Object and fielddeletions require a terminal confirmation or `--yes`. Every revision requests afresh plan. An edit cancels a pending confirmation; approval for theold revision cannot authorize the new one. A remote failure is reported with thediff --git a/packages/twenty-cli/src/app/deployment/apply-app-build.ts b/packages/twenty-cli/src/app/deployment/apply-app-build.tsindex 4a65055d350..c9097a0c2f2 100644--- a/packages/twenty-cli/src/app/deployment/apply-app-build.ts+++ b/packages/twenty-cli/src/app/deployment/apply-app-build.ts@@ -42,7 +42,7 @@ export const applyAppBuild = async ({build: ToolingBuild;appPath: string;context: TargetCommandContext;- inferDeletionFromMissingEntities: boolean;+ inferDeletionFromMissingEntities: boolean | undefined;isCreationApproved: boolean;isDeletionApproved: boolean;approvalSignal?: AbortSignal;@@ -188,7 +188,7 @@ export const applyAppBuild = async ({question: `Apply ${summary.destructive} ${deletionLabel} stored data on ${target.apiUrl}?`,code: 'CONFIRMATION_REQUIRED',message: `The plan 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.',+ hint: 'Review it with twenty app plan, then pass --yes to apply it, or --no-prune to keep entities missing from source.',});}diff --git a/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts b/packages/twenty-cli/src/app/deployment/fetch-app-plan.tsindex cfc1e6dad2a..b382ffd33cd 100644--- a/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts+++ b/packages/twenty-cli/src/app/deployment/fetch-app-plan.ts@@ -1,4 +1,4 @@-import { isPlainObject } from 'twenty-shared/utils';+import { isDefined, isPlainObject } from 'twenty-shared/utils';import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';import { parseAppPlan } from '@/app/deployment/parse-app-plan';@@ -14,7 +14,7 @@ export const fetchAppPlan = async ({signal,}: {build: ToolingBuild;- inferDeletionFromMissingEntities: boolean;+ inferDeletionFromMissingEntities: boolean | undefined;target: ResolvedTarget;signal: AbortSignal;}) => {@@ -37,7 +37,9 @@ export const fetchAppPlan = async ({__args: {manifest: build.manifest,dryRun: true,- inferDeletionFromMissingEntities,+ ...(isDefined(inferDeletionFromMissingEntities) && {+ inferDeletionFromMissingEntities,+ }),},applicationUniversalIdentifier: true,actions: true,diff --git a/packages/twenty-cli/src/app/deployment/format-app-plan.ts b/packages/twenty-cli/src/app/deployment/format-app-plan.tsindex cd13381129f..84f4a0a69e9 100644--- a/packages/twenty-cli/src/app/deployment/format-app-plan.ts+++ b/packages/twenty-cli/src/app/deployment/format-app-plan.ts@@ -13,8 +13,8 @@ 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 NO_PRUNE_HINT =+ 'Entities missing from your source are destroyed by default. Re-run with --no-prune to keep them.';const DENIED_ATTRIBUTE_KEYS = new Set(['id',@@ -231,7 +231,7 @@ export const formatAppPlanActions = ({}: {actions: AppPlanAction[];summary: AppPlanSummary;- inferDeletionFromMissingEntities: boolean;+ inferDeletionFromMissingEntities: boolean | undefined;stream?: NodeJS.WriteStream;}) => {if (actions.length === 0) {@@ -248,8 +248,8 @@ export const formatAppPlanActions = ({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)]+ ...(!isDefined(inferDeletionFromMissingEntities) && summary.delete > 0+ ? [dimText(NO_PRUNE_HINT, stream)]: []),...(summary.destructive > 0? ['', formatDestructiveWarning(actions, stream)]@@ -268,7 +268,7 @@ export const formatAppPlan = ({apiUrl: string;actions: AppPlanAction[];summary: AppPlanSummary;- inferDeletionFromMissingEntities: boolean;+ inferDeletionFromMissingEntities: boolean | undefined;}) =>[`Plan for ${formatDataValue(applicationName)} on ${apiUrl}`,diff --git a/packages/twenty-cli/src/app/deployment/read-infer-deletion-option.ts b/packages/twenty-cli/src/app/deployment/read-infer-deletion-option.tsnew file mode 100644index 00000000000..a9493569cd9--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/read-infer-deletion-option.ts@@ -0,0 +1,24 @@+import { isBoolean } from '@sniptt/guards';++import { type CommandContext } from '@/catalog/types/command-context.type';++// Undefined leaves the default to the server, which depends on the application.+export const readInferDeletionOption = ({+ options,+ output,+}: Pick<CommandContext, 'options' | 'output'>): boolean | undefined => {+ const isDeprecatedNoDeletePassed = options.delete === false;++ if (isDeprecatedNoDeletePassed) {+ output.warn({+ code: 'DEPRECATED_OPTION',+ message: '--no-delete is deprecated, use --no-prune instead.',+ });+ }++ if (isBoolean(options.prune)) {+ return options.prune;+ }++ return isDeprecatedNoDeletePassed ? false : undefined;+};diff --git a/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts b/packages/twenty-cli/src/app/deployment/sync-app-manifest.tsindex ea315adab86..97f6b601533 100644--- a/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts+++ b/packages/twenty-cli/src/app/deployment/sync-app-manifest.ts@@ -1,5 +1,5 @@import { isString } from '@sniptt/guards';-import { isPlainObject } from 'twenty-shared/utils';+import { isDefined, isPlainObject } from 'twenty-shared/utils';import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';import { parseAppPlan } from '@/app/deployment/parse-app-plan';@@ -49,7 +49,7 @@ export const syncAppManifest = async ({signal,}: {build: ToolingBuild;- inferDeletionFromMissingEntities: boolean;+ inferDeletionFromMissingEntities: boolean | undefined;target: ResolvedTarget;signal: AbortSignal;}) => {@@ -58,7 +58,12 @@ export const syncAppManifest = async ({.mutation({__name: 'SyncApplication',syncApplication: {- __args: { manifest: build.manifest, inferDeletionFromMissingEntities },+ __args: {+ manifest: build.manifest,+ ...(isDefined(inferDeletionFromMissingEntities) && {+ inferDeletionFromMissingEntities,+ }),+ },applicationUniversalIdentifier: true,actions: true,},diff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.mdindex e7ba18a3d17..abb9dc29022 100644--- a/packages/twenty-cli/src/app/pull/README.md+++ b/packages/twenty-cli/src/app/pull/README.md@@ -27,6 +27,6 @@ Workflows arrive in `manifest.workflows` and are written as `defineWorkflow` filSkills and agents arrive in `manifest.skills` and `manifest.agents` and are written as `defineSkill` and `defineAgent` files, with no enum bindings. The server exports one only when its definition reproduces the stored entity; otherwise it is reported as `UNSUPPORTED` coverage, so its local file is kept.-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.+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. Because pull is partial, `app apply` of the workspace custom application only deletes entities missing from source with `--prune`.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/commands/app/__tests__/app-apply.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.tsindex 861adb41902..b2dbc840e39 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-apply.spec.ts@@ -539,17 +539,22 @@ describe('app apply', () => {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']),- );+ it.each([+ { flags: [], inferDeletion: undefined },+ { flags: ['--prune'], inferDeletion: true },+ { flags: ['--no-prune'], inferDeletion: false },+ ])(+ 'previews, installs, uploads without credentials, then syncs with $flags',+ async ({ flags, inferDeletion }) => {+ const { envelope, exitCode } = await runJson(...flags);+ const deletionArgument = isDefined(inferDeletion)+ ? { inferDeletionFromMissingEntities: inferDeletion }+ : {};expect(exitCode).toBe(0);expect(envelope.data).toMatchObject({application: APPLICATION,- inferDeletionFromMissingEntities: inferDeletion,+ inferDeletionFromMissingEntities: inferDeletion ?? null,registrationCreated: false,completedPhases: ['build',@@ -584,16 +589,17 @@ describe('app apply', () => {(request) => getOperation(request) === 'sync',);- expect(readGraphqlRequest(preview).arguments).toMatchObject({+ expect(readGraphqlRequest(preview).arguments).toEqual({manifest: MANIFEST,- inferDeletionFromMissingEntities: inferDeletion,+ dryRun: true,+ ...deletionArgument,});expect(isDefined(sync) && readGraphqlRequest(sync)).toMatchObject({query: expect.not.stringContaining('dryRun'),- arguments: {- manifest: MANIFEST,- inferDeletionFromMissingEntities: inferDeletion,- },+ });+ expect(isDefined(sync) && readGraphqlRequest(sync).arguments).toEqual({+ manifest: MANIFEST,+ ...deletionArgument,});expect(readGraphqlRequest(uploadTargets).arguments).toMatchObject({applicationUniversalIdentifier: APPLICATION.universalIdentifier,@@ -623,6 +629,23 @@ describe('app apply', () => {},);+ it('treats the deprecated --no-delete as --no-prune and warns about it', async () => {+ const { exitCode, stderr } = await run('--no-delete');++ expect(exitCode).toBe(0);+ expect(stderr).toContain('--no-delete is deprecated, use --no-prune');+ expect(+ server.requests+ .filter((request) =>+ ['preview', 'sync'].includes(getOperation(request)),+ )+ .map((request) => readGraphqlRequest(request).arguments),+ ).toEqual([+ expect.objectContaining({ inferDeletionFromMissingEntities: false }),+ expect.objectContaining({ inferDeletionFromMissingEntities: false }),+ ]);+ });+it('accepts the lowercase identifier the server returns for an uppercase manifest identifier', async () => {await writeTooling({application: {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.tsindex f87186348ff..17d292c9a6d 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-dev.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-dev.spec.ts@@ -107,7 +107,7 @@ describe('twenty app dev', () => {'ndjson','--create','--yes',- '--no-delete',+ '--no-prune',]);await vi.waitFor(() => expect(buildDevSnapshot).toHaveBeenCalledOnce());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.tsindex d2f967f7d8a..6bae8ededdb 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-plan.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-plan.spec.ts@@ -160,11 +160,14 @@ describe('app plan', () => {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);+ it.each([+ { flags: [], inferDeletion: undefined },+ { flags: ['--prune'], inferDeletion: true },+ { flags: ['--no-prune'], inferDeletion: false },+ ])(+ 'requests only a dry run with $flags',+ async ({ flags, inferDeletion }) => {+ const { envelope, exitCode, stdout } = await runJson(...flags);expect(exitCode).toBe(0);expect(envelope).toMatchObject({@@ -173,7 +176,7 @@ describe('app plan', () => {data: {application: APPLICATION,plan: true,- inferDeletionFromMissingEntities: options.length === 0,+ inferDeletionFromMissingEntities: inferDeletion ?? null,actions: ACTIONS,summary: { create: 1, update: 1, delete: 2, destructive: 1 },},@@ -192,11 +195,13 @@ describe('app plan', () => {});expect(readGraphqlRequest(server.requests[0])).toMatchObject({query: expect.stringContaining('mutation PreviewApplication'),- arguments: {- dryRun: true,- manifest: MANIFEST,- inferDeletionFromMissingEntities: options.length === 0,- },+ });+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({+ dryRun: true,+ manifest: MANIFEST,+ ...(isDefined(inferDeletion) && {+ inferDeletionFromMissingEntities: inferDeletion,+ }),});expect(await readFile(join(appPath, 'builds.txt'), 'utf8')).toBe('built\n',@@ -225,7 +230,7 @@ describe('app plan', () => {' # objectMetadata "company" will be destroyed',' # view "Old view" will be destroyed','Plan: 1 to add, 1 to change, 2 to destroy.',- '--no-delete',+ '--no-prune','Warning: 1 destructive change(s) will permanently delete data.',' - objectMetadata "company": drops the table and all its rows','Nothing was registered',@@ -236,6 +241,37 @@ describe('app plan', () => {expect(stdout).not.toContain('project output');});+ it('does not offer --no-prune when deletions were requested with --prune', async () => {+ const { stdout, exitCode } = await run('--prune');++ expect(exitCode).toBe(0);+ expect(stdout).toContain('Plan: 1 to add, 1 to change, 2 to destroy.');+ expect(stdout).not.toContain('--no-prune');+ });++ it.each([+ { flags: ['--no-delete'], inferDeletion: false },+ { flags: ['--no-delete', '--prune'], inferDeletion: true },+ ])(+ 'accepts the deprecated --no-delete with a warning for $flags',+ async ({ flags, inferDeletion }) => {+ const { envelope, exitCode } = await runJson(...flags);++ expect(exitCode).toBe(0);+ expect(envelope.data.inferDeletionFromMissingEntities).toBe(+ inferDeletion,+ );+ expect(envelope.warnings).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ code: 'DEPRECATED_OPTION' }),+ ]),+ );+ expect(readGraphqlRequest(server.requests[0]).arguments).toMatchObject({+ inferDeletionFromMissingEntities: inferDeletion,+ });+ },+ );+it('reports an empty plan as a success', async () => {state.response = planResponse([]);const { stdout, exitCode } = await run();@@ -496,7 +532,7 @@ describe('app plan', () => {needsProject: true,needsTarget: true,requiredPermissions: ['APPLICATIONS'],- flags: expect.arrayContaining(['--no-delete']),+ flags: expect.arrayContaining(['--prune', '--no-prune']),}),);expect(server.requests).toHaveLength(0);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.tsindex b13d655ec78..2230550bec5 100644--- 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@@ -11,9 +11,19 @@ export const APP_APPLY_COMMAND_DEFINITION: TargetCommandDefinition = {'App directory (default: the app containing the current folder)',},{- flags: '--no-delete',+ flags: '--prune',+ description:+ 'Delete remote entities missing from the app source (the default, except for the workspace custom application)',+ },+ {+ flags: '--no-prune',description: 'Keep remote entities missing from the app source',},+ {+ flags: '--no-delete',+ description: 'Deprecated alias of --no-prune',+ hidden: true,+ },{flags: '--create',description:@@ -28,7 +38,8 @@ export const APP_APPLY_COMMAND_DEFINITION: TargetCommandDefinition = {examples: ['twenty app apply --remote dev','twenty app apply --create --json',- 'twenty app apply --no-delete',+ 'twenty app apply --no-prune',+ 'twenty app apply --prune',],outputModes: ['human', 'json'],writes: true,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.tsindex feca4c40257..08223d589d1 100644--- 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@@ -8,6 +8,7 @@ import { createPostSyncFailure } from '@/app/deployment/create-post-sync-failureimport { formatApplySummary } from '@/app/deployment/format-apply-summary';import { generateAppClient } from '@/app/generate-app-client';import { getAppPlanSummary } from '@/app/deployment/get-app-plan-summary';+import { readInferDeletionOption } from '@/app/deployment/read-infer-deletion-option';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';@@ -25,7 +26,7 @@ export const runAppApplyCommand: CommandRun<TargetCommandContext> = async (context,) => {const startedAt = performance.now();- const inferDeletionFromMissingEntities = context.options.delete !== false;+ const inferDeletionFromMissingEntities = readInferDeletionOption(context);let applyResult: AppApplyResult | undefined;const appProject = await resolveAppProject({explicitPath: readStringOption(context.options, 'path'),@@ -140,7 +141,8 @@ export const runAppApplyCommand: CommandRun<TargetCommandContext> = async (sdk: { version: sdk.version },application: build.application,contentHash: build.contentHash,- inferDeletionFromMissingEntities,+ inferDeletionFromMissingEntities:+ inferDeletionFromMissingEntities ?? null,registrationCreated: applyResult.isRegistrationCreated,completedPhases: applyResult.completedPhases,actions: applyResult.appliedActions ?? null,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.tsindex e6432441ed6..d030c7d092a 100644--- 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@@ -11,9 +11,19 @@ export const APP_DEV_COMMAND_DEFINITION: TargetCommandDefinition = {'App directory (default: the app containing the current folder)',},{- flags: '--no-delete',+ flags: '--prune',+ description:+ 'Delete remote entities missing from the app source (the default, except for the workspace custom application)',+ },+ {+ flags: '--no-prune',description: 'Keep remote entities missing from the app source',},+ {+ flags: '--no-delete',+ description: 'Deprecated alias of --no-prune',+ hidden: true,+ },{flags: '--create',description:@@ -26,8 +36,8 @@ export const APP_DEV_COMMAND_DEFINITION: TargetCommandDefinition = {],examples: ['twenty app dev --remote dev',- 'twenty app dev --create --no-delete',- 'twenty app dev --format ndjson --no-delete',+ 'twenty app dev --create --no-prune',+ 'twenty app dev --format ndjson --no-prune',],outputModes: ['human', 'ndjson'],writes: true,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.tsindex 2765baceee4..73e17a2ad17 100644--- 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@@ -2,6 +2,7 @@ import { isDefined } from 'twenty-shared/utils';import { applyAppBuild } from '@/app/deployment/apply-app-build';import { createPostSyncFailure } from '@/app/deployment/create-post-sync-failure';+import { readInferDeletionOption } from '@/app/deployment/read-infer-deletion-option';import {buildDevSnapshot,type BuiltDevSnapshot,@@ -26,6 +27,7 @@ import { toCliError } from '@/output/to-cli-error';export const runAppDevCommand: CommandRun<TargetCommandContext> = async (context,) => {+ const inferDeletionFromMissingEntities = readInferDeletionOption(context);const project = await resolveAppProject({explicitPath: readStringOption(context.options, 'path'),workingDirectory: process.cwd(),@@ -175,7 +177,7 @@ export const runAppDevCommand: CommandRun<TargetCommandContext> = async (build: snapshot.build,appPath: project.path,context: currentContext,- inferDeletionFromMissingEntities: context.options.delete !== false,+ inferDeletionFromMissingEntities,isCreationApproved: readBooleanOption(context.options, 'create'),isDeletionApproved: readBooleanOption(context.options, 'yes'),approvalSignal: controls.revisionSignal,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.tsindex ce98e3e6069..a07c61ec5c4 100644--- 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@@ -11,13 +11,24 @@ export const APP_PLAN_COMMAND_DEFINITION: TargetCommandDefinition = {'App directory (default: the app containing the current folder)',},{- flags: '--no-delete',+ flags: '--prune',+ description:+ 'Delete remote entities missing from the app source (the default, except for the workspace custom application)',+ },+ {+ flags: '--no-prune',description: 'Keep remote entities missing from the app source',},+ {+ flags: '--no-delete',+ description: 'Deprecated alias of --no-prune',+ hidden: true,+ },],examples: ['twenty app plan --remote dev',- 'twenty app plan --path ./apps/billing --no-delete --json',+ 'twenty app plan --path ./apps/billing --no-prune --json',+ 'twenty app plan --prune',],outputModes: ['human', 'json'],writes: false,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.tsindex fdbd8d6a96f..67bbf74d0db 100644--- 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@@ -1,6 +1,7 @@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 { readInferDeletionOption } from '@/app/deployment/read-infer-deletion-option';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';@@ -9,13 +10,13 @@ export const runAppPlanCommand: CommandRun<TargetCommandContext> = async (context,) => {const startedAt = performance.now();+ const inferDeletionFromMissingEntities = readInferDeletionOption(context);const {project,sdk,data: build,diagnostics,} = await runAppBuild({ context });- const inferDeletionFromMissingEntities = context.options.delete !== false;context.output.progress({message: 'Computing metadata plan (read-only, nothing will be applied)…',@@ -36,7 +37,8 @@ export const runAppPlanCommand: CommandRun<TargetCommandContext> = async (application: build.application,contentHash: build.contentHash,plan: true,- inferDeletionFromMissingEntities,+ inferDeletionFromMissingEntities:+ inferDeletionFromMissingEntities ?? null,actions,summary,diagnostics,diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdxindex aef02945cec..65d6c729b94 100644--- a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx+++ b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx@@ -54,7 +54,7 @@ twenty app plantwenty app apply```-`plan` previews changes. `apply` uploads and synchronizes once. Use `--no-delete` to keep remote entities missing from source, or `--yes` to permit object and field deletions without a prompt. All three commands require an authenticated remote and registration ownership.+`plan` previews changes. `apply` uploads and synchronizes once. Use `--no-prune` to keep remote entities missing from source, or `--yes` to permit object and field deletions without a prompt. All three commands require an authenticated remote and registration ownership.## What you can builddiff --git a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx b/packages/twenty-docs/developers/extend/apps/operations/cli.mdxindex 68fb5d97b6b..97def9b8f6b 100644--- a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx+++ b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx@@ -116,7 +116,7 @@ Other app commands:| `app install` | Install an already registered app package in the workspace || `app uninstall` | Remove the app and everything it owns from the workspace |-Definitions missing from your source are deleted from the workspace by default. Pass `--no-delete` to keep them. Deleting objects or fields also deletes their data, so it requires confirmation. See [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery) for details.+Definitions missing from your source are deleted from the workspace by default. Pass `--no-prune` to keep them. The workspace Custom application keeps them unless you pass `--prune`. Deleting objects or fields also deletes their data, so it requires confirmation. See [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery) for details.## Executing functionsdiff --git a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdxindex ebe7c1dce93..6b5452c61f2 100644--- a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx+++ b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx@@ -22,7 +22,8 @@ Local app development revolves around **syncing**: the CLI rebuilds your manifes| Iterate locally with live sync | `twenty app dev` | Watches your files and syncs on every change. || Sync once and exit (CI, scripts, hooks) | `twenty app apply` | One build + sync, then exits. Add `--yes` to skip the destructive-change confirmation. || Preview changes **without applying them** | `twenty app plan` | Computes and prints the diff; writes nothing. |-| Sync without deleting anything | `twenty app apply --no-delete` | Creates and updates only: entities that exist in the workspace but not in your source are left alone. Also accepted by `plan` and `dev`. |+| Sync without deleting anything | `twenty app apply --no-prune` | Creates and updates only: entities that exist in the workspace but not in your source are left alone. Also accepted by `plan` and `dev`. |+| Prune the workspace Custom application | `twenty app apply --prune` | That app keeps entities missing from source unless you pass `--prune`. Also accepted by `plan` and `dev`. || Regenerate local source from the workspace | `twenty app pull` | **Experimental.** Writes the installed app back to define files. See below. || Remove the app from the workspace | `twenty app uninstall` | Add `--yes` to skip the prompt. || Ship a tarball to a server | `twenty app publish --private` | Requires a **strictly higher** `package.json` version — see [Publishing](/developers/extend/apps/operations/publishing). |@@ -55,7 +56,7 @@ This is your first diagnostic: it tells you exactly which objects, fields, and lDestructive changes (`to destroy`) are listed with what they drop (e.g. `objectMetadata "auditNote" — drops the table and all its rows`) and require interactive confirmation, or `--yes` in scripts.-A sync deletes every entity your app owns that your source no longer declares. When a plan contains destroys it says so and points at `--no-delete`, which makes the sync additive: creates and updates are applied, nothing missing from your source is deleted, and the settings component and uninstall hook bindings of the app stay as they are when your source does not declare them. Use it when your source is intentionally partial, for example while adopting an app that was built in the UI.+A sync deletes every entity your app owns that your source no longer declares. When a plan contains destroys it says so and points at `--no-prune` (formerly `--no-delete`, which still works), which makes the sync additive: creates and updates are applied, nothing missing from your source is deleted, and the settings component and uninstall hook bindings of the app stay as they are when your source does not declare them. Use it when your source is intentionally partial, for example while adopting an app that was built in the UI. The workspace Custom application is the exception: since pull cannot export everything it owns yet, its sync is additive unless you pass `--prune`. Servers released before this change still delete by default, so pass `--no-prune` when applying the Custom application to one.When a sync fails on a single entity, the error names the offending entity and its `universalIdentifier`, for example:@@ -149,7 +150,7 @@ Each entity goes to the file that already defines it, so a second pull rewrites- **Workspace runtime state** — member and API-key role assignments, webhooks, per-user navigation and navigation items pinned to a record, all excluded by design.- **Owned by another application** — reported, never pulled.-The report at the end of a pull lists all of it, grouped by kind and reason. Everything it names as not written is still in your workspace, so push a pulled tree back with `twenty app apply --no-delete` until the missing kinds are covered. A pruning `twenty app apply` would delete them, and `twenty app plan` lists exactly which.+The report at the end of a pull lists all of it, grouped by kind and reason. Everything it names as not written is still in your workspace, so push a pulled tree back with `twenty app apply --no-prune` until the missing kinds are covered. The workspace Custom application already applies this way by default. A pruning apply (the default for other apps, `--prune` for the Custom application) would delete them, and `twenty app plan` lists exactly which.**Workspace-local state.** An entity deactivated in the workspace is written as an active definition, and the overrides the workspace made on an entity, such as a renamed label, are not written. The report lists those rows under "Written without their workspace-local state". Applying the tree back to the same workspace leaves that state untouched; another workspace gets the entity active and without the overrides.diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.resolver.tsindex 778ea512b31..7da9803c505 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.resolver.ts@@ -89,13 +89,15 @@ export class ApplicationDevelopmentResolver {requireApplicationRegistrationOwnership: true,}){ manifest, dryRun, inferDeletionFromMissingEntities }: ApplicationInput,- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @AuthWorkspace()+ { id: workspaceId, workspaceCustomApplicationId }: WorkspaceEntity,): Promise<WorkspaceMigrationDTO> {return this.applicationDevelopmentService.syncApplication({manifest,dryRun,inferDeletionFromMissingEntities,workspaceId,+ workspaceCustomApplicationId,});}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.tsindex c64abcc26e6..9dbee392e23 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-development/application-development.service.ts@@ -118,15 +118,14 @@ export class ApplicationDevelopmentService {dryRun,inferDeletionFromMissingEntities,workspaceId,+ workspaceCustomApplicationId,}: {manifest: ApplicationInput['manifest'];dryRun?: boolean;inferDeletionFromMissingEntities?: boolean | null;workspaceId: string;+ workspaceCustomApplicationId: string;}): Promise<WorkspaceMigrationDTO> {- const shouldInferDeletionFromMissingEntities =- inferDeletionFromMissingEntities !== false;-await this.throttlePerApplication(manifest.application.universalIdentifier,workspaceId,@@ -155,6 +154,15 @@ export class ApplicationDevelopmentService {},);+ const shouldInferDeletionFromMissingEntities =+ await this.resolveDeletionInference({+ applicationUniversalIdentifier:+ manifest.application.universalIdentifier,+ inferDeletionFromMissingEntities,+ workspaceId,+ workspaceCustomApplicationId,+ });+if (dryRun === true) {const { workspaceMigration } =await this.applicationSyncService.synchronizeFromManifest({@@ -293,6 +301,32 @@ export class ApplicationDevelopmentService {};}+ // Pull cannot export everything the workspace custom application owns yet,+ // so applying a pulled project must only delete what is missing on request.+ private async resolveDeletionInference({+ applicationUniversalIdentifier,+ inferDeletionFromMissingEntities,+ workspaceId,+ workspaceCustomApplicationId,+ }: {+ applicationUniversalIdentifier: string;+ inferDeletionFromMissingEntities?: boolean | null;+ workspaceId: string;+ workspaceCustomApplicationId: string;+ }): Promise<boolean> {+ if (isDefined(inferDeletionFromMissingEntities)) {+ return inferDeletionFromMissingEntities;+ }++ const application =+ await this.applicationLookupService.findByUniversalIdentifier({+ universalIdentifier: applicationUniversalIdentifier,+ workspaceId,+ });++ return application?.id !== workspaceCustomApplicationId;+ }+private async throttlePerApplication(applicationIdentifier: string,workspaceId: string,diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.tsindex cfd40a0a106..bf951ec72ae 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-export-application-data-model.integration-spec.ts@@ -1199,6 +1199,82 @@ describe('Application export - data model', () => {}}, 60000);+ it('only deletes workspace Custom application entities missing from the manifest when deletion is explicitly requested', async () => {+ const { data: applicationsData } = await findManyApplications({+ expectToFail: false,+ });+ const customApplication = applicationsData.findManyApplications.find(+ ({ name }) => name === WORKSPACE_CUSTOM_APPLICATION_NAME,+ );++ jestExpectToBeDefined(customApplication);++ const personObject = (+ await findManyObjectMetadata({+ expectToFail: false,+ input: { filter: {}, paging: { first: 1000 } },+ gqlFields: 'id nameSingular',+ })+ ).objects.find(({ nameSingular }) => nameSingular === 'person');++ jestExpectToBeDefined(personObject);++ const { data: createdViewData } = await createOneView({+ expectToFail: false,+ input: {+ name: 'Pruned Custom Application People',+ objectMetadataId: personObject.id,+ type: ViewType.TABLE,+ icon: 'IconUser',+ },+ });++ try {+ const { data } = await exportApplication({+ universalIdentifier: customApplication.universalIdentifier,+ expectToFail: false,+ });+ const { manifest } = data.exportApplication;+ const prunedView = manifest.views.find(+ ({ name }) => name === 'Pruned Custom Application People',+ );++ jestExpectToBeDefined(prunedView);++ const manifestWithoutView = {+ ...manifest,+ views: manifest.views.filter((view) => view !== prunedView),+ };+ const planWith = async (inferDeletionFromMissingEntities?: boolean) => {+ const dryRun = await syncApplication({+ manifest: manifestWithoutView,+ dryRun: true,+ inferDeletionFromMissingEntities,+ expectToFail: false,+ });++ expect(dryRun.errors).toBeUndefined();++ return dryRun.data.syncApplication.actions;+ };++ expect(await planWith(undefined)).toEqual([]);+ expect(await planWith(false)).toEqual([]);+ expect(await planWith(true)).toContainEqual(+ expect.objectContaining({+ type: 'delete',+ metadataName: 'view',+ universalIdentifier: prunedView.universalIdentifier,+ }),+ );+ } finally {+ await destroyOneView({+ expectToFail: false,+ viewId: createdViewData.createView.id,+ });+ }+ }, 60000);+it('should round-trip a role with object, field and flag permissions created through the metadata API in the workspace Custom application without any action', async () => {const { objects } = await findManyObjectMetadata({expectToFail: false,