The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(cli): pull application dependency files (#29197)
Weikofd6cccb3b7a3
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex b3f3c484864..a2aae52ce98 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -435,7 +435,7 @@ failures restore the previous files and baseline.Failures in reconciliation report `error.details.outcome`: `unchanged` after an acknowledged refusal, cancellation before writing or successful rollback; `unknown` if a worker stops without acknowledging completion or rollback fails; `pulled` if writes and baseline completed but temporary-file cleanup failed. An interrupted worker can leave files partially written; inspect the changes and retained `.twenty/cli/pull-backup-*` files before retrying. A failed rollback also reports `backupDirectory`. Ctrl+C exits 130 unless the worker acknowledges a completed commit, in which case pull returns its result.-The current export contains metadata and translations, not application source assets or dependency files. Workflows are written as `defineWorkflow` files in `src/workflows`; a workflow changed in the workflow builder, or one using steps or references an application cannot declare, is reported as a coverage gap and its local file is kept. The workspace Custom application is published from the builder too, so its workflows are written from their active version, and apply publishes a changed definition as a new version. Skills and agents are written as `defineSkill` and `defineAgent` files in `src/skills` and `src/agents`; one the server cannot reproduce from a definition, such as an agent on more than one role, is reported as a coverage gap and its local file is kept. Logic-function/front-component code and unsupported metadata are not regenerated. An export with nonempty `files` is refused before writing. Package files, dependency pins and the installed generated client are left alone; pull never installs dependencies. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.+The current export contains metadata, translations and stored dependency files. Public assets and application source files are not exported yet. Workflows are written as `defineWorkflow` files in `src/workflows`; a workflow changed in the workflow builder, or one using steps or references an application cannot declare, is reported as a coverage gap and its local file is kept. The workspace Custom application is published from the builder too, so its workflows are written from their active version, and apply publishes a changed definition as a new version. Skills and agents are written as `defineSkill` and `defineAgent` files in `src/skills` and `src/agents`; one the server cannot reproduce from a definition, such as an agent on more than one role, is reported as a coverage gap and its local file is kept. Logic-function/front-component code and unsupported metadata are not regenerated. Pull restores `package.json` and `yarn.lock` from the application’s `dependencies` folder. If the exported package omits `twenty-sdk`, as the workspace Custom application does, pull keeps your local SDK dependency. Other exported files are refused before writing. Dependency files unchanged on the workspace keep local edits; changed remote files replace them. Missing remote files leave local files untouched. The installed generated client is left alone; pull never installs dependencies. Run `yarn install` after pulling dependency changes. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.## Install a registered appdiff --git a/packages/twenty-cli/src/app/fetch-app-export.ts b/packages/twenty-cli/src/app/fetch-app-export.tsindex a4d17cf7a46..3268255ae5e 100644--- a/packages/twenty-cli/src/app/fetch-app-export.ts+++ b/packages/twenty-cli/src/app/fetch-app-export.ts@@ -63,16 +63,23 @@ export const fetchAppExport = async ({universalIdentifier,target,signal,+ shouldIncludeDependencies = false,}: {universalIdentifier: string;target: ResolvedTarget;signal: AbortSignal;+ shouldIncludeDependencies?: boolean;}): Promise<AppExport> => {const data = await createMetadataClient({ target, signal }).query({__name: 'ExportApplication',exportApplication: {- __args: { universalIdentifier },+ __args: {+ universalIdentifier,+ ...(shouldIncludeDependencies+ ? { shouldIncludeDependencies: true }+ : {}),+ },application: {universalIdentifier: true,displayName: true,diff --git a/packages/twenty-cli/src/app/parse-app-export.ts b/packages/twenty-cli/src/app/parse-app-export.tsindex 2db9392f6a8..ad5d6e69091 100644--- a/packages/twenty-cli/src/app/parse-app-export.ts+++ b/packages/twenty-cli/src/app/parse-app-export.ts@@ -1,6 +1,7 @@import { isArray, isNull, isString } from '@sniptt/guards';import { isPlainObject } from 'twenty-shared/utils';import { isSameUniversalIdentifier } from '@/app/is-same-universal-identifier';+import { parsePullDependencyFiles } from '@/app/pull/parse-pull-dependency-files';import { isExportedManifest } from '@/app/pull/is-exported-manifest';import {type AppExport,@@ -49,15 +50,6 @@ export const parseAppExport = ({});}- if (applicationExport.files.length > 0) {- throw new CliError({- code: 'TOOLING_UNSUPPORTED',- message:- 'The application export contains source or dependency files that this CLI cannot reconcile. No local files were changed.',- hint: 'Use a CLI version that supports this export format.',- });- }-return {application: {universalIdentifier: applicationExport.application.universalIdentifier,@@ -66,6 +58,6 @@ export const parseAppExport = ({},manifest: applicationExport.manifest,coverage: applicationExport.coverage,- files: [],+ files: parsePullDependencyFiles(applicationExport.files),};};diff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.mdindex abb9dc29022..f078195d1fc 100644--- a/packages/twenty-cli/src/app/pull/README.md+++ b/packages/twenty-cli/src/app/pull/README.md@@ -17,7 +17,7 @@ See the [app tooling overview](../README.md) for package boundaries.- Fields already declared with `defineField` stay in their existing files, even when the server exports them inside an object. Object generation excludes those fields; baseline comparisons use the same source layout. Pull also removes duplicate inline copies left in object files, while retaining the standalone definitions.- Before destination writes, `assertPullSdkExports` checks the actual imports emitted by the writer against the app's SDK. It checks export presence, not every config shape; run typecheck to validate the generated definitions against the installed SDK.- Temporary files and the baseline live under `.twenty/cli`. Apply and pull share `createPullBaseWrite` as the serializer. The baseline is bound to the API URL, workspace UUID and application UUID. Pull stages it with mode 0600 and writes it after the source files.-- The baseline can carry `sourceFingerprints`, a SHA-256 per app-relative source and locale file. Apply captures them before building. Pull reports an overwritten local change when a file it rewrites or deletes no longer matches its fingerprint. Without a fingerprint it compares the file with the writer's rendering of the baseline, which is reliable only for source produced by that writer. Pull carries fingerprints forward, updating the files it writes and dropping the ones it deletes.+- The baseline can carry `sourceFingerprints`, a SHA-256 per app-relative source, locale and dependency file. Apply captures them before building. Pull reports an overwritten local change when a file it rewrites or deletes no longer matches its fingerprint. Without a fingerprint it compares the file with the writer's rendering of the baseline, which is reliable only for source produced by that writer. Pull carries fingerprints forward, updating the files it writes and dropping the ones it deletes.- Ordinary I/O failures restore originals. Cancellation is checked before committing the staged plan, not halfway through it. An acknowledged successful commit wins over cancellation. The parent can forcibly kill an unresponsive worker after its grace period, so an unacknowledged result has outcome `unknown`, never a claim that rollback succeeded. Failed rollback retains backups and reports their directory; failure to clean up after a completed commit has outcome `pulled`.- Human reporting uses CLI terminal escaping, machine reporting contains the full coverage and path lists, and gaps warn without stopping successful writes. Unknown coverage status strings remain visible. Pull does not prompt for approval or require a clean Git checkout; remote changes overwrite conflicting local edits and are included in the report.@@ -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. Because pull is partial, `app apply` of the workspace custom application only deletes entities missing from source with `--prune`.+Pull requests `exportApplication(shouldIncludeDependencies: true)`. Export defaults to metadata-only files (`files: []`) for existing clients and apply baselines. Pull restores `dependencies/package.json` and `dependencies/yarn.lock` to the project root, in the same transaction as metadata and the baseline. Exact folder and filename checks reject all other exported files, including record attachments, public assets and source. If the remote package omits `twenty-sdk`, pull retains the local SDK dependency so the workspace custom app remains usable with the CLI. The baseline stores remote `dependencyFingerprints` separately from written `sourceFingerprints` for this case. Other exported dependency contents are copied exactly. Dependency files unchanged on the server preserve local edits; remote changes replace local contents and use the usual overwrite report. Missing remote files leave local files untouched. Pull does not install dependencies, 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/app/pull/__tests__/parse-pull-dependency-files.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/parse-pull-dependency-files.spec.tsnew file mode 100644index 00000000000..b8aec24d3c7--- /dev/null+++ b/packages/twenty-cli/src/app/pull/__tests__/parse-pull-dependency-files.spec.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { parsePullDependencyFiles } from '@/app/pull/parse-pull-dependency-files';++const packageFile = {+ folder: 'dependencies',+ path: 'package.json',+ content: '{"name":"app"}\n',+};++describe('parsePullDependencyFiles', () => {+ it('retains the exact dependency contents', () => {+ const files = [+ packageFile,+ { folder: 'dependencies', path: 'yarn.lock', content: '' },+ ];+ expect(parsePullDependencyFiles(files)).toEqual(files);+ });++ it.each([+ '../package.json',+ '/package.json',+ 'nested/package.json',+ '.npmrc',+ 'node_modules/package.json',+ 'yarn.lock/../package.json',+ '..\\package.json',+ ])('refuses the dependency path %s', (path) => {+ expect(() => parsePullDependencyFiles([{ ...packageFile, path }])).toThrow(+ 'only pull package.json and yarn.lock',+ );+ });++ it.each([+ null,+ {},+ [{ ...packageFile, content: null }],+ [packageFile, packageFile],+ ])('refuses malformed or duplicate files (%#)', (files) => {+ expect(() => parsePullDependencyFiles(files)).toThrow();+ });++ it.each(['invalid-json', 'null', '[]', '42', '{}, {}'])(+ 'refuses invalid package.json contents %s',+ (content) => {+ expect(() =>+ parsePullDependencyFiles([{ ...packageFile, content }]),+ ).toThrow('JSON object');+ },+ );+});diff --git a/packages/twenty-cli/src/app/pull/__tests__/plan-dependency-writes.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/plan-dependency-writes.spec.tsnew file mode 100644index 00000000000..0ef398652be--- /dev/null+++ b/packages/twenty-cli/src/app/pull/__tests__/plan-dependency-writes.spec.ts@@ -0,0 +1,94 @@+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { collectSourceFingerprints } from '@/app/pull/collect-source-fingerprints';+import { planDependencyWrites } from '@/app/pull/plan-dependency-writes';+import { hashContent } from '@/utils/hash-content';++const files = [+ { folder: 'dependencies', path: 'package.json', content: '{"name":"app"}\n' },+];++describe('planDependencyWrites', () => {+ let appPath: string;+ beforeEach(async () => {+ appPath = await mkdtemp(join(tmpdir(), 'twenty-pull-dependencies-'));+ });+ afterEach(async () => {+ await rm(appPath, { recursive: true, force: true });+ });++ it('records a baseline even when the remote and local dependency already match', async () => {+ await writeFile(join(appPath, 'package.json'), files[0].content);+ const plan = await planDependencyWrites({ appPath, files });+ expect(plan.writes).toEqual([]);+ expect(plan.fingerprints).toEqual({+ 'package.json': hashContent(files[0].content),+ });+ expect(plan.unchangedCount).toBe(1);+ });++ it('preserves dependencies edited after apply when the remote contents have not changed', async () => {+ await writeFile(join(appPath, 'package.json'), files[0].content);+ await writeFile(join(appPath, 'yarn.lock'), 'pinned');+ const sourceFingerprints = await collectSourceFingerprints(appPath);+ expect(sourceFingerprints['yarn.lock']).toBe(hashContent('pinned'));+ await writeFile(join(appPath, 'package.json'), '{"name":"local-edit"}');+ const plan = await planDependencyWrites({+ appPath,+ files,+ sourceFingerprints,+ });+ expect(plan.writes).toEqual([]);+ expect(await readFile(join(appPath, 'package.json'), 'utf8')).toBe(+ '{"name":"local-edit"}',+ );+ });++ it('retains the local SDK dev dependency when the custom app only declares runtime dependencies', async () => {+ await writeFile(+ join(appPath, 'package.json'),+ JSON.stringify({+ devDependencies: { 'twenty-sdk': '2.52.0', 'local-only-tool': '1.0.0' },+ }),+ );+ const plan = await planDependencyWrites({ appPath, files });+ expect(JSON.parse(plan.writes[0].content)).toEqual({+ name: 'app',+ devDependencies: { 'twenty-sdk': '2.52.0' },+ });+ expect(plan.fingerprints['package.json']).toBe(+ hashContent(files[0].content),+ );+ expect(plan.fingerprints['package.json']).not.toBe(+ hashContent(plan.writes[0].content),+ );+ });++ it('uses the remote SDK dependency unchanged when one is exported', async () => {+ await writeFile(+ join(appPath, 'package.json'),+ JSON.stringify({+ devDependencies: { 'twenty-sdk': '2.44.0' },+ }),+ );+ const content = '{"dependencies":{"twenty-sdk":"2.52.0"}}\n';+ const plan = await planDependencyWrites({+ appPath,+ files: [{ ...files[0], content }],+ });+ expect(plan.writes[0].content).toBe(content);+ });++ it('leaves local files in place when no dependency files are exported', async () => {+ await writeFile(join(appPath, 'yarn.lock'), 'local-lock');+ expect((await planDependencyWrites({ appPath, files: [] })).writes).toEqual(+ [],+ );+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(+ 'local-lock',+ );+ });+});diff --git a/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.tsindex adf9e2a029b..ffbff5e1199 100644--- a/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/pull-application.spec.ts@@ -1186,8 +1186,10 @@ export default defineField({]);},);- it('rolls back replaced and deleted source when the final base commit fails', async () => {+ it('rolls back dependencies and source when the final base commit fails', async () => {+ await writeFile(join(appPath, 'yarn.lock'), 'original-lock');requireSuccess(await pull());+ const originalPackageJson = await read('package.json');const originalObject = await read(OBJECT_PATH);const originalApplication = await read('src/application.config.ts');const originalBase = await read(BASE_PATH);@@ -1203,7 +1205,13 @@ export default defineField({await originalCopy(source, destination);},);- const exported = createExport({ includeObject: false });+ const exported = {+ ...createExport({ includeObject: false }),+ files: [+ { folder: 'dependencies', path: 'package.json', content: '{}' },+ { folder: 'dependencies', path: 'yarn.lock', content: 'changed-lock' },+ ],+ };exported.manifest.application.displayName = 'Changed app';expect(await pull(exported)).toMatchObject({success: false,@@ -1212,6 +1220,8 @@ export default defineField({expect(await read(OBJECT_PATH)).toBe(originalObject);expect(await read('src/application.config.ts')).toBe(originalApplication);expect(await read(BASE_PATH)).toBe(originalBase);+ expect(await read('package.json')).toBe(originalPackageJson);+ expect(await read('yarn.lock')).toBe('original-lock');expect(await readdir(join(appPath, '.twenty/cli'))).toEqual(['pull-base.json',]);diff --git a/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.tsindex d7838ced51c..1fa857931f8 100644--- a/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/pull-base.spec.ts@@ -18,6 +18,7 @@ import { type Manifest } from 'twenty-shared/application';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';+import { createPullBaseWrite } from '@/app/pull/create-pull-base-write';import { readTargetBoundPullBase } from '@/app/pull/read-target-bound-pull-base';import { writePullBase } from '@/app/pull/write-pull-base';@@ -128,6 +129,22 @@ describe('target-bound CLI pull base', () => {expect((await stat(basePath)).mode & 0o777).toBe(0o600);});+ it('keeps remote dependency fingerprints separate from written source fingerprints', async () => {+ await seed(+ createPullBaseWrite({+ manifest: MANIFEST,+ target: TARGET,+ sourceFingerprints: { 'package.json': 'a'.repeat(64) },+ dependencyFingerprints: { 'package.json': 'b'.repeat(64) },+ }).content,+ );+ expect(await read()).toMatchObject({+ status: 'used',+ sourceFingerprints: { 'package.json': 'a'.repeat(64) },+ dependencyFingerprints: { 'package.json': 'b'.repeat(64) },+ });+ });+it('stores source fingerprints sorted by path and reads them back', async () => {const roleFingerprint = 'a'.repeat(64);const objectFingerprint = 'b'.repeat(64);@@ -253,6 +270,14 @@ describe('target-bound CLI pull base', () => {}),'unreadable',],+ [+ 'invalid dependency fingerprint',+ JSON.stringify({+ ...BASE,+ dependencyFingerprints: { 'package.json': 'invalid' },+ }),+ 'unreadable',+ ],['invalid source fingerprint',JSON.stringify({diff --git a/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts b/packages/twenty-cli/src/app/pull/collect-source-fingerprints.tsindex bb2453e34ab..99d4b340782 100644--- a/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts+++ b/packages/twenty-cli/src/app/pull/collect-source-fingerprints.ts@@ -13,15 +13,20 @@ import {export const collectSourceFingerprints = async (appPath: string,): Promise<Record<string, string>> => {- const localeFilePaths = await glob(- [`${LOCALES_DIR}/*.json`, `${COMPILED_LOCALES_DIR}/*.json`],+ const additionalFilePaths = await glob(+ [+ `${LOCALES_DIR}/*.json`,+ `${COMPILED_LOCALES_DIR}/*.json`,+ 'package.json',+ 'yarn.lock',+ ],{ cwd: appPath, absolute: true, onlyFiles: true },);const fingerprints: Record<string, string> = {};for (const filePath of [...(await listApplicationSourceFiles(appPath)),- ...localeFilePaths.sort(),+ ...additionalFilePaths.sort(),]) {fingerprints[relative(appPath, filePath).split(sep).join('/')] =hashContent(await readFile(filePath));diff --git a/packages/twenty-cli/src/app/pull/create-pull-base-write.ts b/packages/twenty-cli/src/app/pull/create-pull-base-write.tsindex 6266d25eab9..a92ce541bd0 100644--- a/packages/twenty-cli/src/app/pull/create-pull-base-write.ts+++ b/packages/twenty-cli/src/app/pull/create-pull-base-write.ts@@ -10,16 +10,21 @@ const compareRelativePaths = ([second]: [string, string],) => (first < second ? -1 : first > second ? 1 : 0);+const sortFingerprints = (fingerprints: Record<string, string>) =>+ Object.fromEntries(Object.entries(fingerprints).sort(compareRelativePaths));+export const createPullBaseWrite = ({manifest,target,unreconciledUniversalIdentifiers = [],sourceFingerprints,+ dependencyFingerprints,}: {manifest: ExportedManifest;target: PullTarget;unreconciledUniversalIdentifiers?: string[];sourceFingerprints?: Record<string, string>;+ dependencyFingerprints?: Record<string, string>;}) => ({relativePath: PULL_BASE_FILE_PATH,content: `${JSON.stringify(@@ -31,11 +36,14 @@ export const createPullBaseWrite = ({...(unreconciledUniversalIdentifiers.length > 0? { unreconciledUniversalIdentifiers }: {}),+ ...(isDefined(dependencyFingerprints)+ ? {+ dependencyFingerprints: sortFingerprints(dependencyFingerprints),+ }+ : {}),...(isDefined(sourceFingerprints)? {- sourceFingerprints: Object.fromEntries(- Object.entries(sourceFingerprints).sort(compareRelativePaths),- ),+ sourceFingerprints: sortFingerprints(sourceFingerprints),}: {}),},diff --git a/packages/twenty-cli/src/app/pull/parse-pull-data.ts b/packages/twenty-cli/src/app/pull/parse-pull-data.tsindex 7197fd96f3b..cec40b97320 100644--- a/packages/twenty-cli/src/app/pull/parse-pull-data.ts+++ b/packages/twenty-cli/src/app/pull/parse-pull-data.ts@@ -19,7 +19,9 @@ const isPath = (value: unknown): value is PullDeletion =>const isWrite = (value: unknown): value is PullAppResult['writes'][number] =>isPlainObject(value) &&- (isPullEntityKind(value.kind) || value.kind === 'translation') &&+ (isPullEntityKind(value.kind) ||+ value.kind === 'translation' ||+ value.kind === 'dependency') &&isBoolean(value.isRegeneration) &&isPath(value);diff --git a/packages/twenty-cli/src/app/pull/parse-pull-dependency-files.ts b/packages/twenty-cli/src/app/pull/parse-pull-dependency-files.tsnew file mode 100644index 00000000000..80c9a72cdbd--- /dev/null+++ b/packages/twenty-cli/src/app/pull/parse-pull-dependency-files.ts@@ -0,0 +1,70 @@+import { isArray, isString } from '@sniptt/guards';+import { FileFolder } from 'twenty-shared/types';+import { isPlainObject } from 'twenty-shared/utils';++import { type AppExportFile } from '@/app/types/app-export.type';+import { CliError } from '@/output/cli-error';++const isPackageJsonObject = (content: string): boolean => {+ try {+ return isPlainObject(JSON.parse(content));+ } catch {+ return false;+ }+};++export const parsePullDependencyFiles = (value: unknown): AppExportFile[] => {+ if (!isArray(value)) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The exported files must be an array.',+ });+ }++ const files: AppExportFile[] = [];+ const paths = new Set<string>();++ for (const file of value) {+ if (+ !isPlainObject(file) ||+ !isString(file.folder) ||+ !isString(file.path) ||+ !isString(file.content)+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The server returned an invalid exported file.',+ });+ }++ if (+ file.folder !== FileFolder.Dependencies ||+ !['package.json', 'yarn.lock'].includes(file.path)+ ) {+ throw new CliError({+ code: 'TOOLING_UNSUPPORTED',+ message:+ 'This CLI can only pull package.json and yarn.lock from the dependencies folder. No local files were changed.',+ });+ }++ if (paths.has(file.path)) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: `The server exported ${file.path} more than once.`,+ });+ }++ if (file.path === 'package.json' && !isPackageJsonObject(file.content)) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The exported package.json must contain a JSON object.',+ });+ }++ paths.add(file.path);+ files.push({ folder: file.folder, path: file.path, content: file.content });+ }++ return files;+};diff --git a/packages/twenty-cli/src/app/pull/plan-dependency-writes.ts b/packages/twenty-cli/src/app/pull/plan-dependency-writes.tsnew file mode 100644index 00000000000..7897c7428cc--- /dev/null+++ b/packages/twenty-cli/src/app/pull/plan-dependency-writes.ts@@ -0,0 +1,70 @@+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { isDefined } from 'twenty-shared/utils';++import { pathExists } from '@/app/fs-utils';+import { type PullWrite } from '@/app/pull/plan-pull-writes';+import { preserveLocalSdkDependency } from '@/app/pull/preserve-local-sdk-dependency';+import { type AppExportFile } from '@/app/types/app-export.type';+import { hashContent } from '@/utils/hash-content';++export const planDependencyWrites = async ({+ appPath,+ files,+ sourceFingerprints = {},+ dependencyFingerprints = {},+}: {+ appPath: string;+ files: AppExportFile[];+ sourceFingerprints?: Record<string, string>;+ dependencyFingerprints?: Record<string, string>;+}) => {+ const writes: PullWrite[] = [];+ const fingerprints: Record<string, string> = {};+ const unchangedSourceFingerprints: Record<string, string> = {};++ for (const { path, content: remoteContent } of files) {+ const absolutePath = join(appPath, path);+ const existingContent = (await pathExists(absolutePath))+ ? await readFile(absolutePath, 'utf8')+ : undefined;+ const fingerprint = hashContent(remoteContent);+ fingerprints[path] = fingerprint;++ if (+ isDefined(existingContent) &&+ (dependencyFingerprints[path] ?? sourceFingerprints[path]) === fingerprint+ ) {+ continue;+ }++ const content =+ path === 'package.json' && isDefined(existingContent)+ ? preserveLocalSdkDependency({+ content: remoteContent,+ existingContent,+ })+ : remoteContent;++ if (existingContent === content) {+ unchangedSourceFingerprints[path] = hashContent(content);+ continue;+ }++ writes.push({+ kind: 'dependency',+ universalIdentifier: `dependencies/${path}`,+ relativePath: path,+ content,+ requiredSdkExports: [],+ isRegeneration: isDefined(existingContent),+ });+ }++ return {+ writes,+ fingerprints,+ unchangedSourceFingerprints,+ unchangedCount: files.length - writes.length,+ };+};diff --git a/packages/twenty-cli/src/app/pull/plan-pull-writes.ts b/packages/twenty-cli/src/app/pull/plan-pull-writes.tsindex 61d081b7c37..512de0a9ca5 100644--- a/packages/twenty-cli/src/app/pull/plan-pull-writes.ts+++ b/packages/twenty-cli/src/app/pull/plan-pull-writes.ts@@ -11,7 +11,7 @@ import { writeDefineFile } from '@/app/pull/write-define-file';import { dirname, posix } from 'node:path';import { isDefined } from 'twenty-shared/utils';-export type PullWriteKind = PullEntityKind | 'translation';+export type PullWriteKind = PullEntityKind | 'translation' | 'dependency';export type PullWrite = {kind: PullWriteKind;diff --git a/packages/twenty-cli/src/app/pull/prepare-app-pull.ts b/packages/twenty-cli/src/app/pull/prepare-app-pull.tsindex ffee2ab896c..475434df7b8 100644--- a/packages/twenty-cli/src/app/pull/prepare-app-pull.ts+++ b/packages/twenty-cli/src/app/pull/prepare-app-pull.ts@@ -3,6 +3,7 @@ import { join } from 'node:path';import { isDefined, isPlainObject } from 'twenty-shared/utils';import { PULL_BASE_FILE_PATH } from '@/app/constants/pull-base-file-path.constant';+import { parsePullDependencyFiles } from '@/app/pull/parse-pull-dependency-files';import { assertPullPaths } from '@/app/pull/assert-pull-paths';import { normalizePullTarget } from '@/app/pull/normalize-pull-target';import { type PullAppOptions } from '@/app/pull/types';@@ -18,7 +19,15 @@ export const prepareAppPull = async ({const normalizedTarget = normalizePullTarget(target);- await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });+ const dependencyFiles = parsePullDependencyFiles(applicationExport.files);++ await assertPullPaths({+ appPath,+ relativePaths: [+ PULL_BASE_FILE_PATH,+ ...dependencyFiles.map((file) => file.path),+ ],+ });const packageJson: unknown = JSON.parse(await readFile(join(appPath, 'package.json'), 'utf8'),@@ -28,12 +37,6 @@ export const prepareAppPull = async ({throw new Error('Pull requires a project with a package.json object.');}- if (applicationExport.files.length > 0) {- throw new Error(- 'This CLI cannot reconcile exported source or dependency files.',- );- }-const identity = await readApplicationIdentity({ appPath, signal });if (diff --git a/packages/twenty-cli/src/app/pull/preserve-local-sdk-dependency.ts b/packages/twenty-cli/src/app/pull/preserve-local-sdk-dependency.tsnew file mode 100644index 00000000000..eb3b2fc45a5--- /dev/null+++ b/packages/twenty-cli/src/app/pull/preserve-local-sdk-dependency.ts@@ -0,0 +1,48 @@+import { isString } from '@sniptt/guards';+import { isPlainObject } from 'twenty-shared/utils';++const DEPENDENCY_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'peerDependencies',+];++export const preserveLocalSdkDependency = ({+ content,+ existingContent,+}: {+ content: string;+ existingContent: string;+}): string => {+ const remotePackageJson: Record<string, unknown> = JSON.parse(content);+ const localPackageJson: Record<string, unknown> = JSON.parse(existingContent);++ if (+ DEPENDENCY_FIELDS.some((field) => {+ const dependencies = remotePackageJson[field];+ return (+ isPlainObject(dependencies) && Object.hasOwn(dependencies, 'twenty-sdk')+ );+ })+ ) {+ return content;+ }++ for (const field of DEPENDENCY_FIELDS) {+ const localDependencies = localPackageJson[field];+ if (+ !isPlainObject(localDependencies) ||+ !isString(localDependencies['twenty-sdk'])+ ) {+ continue;+ }+ const remoteDependencies = remotePackageJson[field];+ remotePackageJson[field] = {+ ...(isPlainObject(remoteDependencies) ? remoteDependencies : {}),+ 'twenty-sdk': localDependencies['twenty-sdk'],+ };+ return `${JSON.stringify(remotePackageJson, null, 2)}\n`;+ }++ return content;+};diff --git a/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts b/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.tsindex 6a2f33c8208..b0ebc8bb549 100644--- a/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts+++ b/packages/twenty-cli/src/app/pull/preserve-nested-pull-entities.ts@@ -107,7 +107,8 @@ export const preserveNestedPullEntities = ({for (const change of changes) {if (skippedPaths.has(change.relativePath) ||- change.kind === 'translation'+ change.kind === 'translation' ||+ change.kind === 'dependency') {continue;}diff --git a/packages/twenty-cli/src/app/pull/pull-application.ts b/packages/twenty-cli/src/app/pull/pull-application.tsindex 6e923ba7eab..457ada6b226 100644--- a/packages/twenty-cli/src/app/pull/pull-application.ts+++ b/packages/twenty-cli/src/app/pull/pull-application.ts@@ -20,6 +20,7 @@ import { assertPullSdkExports } from '@/app/pull/assert-pull-sdk-exports';import { applyPullWrites } from '@/app/pull/apply-pull-writes';import { buildManifestEntityLabelByUniversalIdentifier } from '@/app/pull/build-manifest-entity-label-by-universal-identifier';import { planPullWrites } from '@/app/pull/plan-pull-writes';+import { planDependencyWrites } from '@/app/pull/plan-dependency-writes';import { planTranslationWrites } from '@/app/pull/plan-translation-writes';import { scanProjectSourceFiles } from '@/app/source/scan-project-source-files';import { updateSourceFingerprints } from '@/app/pull/update-source-fingerprints';@@ -100,7 +101,17 @@ export const pullApplication = async (),scannedFiles,});- const writes = [...safePlan.writes, ...translationPlan.writes];+ const dependencyPlan = await planDependencyWrites({+ appPath,+ files: applicationExport.files,+ sourceFingerprints: base.sourceFingerprints,+ dependencyFingerprints: base.dependencyFingerprints,+ });+ const writes = [+ ...safePlan.writes,+ ...translationPlan.writes,+ ...dependencyPlan.writes,+ ];const deletions = [...safePlan.deletions,...translationPlan.deletions.filter(@@ -122,8 +133,15 @@ export const pullApplication = async (protectedIdentifiers,}),unreconciledUniversalIdentifiers: [...unreconciledUniversalIdentifiers],+ dependencyFingerprints: {+ ...base.dependencyFingerprints,+ ...dependencyPlan.fingerprints,+ },sourceFingerprints: updateSourceFingerprints({- sourceFingerprints: base.sourceFingerprints,+ sourceFingerprints: {+ ...base.sourceFingerprints,+ ...dependencyPlan.unchangedSourceFingerprints,+ },writes,deletions,}),@@ -172,7 +190,7 @@ export const pullApplication = async (),deletions,overwrittenLocalChanges,- unchangedCount: plan.unchanged.length,+ unchangedCount: plan.unchanged.length + dependencyPlan.unchangedCount,localOnlyRelativePaths: plan.localOnlyRelativePaths,unreadableRelativePaths: scannedFiles.filter((file) => !file.isReadable)diff --git a/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts b/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.tsindex 3d27a80e1b5..77fd3aa7851 100644--- a/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts+++ b/packages/twenty-cli/src/app/pull/read-target-bound-pull-base.ts@@ -26,6 +26,7 @@ export const readTargetBoundPullBase = async ({manifest: ExportedManifest | null;unreconciledUniversalIdentifiers?: string[];sourceFingerprints?: Record<string, string>;+ dependencyFingerprints?: Record<string, string>;}> => {await assertPullPaths({ appPath, relativePaths: [PULL_BASE_FILE_PATH] });@@ -57,7 +58,9 @@ export const readTargetBoundPullBase = async ({isString(identifier) && isValidUniversalIdentifier(identifier),))) ||(isDefined(base.sourceFingerprints) &&- !isSourceFingerprints(base.sourceFingerprints))+ !isSourceFingerprints(base.sourceFingerprints)) ||+ (isDefined(base.dependencyFingerprints) &&+ !isSourceFingerprints(base.dependencyFingerprints))) {return { status: 'unreadable', manifest: null };}@@ -82,6 +85,9 @@ export const readTargetBoundPullBase = async ({unreconciledUniversalIdentifiers: base.unreconciledUniversalIdentifiers?.filter(isString).map((identifier) => identifier.toLowerCase()),+ dependencyFingerprints: isSourceFingerprints(base.dependencyFingerprints)+ ? base.dependencyFingerprints+ : undefined,sourceFingerprints: isSourceFingerprints(base.sourceFingerprints)? base.sourceFingerprints: undefined,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 b2dbc840e39..c8d3139bfc1 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@@ -682,6 +682,9 @@ describe('app apply', () => {applicationUniversalIdentifier: APPLICATION.universalIdentifier,manifest: EXPORTED_MANIFEST,sourceFingerprints: {+ 'package.json': createHash('sha256')+ .update(await readFile(join(appPath, 'package.json')))+ .digest('hex'),'application.ts': createHash('sha256').update('unrelated local edits').digest('hex'),@@ -725,6 +728,9 @@ describe('app apply', () => {await readFile(join(appPath, '.twenty/cli/pull-base.json'), 'utf8'),).sourceFingerprints,).toEqual({+ 'package.json': createHash('sha256')+ .update(await readFile(join(appPath, 'package.json')))+ .digest('hex'),'locales/fr-FR.json': createHash('sha256').update('{"Pet":"Animal"}').digest('hex'),diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.tsindex 2d91b587f5b..ec9b864ae5c 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts@@ -7,6 +7,7 @@ import {readdir,rm,stat,+ symlink,writeFile,} from 'node:fs/promises';import { MetadataWritability } from 'twenty-shared/types';@@ -32,6 +33,7 @@ import {parseSingleJsonLine,runCliForTest,} from '@/__tests__/utils/run-cli-for-test';+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));@@ -171,6 +173,179 @@ describe('app pull command with the packaged worker', () => {expect((await runJson()).envelope.data.writes).toEqual([]);});+ it.each([true, false])(+ 'pulls dependencies and keeps the app usable with an exported SDK dependency: %s',+ async (hasSdk) => {+ const packageJson = JSON.stringify({+ name: 'pulled-app',+ dependencies: {+ ...(hasSdk ? { 'twenty-sdk': '2.44.0' } : {}),+ lodash: '4.17.21',+ },+ });+ exported.files = [+ { folder: 'dependencies', path: 'package.json', content: packageJson },+ { folder: 'dependencies', path: 'yarn.lock', content: 'remote-lock' },+ ];++ const first = await runJson();+ expect(first.exitCode, JSON.stringify(first.envelope)).toBe(0);+ expect(+ server.requests+ .filter((request) => request.body.includes('exportApplication'))+ .map((request) => readGraphqlRequest(request).arguments),+ ).toEqual([+ {+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,+ shouldIncludeDependencies: true,+ },+ ]);+ const pulledPackageJson = await readFile(+ join(appPath, 'package.json'),+ 'utf8',+ );+ expect(JSON.parse(pulledPackageJson).dependencies).toEqual({+ 'twenty-sdk': '2.44.0',+ lodash: '4.17.21',+ });+ if (hasSdk) {+ expect(pulledPackageJson).toBe(packageJson);+ }+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(+ 'remote-lock',+ );+ expect(first.envelope.data.writes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'dependency',+ relativePath: 'package.json',+ }),+ expect.objectContaining({+ kind: 'dependency',+ relativePath: 'yarn.lock',+ }),+ ]),+ );+ expect(JSON.stringify(first.envelope.data)).not.toContain('remote-lock');++ await writeFile(join(appPath, 'yarn.lock'), 'local-lock');+ const localPackageJson = JSON.stringify({+ ...JSON.parse(pulledPackageJson),+ description: 'local edit',+ });+ await writeFile(join(appPath, 'package.json'), localPackageJson);+ const repeated = await runJson();+ expect(repeated.exitCode, JSON.stringify(repeated.envelope)).toBe(0);+ expect(repeated.envelope.data.writes).toEqual([]);+ expect(await readFile(join(appPath, 'package.json'), 'utf8')).toBe(+ localPackageJson,+ );+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(+ 'local-lock',+ );++ exported.files[1].content = 'updated-remote-lock';+ const changed = await runJson();+ expect(changed.exitCode, JSON.stringify(changed.envelope)).toBe(0);+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(+ 'updated-remote-lock',+ );+ expect(changed.envelope.data.overwrittenLocalChanges).toContainEqual({+ universalIdentifier: 'dependencies/yarn.lock',+ relativePath: 'yarn.lock',+ });++ await rm(join(appPath, 'yarn.lock'));+ expect((await runJson()).exitCode).toBe(0);+ expect(await readFile(join(appPath, 'yarn.lock'), 'utf8')).toBe(+ 'updated-remote-lock',+ );++ exported.files[0].content = JSON.stringify({+ ...JSON.parse(packageJson),+ description: 'remote edit',+ });+ const packageChanged = await runJson();+ expect(+ packageChanged.exitCode,+ JSON.stringify(packageChanged.envelope),+ ).toBe(0);+ expect(+ JSON.parse(await readFile(join(appPath, 'package.json'), 'utf8')),+ ).toMatchObject({+ description: 'remote edit',+ dependencies: { 'twenty-sdk': '2.44.0' },+ });+ expect(+ packageChanged.envelope.data.overwrittenLocalChanges,+ ).toContainEqual({+ universalIdentifier: 'dependencies/package.json',+ relativePath: 'package.json',+ });+ },+ 30_000,+ );++ it.each([+ 'source',+ 'public-asset',+ 'files-field',+ 'email-attachment',+ 'agent-chat',+ ])(+ 'rejects exported %s files without changing dependencies or metadata',+ async (folder) => {+ const originalPackageJson = await readFile(+ join(appPath, 'package.json'),+ 'utf8',+ );+ exported.files = [+ { folder: 'dependencies', path: 'package.json', content: '{}' },+ { folder, path: 'package.json', content: 'private data' },+ ];+ expect((await runJson()).envelope.error.code).toBe('TOOLING_UNSUPPORTED');+ expect(await readFile(join(appPath, 'package.json'), 'utf8')).toBe(+ originalPackageJson,+ );+ expect((await readdir(appPath)).sort()).toEqual([+ 'app.ts',+ 'node_modules',+ 'package.json',+ ]);+ },+ );++ it('refuses a dependency symlink before writing either dependency file', async () => {+ const outsidePath = `${appPath}-outside.lock`;+ const originalPackageJson = await readFile(+ join(appPath, 'package.json'),+ 'utf8',+ );+ await writeFile(outsidePath, 'outside-lock');+ await symlink(outsidePath, join(appPath, 'yarn.lock'));+ exported.files = [+ { folder: 'dependencies', path: 'package.json', content: '{}' },+ { folder: 'dependencies', path: 'yarn.lock', content: 'remote-lock' },+ ];+ try {+ const result = await runJson();+ expect(result.exitCode).not.toBe(0);+ expect(result.envelope.error.message).toContain('symbolic links');+ expect(await readFile(outsidePath, 'utf8')).toBe('outside-lock');+ expect(await readFile(join(appPath, 'package.json'), 'utf8')).toBe(+ originalPackageJson,+ );+ expect((await readdir(appPath)).sort()).toEqual([+ 'app.ts',+ 'node_modules',+ 'package.json',+ 'yarn.lock',+ ]);+ } finally {+ await rm(outsidePath, { force: true });+ }+ });+it('refuses incompatible writer exports before any destination changes', async () => {await appendFile(join(sdkPath, 'define.cjs'),@@ -253,7 +428,7 @@ export default defineObject({ nameSingular: 'invalid' });`,]);});- it('rejects exported source and dependency files before writes', async () => {+ it('rejects files outside the dependency folder before writes', async () => {exported.files.push({ folder: '.', path: 'package.json', content: '{}' });expect((await runJson()).envelope.error.code).toBe('TOOLING_UNSUPPORTED');expect((await readdir(appPath)).sort()).toEqual([diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.tsindex dee9619d111..e91eb1b8eae 100644--- a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts@@ -82,7 +82,12 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({const [workspaceId, applicationExport] = await Promise.all([fetchWorkspaceId({ target, signal }),- fetchAppExport({ universalIdentifier, target, signal }),+ fetchAppExport({+ universalIdentifier,+ target,+ signal,+ shouldIncludeDependencies: true,+ }),]);output.progress({message:@@ -241,6 +246,11 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({),]: []),+ ...(data.writes.some((write) => write.kind === 'dependency')+ ? [+ `Run ${commandText('yarn install')} to install the pulled dependencies.`,+ ]+ : []),`Run ${commandText('twenty app typecheck')} to check the generated definitions.`,].filter(Boolean)diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex bf9b354dd85..aa0ff5c6341 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -4052,7 +4052,7 @@ type Query {enterprisePortalSession(returnUrlPath: String): StringenterpriseSubscriptionStatus: EnterpriseSubscriptionStatusDTOeventLogs(input: EventLogQueryInput!): EventLogQueryResult!- exportApplication(universalIdentifier: UUID!): ApplicationExport!+ exportApplication(shouldIncludeDependencies: Boolean = false, universalIdentifier: UUID!): ApplicationExport!field("""The id of the record to find."""id: UUID!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 6050b043149..68da14594e1 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -7515,7 +7515,7 @@ export interface QueryGenqlSelection{enterprisePortalSession?: { __args: {returnUrlPath?: (Scalars['String'] | null)} } | boolean | numberenterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTOGenqlSelectioneventLogs?: (EventLogQueryResultGenqlSelection & { __args: {input: EventLogQueryInput} })- exportApplication?: (ApplicationExportGenqlSelection & { __args: {universalIdentifier: Scalars['UUID']} })+ exportApplication?: (ApplicationExportGenqlSelection & { __args: {shouldIncludeDependencies?: (Scalars['Boolean'] | null), universalIdentifier: Scalars['UUID']} })field?: (FieldGenqlSelection & { __args: {/** The id of the record to find. */id: Scalars['UUID']} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 67937a7f226..48ab97508ee 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -10755,6 +10755,9 @@ export default {"exportApplication": [51,{+ "shouldIncludeDependencies": [+ 4+ ],"universalIdentifier": [525,"UUID!"diff --git a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx b/packages/twenty-docs/developers/extend/apps/operations/cli.mdxindex 97def9b8f6b..7705a888410 100644--- a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx+++ b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx@@ -110,7 +110,7 @@ Other app commands:| `app plan` | Preview the metadata changes an apply would make || `app apply` | Build, upload and sync the app || `app generate-client` | Regenerate the typed API client without syncing |-| `app pull` | Write the installed app's metadata back to local source |+| `app pull` | Restore metadata, translations and stored dependencies || `app translations extract` | Extract translatable strings into `locales/` catalogs || `app publish` | Publish the app to npm or to a private Twenty registry || `app install` | Install an already registered app package in the workspace |diff --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 59f2ec85db5..e0106fbe26e 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@@ -24,7 +24,7 @@ Local app development revolves around **syncing**: the CLI rebuilds your manifes| Preview changes **without applying them** | `twenty app plan` | Computes and prints the diff; writes nothing. || 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. |+| Regenerate local source from the workspace | `twenty app pull` | **Experimental.** Restores define files, translations and stored dependencies. 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). || Publish to the marketplace (npm) | `twenty app publish` | — |@@ -109,7 +109,7 @@ A plan:before running it, and review the diff.</Warning>-`twenty app pull` is the inverse of `apply`: it reads an application out of the workspace and writes it back as define files.+`twenty app pull` is the inverse of `apply`: it reads an application out of the workspace and restores its define files, translations and stored dependency files.```bashtwenty app pull --universal-identifier <universalIdentifier>@@ -120,6 +120,7 @@ Pull needs an existing project — scaffold one with `twenty app init` first, th**What it writes:**- the application config;+- stored `package.json` and `yarn.lock` dependency files, at the project root;- objects, with their fields inline;- fields your app added to objects it does not own;- authored indexes;@@ -138,6 +139,10 @@ Pull needs an existing project — scaffold one with `twenty app init` first, thEach entity goes to the file that already defines it, so a second pull rewrites only what changed on the server. A file is also rewritten when it uses a different define function than pull would write, for example a role that became or stopped being the default role. New entities are placed beside existing files of their kind, and a generated name that would land on an unrelated file is qualified rather than overwriting it.+**Dependency files.** When the stored `package.json` or `yarn.lock` changes, pull replaces the local file and reports any overwritten local edits. If the remote file has not changed since the previous pull, local edits are kept. A missing remote file does not delete its local counterpart. When the exported package omits `twenty-sdk`, as the workspace Custom application does, pull retains your local SDK dependency so CLI commands can still load the project. Dependency files, metadata and the baseline are written together and rolled back together if a write fails.++Run `yarn install` after pulling dependency changes. Pull does not install packages, run package scripts or regenerate the typed client.+**What it does not write:**- **Not exported yet** — command menu items and settings menu items, logic functions and front components, connection providers, application variables, public assets, timeline activity types, and the stored source of your functions.@@ -147,14 +152,14 @@ Each entity goes to the file that already defines it, so a second pull rewrites- **Widgets the export cannot carry yet** — on any layout, including your own, a widget of the deprecated `VIEW` type, a widget showing one of your app's own front components or command menu items, or a widget without a position for its tab's layout mode is reported, and the layout or tab is written without it.- **Workflows the export cannot carry yet** — a workflow changed in the workflow builder since the last sync, a system or private workflow, one with a Code or chat message step, which application workflows don't support, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for the first and last cases: the builder publishes its workflows too, and they may call any app's actions, so they are pulled. One of its workflows is reported instead when it has no active version, or when its active version uses settings a definition can't express. Email and calendar steps are pulled: an account shared with the workspace is written as its `connectedAccountHandle`, while a member's private account and variables are kept as they are. The workflow is reported instead when a step's account is archived, can no longer run the step, or shares its address with an older account, since applying the handle would pick another account.- **Agents the export cannot carry yet** — an agent on more than one role, or bound to a role pull does not write, is reported and left in place.-- **Workspace runtime state** — member and API-key role assignments, webhooks, per-user navigation and navigation items pinned to a record, all excluded by design.+- **Workspace runtime state**, record attachments, email attachments, member and API-key role assignments, webhooks, per-user navigation and navigation items pinned to a record, all excluded by design, including for the workspace Custom application.- **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-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.-**The base file.** Pull records what it pulled in `.twenty/pull-base.json`, which is gitignored and per checkout. That file is what a later pull compares against to leave untouched the files whose entity did not change, and to delete the file of an entity that is gone from the workspace. A checkout without it simply writes everything and deletes nothing.+**The base file.** Pull records what it pulled in `.twenty/cli/pull-base.json`, which is gitignored and per checkout. That file is what a later pull compares against to leave untouched the files whose entity did not change, and to delete the file of an entity that is gone from the workspace. A checkout without it simply writes everything and deletes nothing.## Recovery ladderdiff --git a/packages/twenty-front/src/generated-metadata/schema.ts b/packages/twenty-front/src/generated-metadata/schema.tsindex 4e67642fbf3..2fe6d4ed3c6 100644--- a/packages/twenty-front/src/generated-metadata/schema.ts+++ b/packages/twenty-front/src/generated-metadata/schema.ts@@ -6002,6 +6002,7 @@ export type QueryEventLogsArgs = {export type QueryExportApplicationArgs = {+ shouldIncludeDependencies?: InputMaybe<Scalars['Boolean']['input']>;universalIdentifier: Scalars['UUID']['input'];};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 9dbee392e23..28f0c75403d 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@@ -103,13 +103,16 @@ export class ApplicationDevelopmentService {async exportApplication({universalIdentifier,workspaceId,+ shouldIncludeDependencies,}: {universalIdentifier: string;workspaceId: string;+ shouldIncludeDependencies?: boolean;}): Promise<ApplicationExport> {return this.applicationManifestExportService.exportApplication({workspaceId,applicationUniversalIdentifier: universalIdentifier,+ shouldIncludeDependencies,});}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/application-export.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/application-export.resolver.tsindex 10c867ce5b0..8e2408f9e25 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-development/application-export.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-development/application-export.resolver.ts@@ -54,12 +54,13 @@ export class ApplicationExportResolver {idKey: 'universalIdentifier',requireApplicationRegistrationOwnership: true,})- { universalIdentifier }: ExportApplicationInput,+ { universalIdentifier, shouldIncludeDependencies }: ExportApplicationInput,@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,): Promise<ApplicationExportDTO> {return this.applicationDevelopmentService.exportApplication({universalIdentifier,workspaceId,+ shouldIncludeDependencies,});}}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-development/dtos/export-application.input.ts b/packages/twenty-server/src/engine/core-modules/application/application-development/dtos/export-application.input.tsindex 576eb1c8c09..4e8ccc281ab 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-development/dtos/export-application.input.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-development/dtos/export-application.input.ts@@ -1,6 +1,6 @@import { ArgsType, Field } from '@nestjs/graphql';-import { IsNotEmpty, IsUUID } from 'class-validator';+import { IsBoolean, IsNotEmpty, IsOptional, IsUUID } from 'class-validator';import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';@@ -10,4 +10,9 @@ export class ExportApplicationInput {@IsNotEmpty()@IsUUID()universalIdentifier: string;++ @Field(() => Boolean, { nullable: true, defaultValue: false })+ @IsOptional()+ @IsBoolean()+ shouldIncludeDependencies?: boolean;}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.tsindex f1c27584fcd..a07a749f4f1 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/application-manifest-export.service.ts@@ -18,6 +18,7 @@ import { reconstructRolesManifest } from 'src/engine/core-modules/application/apimport { reconstructSkillsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-skills-manifest.util';import { reconstructViewsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-views-manifest.util';import { reconstructWorkflowsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-workflows-manifest.util';+import { ApplicationDependencyFilesService } from 'src/engine/core-modules/application/application-package/application-dependency-files.service';import { ApplicationRegistrationLookupService } from 'src/engine/core-modules/application/application-registration/application-registration-lookup/application-registration-lookup.service';import { ApplicationTranslationCacheService } from 'src/engine/core-modules/application/application-translation/application-translation-cache.service';import {@@ -47,6 +48,7 @@ const findUniversalIdentifierById = ({export class ApplicationManifestExportService {constructor(private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly applicationDependencyFilesService: ApplicationDependencyFilesService,private readonly applicationTranslationCacheService: ApplicationTranslationCacheService,private readonly applicationRegistrationLookupService: ApplicationRegistrationLookupService,private readonly applicationService: ApplicationService,@@ -56,9 +58,11 @@ export class ApplicationManifestExportService {async exportApplication({workspaceId,applicationUniversalIdentifier,+ shouldIncludeDependencies = false,}: {workspaceId: string;applicationUniversalIdentifier: string;+ shouldIncludeDependencies?: boolean;}): Promise<ApplicationExport> {const { flatApplicationMaps, ...allFlatEntityMaps } =await this.workspaceCacheService.getOrRecompute(workspaceId, [@@ -241,7 +245,14 @@ export class ApplicationManifestExportService {...skillsCoverage,],}),- files: [],+ files: shouldIncludeDependencies+ ? await this.applicationDependencyFilesService.getExportedDependencyFiles(+ {+ workspaceId,+ applicationUniversalIdentifier,+ },+ )+ : [],};}}diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/application-dependency-files.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-package/application-dependency-files.service.tsindex 802597a235a..ad62fac1a60 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-package/application-dependency-files.service.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/application-dependency-files.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';import { FileFolder } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';import { assertMatchingDependencyChecksumsOrThrow } from 'src/engine/core-modules/application/application-package/utils/assert-matching-dependency-checksums-or-throw.util';import { computeApplicationPackageChecksums } from 'src/engine/core-modules/application/application-package/utils/compute-application-package-checksums.util';@@ -27,6 +28,38 @@ type StoredDependencyFiles = {export class ApplicationDependencyFilesService {constructor(private readonly fileStorageService: FileStorageService) {}+ async getExportedDependencyFiles(identifier: ApplicationIdentifier) {+ const isPackageJsonStored = await this.fileStorageService.checkFileExists({+ ...identifier,+ fileFolder: FileFolder.Dependencies,+ resourcePath: 'package.json',+ });++ if (!isPackageJsonStored) {+ return [];+ }++ const { packageJsonContent, yarnLockContent } =+ await this.getDependencyContents(identifier);++ return [+ {+ folder: FileFolder.Dependencies,+ path: 'package.json',+ content: packageJsonContent,+ },+ ...(isDefined(yarnLockContent)+ ? [+ {+ folder: FileFolder.Dependencies,+ path: 'yarn.lock',+ content: yarnLockContent,+ },+ ]+ : []),+ ];+ }+async getVerifiedDependencyContentsOrThrow({workspaceId,applicationUniversalIdentifier,diff --git a/packages/twenty-server/test/integration/metadata/suites/application/export-application-dependencies.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/export-application-dependencies.integration-spec.tsnew file mode 100644index 00000000000..5c1df0c422a--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/export-application-dependencies.integration-spec.ts@@ -0,0 +1,151 @@+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';+import { exportApplication } from 'test/integration/metadata/suites/application/utils/export-application.util';+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { FileFolder } from 'twenty-shared/types';++import { type FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++const TEST_APP_ID = 'b1cf31ad-d8b5-4728-960b-34e02ad07a51';+const PACKAGE_JSON =+ '{\n "name": "export-dependencies", "version": "1.0.0"\n}\n';+const YARN_LOCK = '# Stored dependency lockfile\n';+const APPLICATION_IDENTIFIER = {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ applicationUniversalIdentifier: TEST_APP_ID,+};++const PACKAGE_JSON_EXPORT = {+ folder: FileFolder.Dependencies,+ path: 'package.json',+ content: PACKAGE_JSON,+};+const YARN_LOCK_EXPORT = {+ folder: FileFolder.Dependencies,+ path: 'yarn.lock',+ content: YARN_LOCK,+};++describe('Application export - dependency files', () => {+ let fileStorageService: FileStorageService;++ const writeFile = ({+ fileFolder = FileFolder.Dependencies,+ resourcePath,+ content,+ }: {+ fileFolder?: FileFolder;+ resourcePath: string;+ content: string;+ }) =>+ fileStorageService.writeFile({+ ...APPLICATION_IDENTIFIER,+ fileFolder,+ resourcePath,+ sourceFile: Buffer.from(content),+ settings: { isTemporaryFile: false, toDelete: false },+ });++ beforeAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: TEST_APP_ID,+ });+ await setupApplicationForSync({+ applicationUniversalIdentifier: TEST_APP_ID,+ name: 'Export Dependencies Test Application',+ description: 'App for testing dependency file export',+ sourcePath: 'export-dependencies',+ });+ jest.useRealTimers();+ fileStorageService =+ getAppProviderByClassName<FileStorageService>('FileStorageService');+ });++ beforeEach(async () => {+ await writeFile({ resourcePath: 'package.json', content: PACKAGE_JSON });+ await writeFile({ resourcePath: 'yarn.lock', content: YARN_LOCK });+ });++ afterAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: TEST_APP_ID,+ });+ });++ it.each([undefined, false])(+ 'keeps exports metadata-only when shouldIncludeDependencies is %s',+ async (shouldIncludeDependencies) => {+ const { data, errors } = await exportApplication({+ universalIdentifier: TEST_APP_ID,+ shouldIncludeDependencies,+ });++ expect(errors).toBeUndefined();+ expect(data.exportApplication.files).toEqual([]);+ },+ );++ it('exports only the dependency pair, preserving stored content exactly', async () => {+ for (const fileFolder of [+ FileFolder.Source,+ FileFolder.PublicAsset,+ FileFolder.FilesField,+ FileFolder.EmailAttachment,+ ]) {+ await writeFile({+ fileFolder,+ resourcePath: 'package.json',+ content: '{"private":"excluded"}',+ });+ }+ await writeFile({ resourcePath: 'other.json', content: '{}' });+ await writeFile({ resourcePath: 'nested/package.json', content: '{}' });++ const { data, errors } = await exportApplication({+ universalIdentifier: TEST_APP_ID,+ shouldIncludeDependencies: true,+ });++ expect(errors).toBeUndefined();+ expect(data.exportApplication.files).toEqual([+ PACKAGE_JSON_EXPORT,+ YARN_LOCK_EXPORT,+ ]);+ });++ it('exports package.json when no lockfile is stored', async () => {+ await fileStorageService.deleteFile({+ ...APPLICATION_IDENTIFIER,+ fileFolder: FileFolder.Dependencies,+ resourcePath: 'yarn.lock',+ });++ const { data, errors } = await exportApplication({+ universalIdentifier: TEST_APP_ID,+ shouldIncludeDependencies: true,+ });++ expect(errors).toBeUndefined();+ expect(data.exportApplication.files).toEqual([PACKAGE_JSON_EXPORT]);+ });++ it('keeps metadata available when package.json is absent', async () => {+ await fileStorageService.deleteFile({+ ...APPLICATION_IDENTIFIER,+ fileFolder: FileFolder.Dependencies,+ resourcePath: 'package.json',+ });++ const { data, errors } = await exportApplication({+ universalIdentifier: TEST_APP_ID,+ shouldIncludeDependencies: true,+ });++ expect(errors).toBeUndefined();+ expect(data.exportApplication.files).toEqual([]);+ expect(+ data.exportApplication.manifest.application.universalIdentifier,+ ).toBe(TEST_APP_ID);+ });+});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application-query-factory.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application-query-factory.util.tsindex 2eeeb6faa82..d7dc2c1df39 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application-query-factory.util.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application-query-factory.util.ts@@ -2,12 +2,20 @@ import gql from 'graphql-tag';export const exportApplicationQueryFactory = ({universalIdentifier,+ shouldIncludeDependencies,}: {universalIdentifier: string;+ shouldIncludeDependencies?: boolean;}) => ({query: gql`- query ExportApplication($universalIdentifier: UUID!) {- exportApplication(universalIdentifier: $universalIdentifier) {+ query ExportApplication(+ $universalIdentifier: UUID!+ $shouldIncludeDependencies: Boolean+ ) {+ exportApplication(+ universalIdentifier: $universalIdentifier+ shouldIncludeDependencies: $shouldIncludeDependencies+ ) {application {universalIdentifierdisplayName@@ -30,5 +38,6 @@ export const exportApplicationQueryFactory = ({`,variables: {universalIdentifier,+ shouldIncludeDependencies,},});diff --git a/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application.util.ts b/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application.util.tsindex 0927dc000aa..8901221f3db 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application.util.ts+++ b/packages/twenty-server/test/integration/metadata/suites/application/utils/export-application.util.ts@@ -9,10 +9,12 @@ import { type ApplicationExportCoverageEntryDTO } from 'src/engine/core-modules/export const exportApplication = async ({universalIdentifier,+ shouldIncludeDependencies,expectToFail = false,token,}: {universalIdentifier: string;+ shouldIncludeDependencies?: boolean;expectToFail?: boolean;token?: string;}): CommonResponseBody<{@@ -29,6 +31,7 @@ export const exportApplication = async ({}> => {const graphqlOperation = exportApplicationQueryFactory({universalIdentifier,+ shouldIncludeDependencies,});const response = await makeMetadataApiRequest(graphqlOperation, token);