Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ The `yarn twenty` CLI is your interface to everything app-related. Full command
| `dev` | Watch source files and live-sync changes | [Quick Start](/developers/extend/apps/getting-started/quick-start) |
| `plan` | Preview metadata changes without applying them | [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery#previewing-changes-plan) |
| `apply` | Apply metadata changes after showing the plan | [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery) |
| `pull` | **Experimental.** Write the installed application back to local source files | [Syncing & recovery](/developers/extend/apps/operations/sync-and-recovery#pulling-an-installed-app-back-to-source) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would deserve a pull-plan mode (ok for doing it in another PR but i would start by this personnally)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and I would like it too. Two things make me want it as a follow-up rather than here.

It needs the writer to produce content without touching the tree, which is already how it works: the planner returns the full content of every write, and applying it is a separate step. So a plan mode is mostly a flag that stops before applyPullWrites and prints the same report, plus a diff of each file against what is on disk. That diff is the part worth designing properly rather than bolting on, since the useful output is "this file would change in these ways", not just "this file would be rewritten".

The other reason is size: this PR is already flagged as too large to review reliably, so I would rather not add a surface to it.

Happy to take it as the next one if you want it before the remaining entity families.

| `dev:build` | Compile the app and generate the API client (`--tarball` to pack a `.tgz`) | [Publishing](/developers/extend/apps/operations/publishing) |
| `dev:typecheck` | Run TypeScript type checking | [Testing](/developers/extend/apps/operations/testing) |
| `dev:add` | Scaffold a new entity | [Scaffolding](/developers/extend/apps/getting-started/scaffolding) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ For day-to-day local iteration you almost always want `yarn twenty dev`. Deployi
| Sync once and exit (CI, scripts, hooks) | `yarn twenty apply` | One build + sync, then exits. Add `--force` to skip the destructive-change confirmation. |
| Preview changes **without applying them** | `yarn twenty plan` | Computes and prints the diff; writes nothing. |
| Sync without deleting anything | `yarn twenty 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`. |
| Regenerate local source from the workspace | `yarn twenty pull` | **Experimental.** Writes the installed app back to define files. See below. |
| Remove the app from the workspace | `yarn twenty app:uninstall` | Add `--yes` to skip the prompt. |
| Ship a tarball to a server | `yarn twenty app:publish --private` | Requires a **strictly higher** `package.json` version — see [Publishing](/developers/extend/apps/operations/publishing). |
| Publish to the marketplace (npm) | `yarn twenty app:publish` | — |
Expand Down Expand Up @@ -94,6 +95,40 @@ A plan:
A plan only previews **metadata** changes. It also works for an app that was never synced: the server evaluates the manifest against an empty application, so the plan lists everything your source would create.
</Note>

## Pulling an installed app back to source

<Warning>
`yarn twenty pull` is **experimental**. It covers only part of an application today, its output shape may change between releases, and it overwrites the files that define the entities it pulls. Commit your work before running it, and review the diff.
</Warning>

`yarn twenty pull` is the inverse of `apply`: it reads an application out of the workspace and writes it back as define files.

```bash
yarn twenty pull -u <universalIdentifier>
```

Pull needs an existing project — scaffold one with `npx create-twenty-app@latest` first, then pull into it. Without `-u`, pull targets the application your local `defineApplication()` file declares. Add `-v` to expand the coverage sections of the report, which then name up to 20 identifiers per metadata type instead of only the totals.

**What it writes:**

- the application config;
- objects, with their fields inline;
- fields your app added to objects it does not own;
- authored indexes.

Each entity goes to the file that already defines it, so a second pull rewrites only what changed on the server. 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.

**What it does not write:**

- **Not exported yet** — roles and permissions, views, page layouts, navigation, command menu items, logic functions and front components, and the stored source of your functions.
- **Derived by the engine** — system fields, default relations, default views and backing indexes. The server rebuilds them on apply. An object may still point its label identifier at one of them, as junction objects created in the UI do; the pointer is written and the build resolves it without adding a field.
- **Workspace runtime state** — member and API-key role assignments, webhooks and per-user navigation, 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 reason. Everything it names as not written is still in your workspace, so push a pulled tree back with `yarn twenty apply --no-delete` until the missing kinds are covered. A pruning `yarn twenty apply` would delete them, and `yarn twenty plan` lists exactly which.

**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.

## Recovery ladder

When local metadata looks wrong, escalate in this order and stop as soon as you're unblocked. Each step is more disruptive than the last.
Expand Down
25 changes: 25 additions & 0 deletions packages/twenty-sdk/src/cli/commands/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import { AppDevCommand } from './dev';
import { AppDevOnceCommand } from './dev-once';
import { registerDevFunctionCommands } from './function';
import { AppGenerateClientCommand } from './generate-client';
import { AppPullCommand } from './pull';
import { AppTranslationsExtractCommand } from './translations-extract';
import { AppTypecheckCommand } from './typecheck';

export const registerDevCommands = (program: Command): void => {
const buildCommand = new AppBuildCommand();
const devCommand = new AppDevCommand();
const devOnceCommand = new AppDevOnceCommand();
const pullCommand = new AppPullCommand();
const typecheckCommand = new AppTypecheckCommand();
const addCommand = new EntityAddCommand();
const generateClientCommand = new AppGenerateClientCommand();
Expand Down Expand Up @@ -146,6 +148,29 @@ export const registerDevCommands = (program: Command): void => {
},
);

program
.command('pull [appPath]')
.description(
'Write the installed application back to local source files (experimental)',
)
.option(
'-u, --universal-identifier <id>',
'Universal identifier of the application to pull',
)
.option('-v, --verbose', 'Show detailed logs')
.action(
async (
appPath: string | undefined,
options: { universalIdentifier?: string; verbose?: boolean },
) => {
await pullCommand.execute({
appPath: formatPath(appPath),
universalIdentifier: options.universalIdentifier,
verbose: options.verbose,
});
},
);

program
.command('dev:build [appPath]')
.description('Build and generate API client')
Expand Down
65 changes: 65 additions & 0 deletions packages/twenty-sdk/src/cli/commands/dev/pull.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { appPull } from '@/cli/operations/pull';
import { ConfigService } from '@/cli/utilities/config/config-service';
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
import { formatPullReport } from '@/cli/utilities/pull/format-pull-report';
import { PULL_BASE_FILE_PATH } from '@/cli/utilities/pull/pull-base-file';
import { checkSdkVersionCompatibility } from '@/cli/utilities/version/check-sdk-version-compatibility';
import chalk from 'chalk';

export type AppPullCommandOptions = {
appPath?: string;
universalIdentifier?: string;
verbose?: boolean;
};

export class AppPullCommand {
async execute(options: AppPullCommandOptions): Promise<void> {
const appPath = options.appPath ?? CURRENT_EXECUTION_DIRECTORY;

await checkSdkVersionCompatibility(appPath);

const remoteName = ConfigService.getActiveRemote();

console.log(
chalk.yellow(
'⚠ pull is experimental\n' +
' It covers only part of an application, and it overwrites the files\n' +
' that define what it pulls. Commit your work before running it.\n',
),
);
console.log(chalk.blue(`Pulling application from ${remoteName}...`));
console.log(chalk.gray(`App path: ${appPath}\n`));

const result = await appPull({
appPath,
universalIdentifier: options.universalIdentifier,
onProgress: (message) => console.log(chalk.gray(message)),
});

if (!result.success) {
console.error(chalk.red(result.error.message));
process.exit(1);
}

const report = formatPullReport({
writes: result.data.writes,
deletions: result.data.deletions,
unchangedCount: result.data.unchangedCount,
skipped: result.data.skipped,
coverage: result.data.coverage,
localOnlyRelativePaths: result.data.localOnlyRelativePaths,
unreadableRelativePaths: result.data.unreadableRelativePaths,
verbose: options.verbose,
});

console.log(`\n${report}\n`);

console.log(
chalk.green(
`✓ Pulled ${result.data.applicationDisplayName} into ${appPath}`,
),
);
console.log(chalk.gray(`Base recorded in ${PULL_BASE_FILE_PATH}`));
console.log(chalk.gray('Next: yarn twenty plan --no-delete'));
}
}
2 changes: 2 additions & 0 deletions packages/twenty-sdk/src/cli/operations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export type { AppDevOnceOptions, AppDevOnceResult } from './dev-once';
export { appInstall } from './install';
export type { AppInstallOptions } from './install';
export { appPublish } from './publish';
export { appPull } from './pull';
export type { AppPullOptions, AppPullResult } from './pull';
export type { AppPublishOptions, AppPublishResult } from './publish';
export { appUninstall } from './uninstall';
export type { AppUninstallOptions } from './uninstall';
Expand Down
197 changes: 197 additions & 0 deletions packages/twenty-sdk/src/cli/operations/pull.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
import { ApiService } from '@/cli/utilities/api/api-service';
import { promptForReauthentication } from '@/cli/utilities/auth/reauth-helper';
import { ManifestEntityKey } from '@/cli/utilities/build/manifest/manifest-extract-config';
import { ConfigService } from '@/cli/utilities/config/config-service';
import {
getGraphQLErrorMessage,
hasGraphQLErrorSubCode,
} from '@/cli/utilities/error/parse-server-error';
import { pathExists } from '@/cli/utilities/file/fs-utils';
import { type ApplicationExportCoverageEntry } from '@/cli/utilities/pull/application-export-type';
import { applyPullWrites } from '@/cli/utilities/pull/apply-pull-writes';
import { type SkippedPullEntity } from '@/cli/utilities/pull/build-pull-entities';
import {
planPullWrites,
type PullDeletion,
type PullWrite,
} from '@/cli/utilities/pull/plan-pull-writes';
import {
readPullBaseManifest,
writePullBaseManifest,
} from '@/cli/utilities/pull/pull-base-file';
import { scanProjectDefineFiles } from '@/cli/utilities/pull/scan-project-define-files';
import { runSafe } from '@/cli/utilities/run-safe';
import { join } from 'node:path';
import { isDefined } from 'twenty-shared/utils';

export type AppPullOptions = {
appPath: string;
universalIdentifier?: string;
onProgress?: (message: string) => void;
};

export type AppPullResult = {
applicationDisplayName: string;
applicationUniversalIdentifier: string;
writes: PullWrite[];
deletions: PullDeletion[];
unchangedCount: number;
localOnlyRelativePaths: string[];
skipped: SkippedPullEntity[];
coverage: ApplicationExportCoverageEntry[];
unreadableRelativePaths: string[];
hadBase: boolean;
};

const EXPORT_REFUSAL_SUB_CODES = [
'APPLICATION_NOT_EXPORTABLE',
'STANDARD_APPLICATION_NOT_EXPORTABLE',
'APPLICATION_NOT_FOUND',
];

const innerAppPull = async (
options: AppPullOptions,
): Promise<CommandResult<AppPullResult>> => {
const { appPath, onProgress } = options;

if (!(await pathExists(join(appPath, 'package.json')))) {
return {
success: false,
error: {
code: APP_ERROR_CODES.PULL_FAILED,
message:
`No package.json found in ${appPath}.\n\n` +
' Scaffold a project first, then pull into it:\n' +
' npx create-twenty-app@latest my-app',
},
};
}

onProgress?.('Checking server...');

const apiService = new ApiService({ disableInterceptors: true });
const validateAuth = await apiService.validateAuth();

if (!validateAuth.serverUp) {
return {
success: false,
error: {
code: APP_ERROR_CODES.PULL_FAILED,
message:
'Cannot reach Twenty server.\n\n' +
' Start a local server:\n' +
' yarn twenty docker:start\n\n' +
' Check server status:\n' +
' yarn twenty docker:status',
},
};
}

if (!validateAuth.authValid) {
const outcome = await promptForReauthentication(
ConfigService.getActiveRemote(),
);

if (outcome !== 'reauthenticated') {
return {
success: false,
error: {
code: APP_ERROR_CODES.PULL_FAILED,
message:
'Authentication failed. Run `yarn twenty remote:add` to authenticate.',
},
};
}
}

onProgress?.('Reading local source files...');

const scannedFiles = await scanProjectDefineFiles(appPath);
const localApplicationUniversalIdentifier = scannedFiles.find(
(scannedFile) => scannedFile.entityKey === ManifestEntityKey.Application,
)?.universalIdentifier;

const universalIdentifier =
options.universalIdentifier ?? localApplicationUniversalIdentifier;

if (!isDefined(universalIdentifier)) {
return {
success: false,
error: {
code: APP_ERROR_CODES.PULL_FAILED,
message:
'Could not tell which application to pull.\n\n' +
' Pass the identifier explicitly:\n' +
' yarn twenty pull -u <universalIdentifier>',
},
};
}

onProgress?.(`Exporting application ${universalIdentifier}...`);

const exportResult = await apiService.exportApplication(universalIdentifier);

if (!exportResult.success) {
const isRefusal = EXPORT_REFUSAL_SUB_CODES.some((subCode) =>
hasGraphQLErrorSubCode(exportResult.error, subCode),
);

return {
success: false,
error: {
code: APP_ERROR_CODES.PULL_FAILED,
message: isRefusal
? (getGraphQLErrorMessage(exportResult.error) ??
'The server refused to export this application')
: `Export failed: ${getGraphQLErrorMessage(exportResult.error) ?? exportResult.message ?? 'Unknown error'}`,
},
};
}

const applicationExport = exportResult.data;
const { manifest } = applicationExport;

onProgress?.('Planning source writes...');

const baseManifest = await readPullBaseManifest({
appPath,
applicationUniversalIdentifier: manifest.application.universalIdentifier,
});

const plan = planPullWrites({ manifest, baseManifest, scannedFiles });

onProgress?.('Writing source files...');

await applyPullWrites({
appPath,
writes: plan.writes,
deletions: plan.deletions,
});

await writePullBaseManifest({ appPath, manifest });

return {
success: true,
data: {
applicationDisplayName: applicationExport.application.displayName,
applicationUniversalIdentifier:
applicationExport.application.universalIdentifier,
writes: plan.writes,
deletions: plan.deletions,
unchangedCount: plan.unchanged.length,
localOnlyRelativePaths: plan.localOnlyRelativePaths,
skipped: plan.skipped,
coverage: applicationExport.coverage,
unreadableRelativePaths: scannedFiles
.filter((scannedFile) => !scannedFile.isReadable)
.map((scannedFile) => scannedFile.relativePath),
hadBase: isDefined(baseManifest),
},
};
};

export const appPull = (
options: AppPullOptions,
): Promise<CommandResult<AppPullResult>> =>
runSafe(() => innerAppPull(options), APP_ERROR_CODES.PULL_FAILED);
1 change: 1 addition & 0 deletions packages/twenty-sdk/src/cli/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const APP_ERROR_CODES = {
APPLY_ABORTED: 'APPLY_ABORTED',
TYPECHECK_FAILED: 'TYPECHECK_FAILED',
DEPLOY_FAILED: 'DEPLOY_FAILED',
PULL_FAILED: 'PULL_FAILED',
} as const;

export const SERVER_ERROR_CODES = {
Expand Down
Loading
Loading