The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Export application agents and skills for twenty app pull (#28971)
Félix Malfaite51b61ecb88d
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex f915dca05ac..ee487f4f565 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -432,7 +432,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. 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 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. 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 created in the workspace, 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.## Install a registered appdiff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.mdindex 8e4dad74c4e..e7ba18a3d17 100644--- a/packages/twenty-cli/src/app/pull/README.md+++ b/packages/twenty-cli/src/app/pull/README.md@@ -25,6 +25,8 @@ Translation string extraction uses the CLI's TypeScript parser. Traversal, statiWorkflows arrive in `manifest.workflows` and are written as `defineWorkflow` files. Their filter operands and form field types use SDK enums; filter group logical operators stay string literals, which every SDK with `defineWorkflow` accepts. A workflow the server cannot express as a definition is reported as `UNSUPPORTED` coverage, so its local file is kept.+Skills 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.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__/build-pull-entities.spec.ts b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.tsindex 2e90cb99184..36fffcda154 100644--- a/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts+++ b/packages/twenty-cli/src/app/pull/__tests__/build-pull-entities.spec.ts@@ -62,6 +62,8 @@ const LEGACY_OBJECT_PERMISSION_UID = '60606060-6060-4606-8606-606060606060';const WORKFLOW_UID = '70707070-7070-4707-8707-707070707070';const WORKFLOW_TRIGGER_UID = '80808080-8080-4808-8808-808080808080';const WORKFLOW_STEP_UID = '90909090-9090-4909-8909-909090909090';+const AGENT_UID = 'a0a0a0a0-a0a0-4a0a-8a0a-a0a0a0a0a0a0';+const SKILL_UID = 'b0b0b0b0-b0b0-4b0b-8b0b-b0b0b0b0b0b0';const APPLICATION_WITH_SUPPORT_DEFAULT_ROLE = {universalIdentifier: APP_UID,@@ -981,6 +983,48 @@ describe('buildPullEntities', () => {).toBe('70707070');});+ it('should write agents into src/agents and skills into src/skills verbatim, named after their name', () => {+ const agent = {+ universalIdentifier: AGENT_UID,+ name: 'pet-groomer',+ label: 'Pet Groomer',+ prompt: 'Plan the grooming.',+ responseFormat: { type: 'text' as const },+ };+ const skill = {+ universalIdentifier: SKILL_UID,+ name: 'grooming-tips',+ label: 'Grooming Tips',+ content: 'Brush first.',+ };+ const { entities, skipped } = buildPullEntities(+ buildManifest({ agents: [agent], skills: [skill] }),+ );+ const pathOf = (kind: string) => {+ const entity = entities.find((candidate) => candidate.kind === kind);++ return `${entity?.defaultFolder}/${entity?.fileBaseName}${entity?.fileSuffix}`;+ };++ expect(skipped).toEqual([]);+ expect(entities.find((entity) => entity.kind === 'agent')).toMatchObject({+ universalIdentifier: AGENT_UID,+ definer: 'defineAgent',+ config: agent,+ enumBindings: [],+ parentName: null,+ });+ expect(entities.find((entity) => entity.kind === 'skill')).toMatchObject({+ universalIdentifier: SKILL_UID,+ definer: 'defineSkill',+ config: skill,+ enumBindings: [],+ parentName: null,+ });+ expect(pathOf('agent')).toBe('src/agents/pet-groomer.agent.ts');+ expect(pathOf('skill')).toBe('src/skills/grooming-tips.skill.ts');+ });+it('should build a manifest that has no views, view fields, page layouts and page layout tabs properties without producing their entities', () => {const {views: _views,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 6019289254d..763f41d5ec7 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@@ -37,6 +37,9 @@ const STANDALONE_FIELD_PATH = 'src/fields/rating.ts';const WORKFLOW_IDENTIFIER = 'acacacac-acac-4aca-8aca-acacacacacac';const WORKFLOW_TRIGGER_IDENTIFIER = 'adadadad-adad-4ada-8ada-adadadadadad';const WORKFLOW_STEP_IDENTIFIER = 'aeaeaeae-aeae-4aea-8aea-aeaeaeaeaeae';+const AGENT_IDENTIFIER = 'afafafaf-afaf-4afa-8afa-afafafafafaf';+const AGENT_TRIGGER_IDENTIFIER = 'bcbcbcbc-bcbc-4bcb-8bcb-bcbcbcbcbcbc';+const SKILL_IDENTIFIER = 'bdbdbdbd-bdbd-4bdb-8bdb-bdbdbdbdbdbd';const TARGET: AppPullTarget = {apiUrl: 'https://example.test',workspaceId: WORKSPACE_IDENTIFIER,@@ -811,6 +814,125 @@ export default defineField({await expect(read(workflowPath)).rejects.toMatchObject({ code: 'ENOENT' });});+ it('writes agents and skills, keeps them while unchanged or unsupported and removes confirmed remote deletions', async () => {+ const agentPath = 'src/agents/pet-groomer.agent.ts';+ const skillPath = 'src/skills/grooming-tips.skill.ts';+ const agent = {+ universalIdentifier: AGENT_IDENTIFIER,+ name: 'pet-groomer',+ label: 'Pet Groomer',+ prompt: 'Plan the grooming of new pets.',+ responseFormat: { type: 'text' },+ roleUniversalIdentifier: OTHER_IDENTIFIER,+ triggers: [+ {+ universalIdentifier: AGENT_TRIGGER_IDENTIFIER,+ type: 'DATABASE_EVENT',+ settings: { eventName: 'pet.created' },+ },+ ],+ };+ const skill = {+ universalIdentifier: SKILL_IDENTIFIER,+ name: 'grooming-tips',+ label: 'Grooming Tips',+ content: 'Brush first.\nThen bathe.',+ };+ const withAgentAndSkill = ({+ agentManifest = agent,+ coverage = [],+ }: {+ agentManifest?: typeof agent;+ coverage?: AppExportCoverageEntry[];+ } = {}) => {+ const exported = createExport({ coverage });++ return {+ ...exported,+ manifest: {+ ...exported.manifest,+ agents: [agentManifest],+ skills: [skill],+ },+ };+ };++ const created = requireSuccess(await pull(withAgentAndSkill()));+ expect(created.writes).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ relativePath: agentPath, kind: 'agent' }),+ expect.objectContaining({ relativePath: skillPath, kind: 'skill' }),+ ]),+ );+ expect(await read(agentPath)).toContain(+ "import { defineAgent } from 'twenty-sdk/define';",+ );+ expect(await read(agentPath)).toContain("eventName: 'pet.created',");+ expect(await read(skillPath)).toContain(+ "content: 'Brush first.\\nThen bathe.',",+ );++ const localEdit = (await read(agentPath)).replace(+ "label: 'Pet Groomer',",+ "label: 'Pet Groomer',\n",+ );+ await writeFile(join(appPath, agentPath), localEdit);+ expect(requireSuccess(await pull(withAgentAndSkill())).writes).toEqual([]);+ expect(await read(agentPath)).toBe(localEdit);++ const changed = requireSuccess(+ await pull(+ withAgentAndSkill({+ agentManifest: { ...agent, prompt: 'Groom every pet weekly.' },+ }),+ ),+ );+ expect(changed.writes).toEqual([+ expect.objectContaining({+ relativePath: agentPath,+ isRegeneration: true,+ }),+ ]);+ expect(await read(agentPath)).toContain(+ "prompt: 'Groom every pet weekly.',",+ );++ const unsupported = createExport({+ coverage: [+ {+ metadataName: 'agent',+ universalIdentifier: AGENT_IDENTIFIER,+ status: 'UNSUPPORTED',+ reason:+ 'agent with values a definition cannot express: modelConfiguration',+ },+ {+ metadataName: 'skill',+ universalIdentifier: SKILL_IDENTIFIER,+ status: 'UNSUPPORTED',+ reason: 'skill deactivated in this workspace',+ },+ ],+ });+ const kept = requireSuccess(await pull(unsupported));+ expect(kept.deletions).toEqual([]);+ expect(await read(agentPath)).toContain(+ "prompt: 'Groom every pet weekly.',",+ );+ expect(await read(skillPath)).toContain("name: 'grooming-tips',");++ const removed = requireSuccess(await pull(createExport()));+ expect(removed.deletions).toEqual(+ expect.arrayContaining([+ { universalIdentifier: AGENT_IDENTIFIER, relativePath: agentPath },+ { universalIdentifier: SKILL_IDENTIFIER, relativePath: skillPath },+ ]),+ );+ expect(removed.deletions).toHaveLength(2);+ await expect(read(agentPath)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(read(skillPath)).rejects.toMatchObject({ code: 'ENOENT' });+ });+it('retains a covered whole-file base until its remote deletion is confirmed', async () => {requireSuccess(await pull());const partialExport = createExport({diff --git a/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.tsindex 558fff7cc72..675d21ccb8f 100644--- a/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts+++ b/packages/twenty-cli/src/app/pull/assert-pull-sdk-exports.ts@@ -3,6 +3,7 @@ import { join } from 'node:path';import { isDefined } from 'twenty-shared/utils';import { type PullWrite } from '@/app/pull/plan-pull-writes';+import { PULL_MINIMUM_SDK_VERSION } from '@/app/pull/pull-minimum-sdk-version.constant';import { CliError } from '@/output/cli-error';export const assertPullSdkExports = ({@@ -32,7 +33,7 @@ export const assertPullSdkExports = ({throw new CliError({code: 'SDK_SOURCE_UNSUPPORTED',message: `The app's twenty-sdk cannot read the generated definitions. Missing exports: ${missingNames.join(', ')}.`,- hint: 'Upgrade the app to a compatible twenty-sdk version (2.50.0 or later).',+ hint: `Upgrade the app to a compatible twenty-sdk version (${PULL_MINIMUM_SDK_VERSION} or later).`,details: { missingNames },});}diff --git a/packages/twenty-cli/src/app/pull/build-pull-entities.ts b/packages/twenty-cli/src/app/pull/build-pull-entities.tsindex 062e4564c35..e13d3c0574b 100644--- a/packages/twenty-cli/src/app/pull/build-pull-entities.ts+++ b/packages/twenty-cli/src/app/pull/build-pull-entities.ts@@ -45,6 +45,8 @@ export const PULL_ENTITY_KINDS = ['navigationMenuItem','pageLayoutWidget','workflow',+ 'skill',+ 'agent',] as const;export type PullEntityKind = (typeof PULL_ENTITY_KINDS)[number];@@ -390,5 +392,39 @@ export const buildPullEntities = (});}+ for (const skillManifest of manifest.skills ?? []) {+ entities.push({+ kind: 'skill',+ universalIdentifier: skillManifest.universalIdentifier,+ definer: 'defineSkill',+ config: skillManifest,+ enumBindings: [],+ defaultFolder: 'src/skills',+ fileSuffix: '.skill.ts',+ fileBaseName: toFileBaseName({+ segments: [skillManifest.name],+ universalIdentifier: skillManifest.universalIdentifier,+ }),+ parentName: null,+ });+ }++ for (const agentManifest of manifest.agents ?? []) {+ entities.push({+ kind: 'agent',+ universalIdentifier: agentManifest.universalIdentifier,+ definer: 'defineAgent',+ config: agentManifest,+ enumBindings: [],+ defaultFolder: 'src/agents',+ fileSuffix: '.agent.ts',+ fileBaseName: toFileBaseName({+ segments: [agentManifest.name],+ universalIdentifier: agentManifest.universalIdentifier,+ }),+ parentName: null,+ });+ }+return { entities, skipped };};diff --git a/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.tsindex 625750629e2..a7cc073450a 100644--- a/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts+++ b/packages/twenty-cli/src/app/pull/entity-key-by-kind.constant.ts@@ -15,4 +15,6 @@ export const ENTITY_KEY_BY_KIND: Record<PullEntityKind, ManifestEntityKey> = {navigationMenuItem: 'navigationMenuItems',pageLayoutWidget: 'pageLayoutWidgets',workflow: 'workflows',+ skill: 'skills',+ agent: 'agents',};diff --git a/packages/twenty-cli/src/app/pull/pull-minimum-sdk-version.constant.ts b/packages/twenty-cli/src/app/pull/pull-minimum-sdk-version.constant.tsnew file mode 100644index 00000000000..9d9bb7a3414--- /dev/null+++ b/packages/twenty-cli/src/app/pull/pull-minimum-sdk-version.constant.ts@@ -0,0 +1 @@+export const PULL_MINIMUM_SDK_VERSION = '2.50.0';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 b6d8223e9ce..dee9619d111 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@@ -7,6 +7,7 @@ import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';import { parseToolingResult } from '@/app/parse-tooling-result';import { formatPullReport } from '@/app/pull/format-pull-report';import { parsePullData } from '@/app/pull/parse-pull-data';+import { PULL_MINIMUM_SDK_VERSION } from '@/app/pull/pull-minimum-sdk-version.constant';import { readAppIdentity } from '@/app/read-app-identity';import { resolveAppProject } from '@/app/project/resolve-app-project';import { runAppWorker } from '@/app/run-app-worker';@@ -142,7 +143,7 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({hint:result.error.hint ??(result.error.code === 'SDK_SOURCE_UNSUPPORTED'- ? 'Upgrade the app to a compatible twenty-sdk version (2.50.0 or later).'+ ? `Upgrade the app to a compatible twenty-sdk version (${PULL_MINIMUM_SDK_VERSION} or later).`: undefined),details: { ...result.error.details, diagnostics },});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 9ee46cd907a..94619897a04 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@@ -131,18 +131,21 @@ Pull needs an existing project — scaffold one with `twenty app init` first, th- navigation menu items, as `defineNavigationMenuItem()` files, folders included;- widgets your app added to tabs it does not own, as standalone `definePageLayoutWidget()` files;- workflows, as `defineWorkflow()` files, when their stored version is the one the last sync wrote;+- skills, as `defineSkill()` files;+- agents, as `defineAgent()` files, with their triggers and the role your app binds them to;- published translations, as `locales/<locale>.json` for the strings pull can read back from the pulled metadata and source, and `locales/compiled/<locale>.json` for the rest.Each 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.**What it does not write:**-- **Not exported yet** — command menu items and settings menu items, logic functions and front components, skills and agents, connection providers, application variables, public assets, timeline activity types, and the stored source of your functions.+- **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.- **Derived by the engine** — system fields, default relations, default views and backing indexes, and the default page layouts of each object. 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.- **Placed on a default or foreign view** — filters, filter groups, sorts, groups and field groups added to an engine default view, or to a view owned by another application, have no source form yet and are reported. View fields added there are written as standalone files, since the view's identifier is known.- **Placed on a default or foreign page layout** — tabs and widgets added to an engine default page layout, or to one owned by another application, are written as standalone `definePageLayoutTab()` and `definePageLayoutWidget()` files, since the identifier they attach to is known.- **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, one built in the workspace, a system or private workflow, one with a Code or chat message step, which application workflows don't support, or an email or calendar step, which export doesn't carry yet, and one calling another app's workflow action are reported and left in place. The workspace custom application is the exception for that last case: its workflows may call any app's actions, so they are pulled.+- **Agents and skills the export cannot carry yet** — agents and skills created in the workspace rather than by your app, a deactivated skill, and an agent with a model configuration or bound to a role pull does not write are 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.- **Owned by another application** — reported, never pulled.diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.tsnew file mode 100644index 00000000000..50c95c2998e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-agent-to-agent-manifest.util.spec.ts@@ -0,0 +1,125 @@+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';+import { type AgentManifest } from 'twenty-shared/application';++import { fromFlatAgentToAgentManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util';+import { fromAgentManifestToUniversalFlatAgent } from 'src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util';+import { type UniversalFlatAgent } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-agent.type';+import { compareTwoFlatEntity } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/compare-two-universal-flat-entity.util';++const APP_UID = '11111111-1111-4111-8111-111111111111';+const AGENT_UID = '22222222-2222-4222-8222-222222222222';+const ROLE_UID = '33333333-3333-4333-8333-333333333333';+const CRON_TRIGGER_UID = '44444444-4444-4444-8444-444444444444';+const DATABASE_EVENT_TRIGGER_UID = '55555555-5555-4555-8555-555555555555';+const NOW = '2026-09-14T10:00:00.000Z';++const AGENT_MANIFEST: Required<AgentManifest> = {+ universalIdentifier: AGENT_UID,+ name: 'lead-scorer',+ label: 'Lead Scorer',+ icon: 'IconRobot',+ description: 'Scores new leads',+ prompt: 'Score the lead and explain your reasoning.',+ modelId: 'gpt-4o',+ responseFormat: {+ type: 'json',+ schema: {+ type: 'object',+ properties: { score: { type: 'number', description: 'From 0 to 100' } },+ required: ['score'],+ additionalProperties: false,+ },+ },+ roleUniversalIdentifier: ROLE_UID,+ triggers: [+ {+ universalIdentifier: CRON_TRIGGER_UID,+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ isActive: false,+ instructions: 'Rescore stale leads',+ },+ {+ universalIdentifier: DATABASE_EVENT_TRIGGER_UID,+ type: 'DATABASE_EVENT',+ settings: {+ eventName: 'company.updated',+ updatedFields: ['name'],+ batchMode: true,+ },+ },+ ],+};++const MINIMAL_AGENT_MANIFEST: AgentManifest = {+ universalIdentifier: AGENT_UID,+ name: 'assistant',+ label: 'Assistant',+ prompt: 'Help the user.',+ responseFormat: { type: 'text' },+};++const forward = (agentManifest: AgentManifest) =>+ fromAgentManifestToUniversalFlatAgent({+ agentManifest,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ });++describe('fromFlatAgentToAgentManifest', () => {+ it('should reproduce the manifest after a forward then an inverse conversion', () => {+ expect(+ fromFlatAgentToAgentManifest({+ flatAgent: forward(AGENT_MANIFEST),+ roleUniversalIdentifier: ROLE_UID,+ }),+ ).toEqual(AGENT_MANIFEST);+ });++ it('should reproduce the flat entity after an inverse then a forward conversion', () => {+ const flatAgent: UniversalFlatAgent = {+ ...forward(AGENT_MANIFEST),+ icon: null,+ description: null,+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ triggers: [+ {+ id: CRON_TRIGGER_UID,+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ isActive: true,+ instructions: null,+ },+ ],+ };++ expect(+ compareTwoFlatEntity({+ fromUniversalFlatEntity: flatAgent,+ toUniversalFlatEntity: forward(+ fromFlatAgentToAgentManifest({ flatAgent }),+ ),+ metadataName: 'agent',+ }),+ ).toBeUndefined();+ });++ it('should omit what the forward conversion defaults: icon, description, the workspace default model, triggers and the role', () => {+ expect(+ fromFlatAgentToAgentManifest({+ flatAgent: forward(MINIMAL_AGENT_MANIFEST),+ }),+ ).toStrictEqual(MINIMAL_AGENT_MANIFEST);+ });++ it('should keep a text response format so the definition does not rely on its default', () => {+ const { responseFormat: _responseFormat, ...manifestWithoutFormat } =+ MINIMAL_AGENT_MANIFEST;++ expect(+ fromFlatAgentToAgentManifest({+ flatAgent: forward(manifestWithoutFormat),+ }).responseFormat,+ ).toEqual({ type: 'text' });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-skill-to-skill-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-skill-to-skill-manifest.util.spec.tsnew file mode 100644index 00000000000..a9f76af698c--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-flat-skill-to-skill-manifest.util.spec.ts@@ -0,0 +1,66 @@+import { type SkillManifest } from 'twenty-shared/application';++import { fromFlatSkillToSkillManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util';+import { fromSkillManifestToUniversalFlatSkill } from 'src/engine/core-modules/application/application-manifest/converters/from-skill-manifest-to-universal-flat-skill.util';+import { type UniversalFlatSkill } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-skill.type';+import { compareTwoFlatEntity } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/compare-two-universal-flat-entity.util';++const APP_UID = '11111111-1111-4111-8111-111111111111';+const SKILL_UID = '22222222-2222-4222-8222-222222222222';+const NOW = '2026-09-14T10:00:00.000Z';++const SKILL_MANIFEST: Required<SkillManifest> = {+ universalIdentifier: SKILL_UID,+ name: 'sales-outreach',+ label: 'Sales Outreach',+ icon: 'IconBrain',+ description: 'Guides a structured outreach',+ content: 'Research the company, then draft a message.',+};++const forward = (skillManifest: SkillManifest) =>+ fromSkillManifestToUniversalFlatSkill({+ skillManifest,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ });++describe('fromFlatSkillToSkillManifest', () => {+ it('should reproduce the manifest after a forward then an inverse conversion', () => {+ expect(+ fromFlatSkillToSkillManifest({ flatSkill: forward(SKILL_MANIFEST) }),+ ).toEqual(SKILL_MANIFEST);+ });++ it('should reproduce the flat entity after an inverse then a forward conversion', () => {+ const flatSkill: UniversalFlatSkill = {+ ...forward(SKILL_MANIFEST),+ icon: null,+ description: null,+ };++ expect(+ compareTwoFlatEntity({+ fromUniversalFlatEntity: flatSkill,+ toUniversalFlatEntity: forward(+ fromFlatSkillToSkillManifest({ flatSkill }),+ ),+ metadataName: 'skill',+ }),+ ).toBeUndefined();+ });++ it('should omit the icon and description of a skill stored without them', () => {+ const {+ icon: _icon,+ description: _description,+ ...manifestWithoutIconAndDescription+ } = SKILL_MANIFEST;++ expect(+ fromFlatSkillToSkillManifest({+ flatSkill: forward(manifestWithoutIconAndDescription),+ }),+ ).toStrictEqual(manifestWithoutIconAndDescription);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util.tsnew file mode 100644index 00000000000..ee2c97d9748--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util.ts@@ -0,0 +1,63 @@+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';+import {+ type AgentManifest,+ type AgentTrigger,+ type AgentTriggerManifest,+} from 'twenty-shared/application';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';++import { type UniversalFlatAgent } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-agent.type';++const fromAgentTriggerToAgentTriggerManifest = ({+ id,+ isActive,+ instructions,+ ...trigger+}: AgentTrigger): AgentTriggerManifest => ({+ universalIdentifier: id,+ ...trigger,+ ...(isActive ? {} : { isActive }),+ ...(isDefined(instructions) ? { instructions } : {}),+});++export const fromFlatAgentToAgentManifest = ({+ flatAgent,+ roleUniversalIdentifier,+}: {+ flatAgent: Pick<+ UniversalFlatAgent,+ | 'universalIdentifier'+ | 'name'+ | 'label'+ | 'icon'+ | 'description'+ | 'prompt'+ | 'modelId'+ | 'responseFormat'+ | 'triggers'+ >;+ roleUniversalIdentifier?: string;+}): AgentManifest => ({+ universalIdentifier: flatAgent.universalIdentifier,+ name: flatAgent.name,+ label: flatAgent.label,+ ...(isDefined(flatAgent.icon) ? { icon: flatAgent.icon } : {}),+ ...(isDefined(flatAgent.description)+ ? { description: flatAgent.description }+ : {}),+ prompt: flatAgent.prompt,+ ...(flatAgent.modelId === AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID+ ? {}+ : { modelId: flatAgent.modelId }),+ ...(isDefined(flatAgent.responseFormat)+ ? { responseFormat: flatAgent.responseFormat }+ : {}),+ ...(isDefined(roleUniversalIdentifier) ? { roleUniversalIdentifier } : {}),+ ...(isNonEmptyArray(flatAgent.triggers)+ ? {+ triggers: flatAgent.triggers.map(+ fromAgentTriggerToAgentTriggerManifest,+ ),+ }+ : {}),+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util.tsnew file mode 100644index 00000000000..5e5b8d8f61a--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util.ts@@ -0,0 +1,27 @@+import { type SkillManifest } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { type UniversalFlatSkill } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-skill.type';++export const fromFlatSkillToSkillManifest = ({+ flatSkill,+}: {+ flatSkill: Pick<+ UniversalFlatSkill,+ | 'universalIdentifier'+ | 'name'+ | 'label'+ | 'icon'+ | 'description'+ | 'content'+ >;+}): SkillManifest => ({+ universalIdentifier: flatSkill.universalIdentifier,+ name: flatSkill.name,+ label: flatSkill.label,+ ...(isDefined(flatSkill.icon) ? { icon: flatSkill.icon } : {}),+ ...(isDefined(flatSkill.description)+ ? { description: flatSkill.description }+ : {}),+ content: flatSkill.content,+});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 d3373c513a7..12c0d96c716 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@@ -9,11 +9,13 @@ import { type ApplicationExport } from 'src/engine/core-modules/application/applimport { assertFlatApplicationIsExportable } from 'src/engine/core-modules/application/application-manifest/utils/assert-flat-application-is-exportable.util';import { classifyApplicationFlatEntities } from 'src/engine/core-modules/application/application-manifest/utils/classify-application-flat-entities.util';import { getApplicationSubAllFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/get-application-sub-all-flat-entity-maps.util';+import { reconstructAgentsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-agents-manifest.util';import { reconstructDataModelManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-data-model-manifest.util';import { getResolvableReferenceUniversalIdentifiers } from 'src/engine/core-modules/application/application-manifest/utils/get-resolvable-reference-universal-identifiers.util';import { reconstructNavigationMenuItemsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-navigation-menu-items-manifest.util';import { reconstructPageLayoutsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-page-layouts-manifest.util';import { reconstructRolesManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-roles-manifest.util';+import { 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 { ApplicationRegistrationLookupService } from 'src/engine/core-modules/application/application-registration/application-registration-lookup/application-registration-lookup.service';@@ -160,6 +162,18 @@ export class ApplicationManifestExportService {canReferenceOtherApplicationsWorkflowActions:flatApplication.id === workspaceCustomFlatApplication.id,});+ const { agents, coverage: agentsCoverage } = reconstructAgentsManifest({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ resolvableRoleUniversalIdentifiers:+ getResolvableReferenceUniversalIdentifiers({+ coverage: rolesCoverage,+ metadataName: 'role',+ }),+ });+ const { skills, coverage: skillsCoverage } = reconstructSkillsManifest({+ applicationAllFlatEntityMaps,+ });const translations = isDefined(flatApplication.applicationRegistrationId)? await this.applicationTranslationCacheService.getCatalogsByLocale(flatApplication.applicationRegistrationId,@@ -182,8 +196,8 @@ export class ApplicationManifestExportService {frontComponents: [],permissionFlags,roles,- skills: [],- agents: [],+ skills,+ agents,publicAssets: [],views,viewFields,@@ -216,6 +230,8 @@ export class ApplicationManifestExportService {...pageLayoutsCoverage,...navigationMenuItemsCoverage,...workflowsCoverage,+ ...agentsCoverage,+ ...skillsCoverage,],}),files: [],diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.tsindex 68a1fb26160..b35b1c5c0af 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/export-covers-compared-properties.spec.ts@@ -1,4 +1,5 @@import {+ type AgentManifest,type FieldPermissionManifest,type NavigationMenuItemManifest,type ObjectPermissionManifest,@@ -16,6 +17,7 @@ import {type ViewFilterManifest,type ViewGroupManifest,type ViewManifest,+ type SkillManifest,type ViewSortManifest,type WorkflowManifest,} from 'twenty-shared/application';@@ -38,6 +40,10 @@ import {} from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';+import { fromFlatAgentToAgentManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util';+import { fromFlatSkillToSkillManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util';+import { fromSkillManifestToUniversalFlatSkill } from 'src/engine/core-modules/application/application-manifest/converters/from-skill-manifest-to-universal-flat-skill.util';+import { fromAgentManifestToUniversalFlatAgent } from 'src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util';import { fromFieldPermissionManifestToUniversalFlatFieldPermission } from 'src/engine/core-modules/application/application-manifest/converters/from-field-permission-manifest-to-universal-flat-field-permission.util';import { fromFlatFieldMetadataToFieldManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-field-metadata-to-field-manifest.util';import { fromFlatFieldPermissionToFieldPermissionManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-field-permission-to-field-permission-manifest.util';@@ -393,6 +399,43 @@ const exportWorkflowManifestOrThrow = (manifest: WorkflowManifest) => {return conversion.manifest;};+const AGENT_MANIFEST: AgentManifest = {+ universalIdentifier: APP_UID,+ name: 'lead-scorer',+ label: 'Lead Scorer',+ icon: 'IconRobot',+ description: 'Scores new leads',+ prompt: 'Score the lead.',+ modelId: 'gpt-4o',+ responseFormat: { type: 'text' },+ roleUniversalIdentifier: OBJECT_UID,+ triggers: [+ {+ universalIdentifier: FIELD_UID,+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ },+ ],+};++const EXPORTED_AGENT_MANIFEST = fromFlatAgentToAgentManifest({+ flatAgent: fromAgentManifestToUniversalFlatAgent({+ agentManifest: AGENT_MANIFEST,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ }),+ roleUniversalIdentifier: AGENT_MANIFEST.roleUniversalIdentifier,+});++const SKILL_MANIFEST: SkillManifest = {+ universalIdentifier: APP_UID,+ name: 'sales-outreach',+ label: 'Sales Outreach',+ icon: 'IconBrain',+ description: 'Guides an outreach',+ content: 'Research the company first.',+};+type ExportedKind = {metadataName: keyof typeof ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY;emittedProperties: string[];@@ -813,6 +856,50 @@ const EXPORTED_KINDS: ExportedKind[] = ['the sync points it at the version it derives from the definition',},},+ {+ metadataName: 'agent',+ emittedProperties: Object.keys(EXPORTED_AGENT_MANIFEST),+ renamedProperties: {},+ workspaceLocalProperties: [],+ knownGaps: {+ modelConfiguration:+ 'no manifest slot; an agent with one is reported as unsupported',+ isSystem:+ 'always true for application agents; any other value is reported as unsupported',+ },+ },+ {+ metadataName: 'roleTarget',+ emittedProperties: Object.keys(EXPORTED_AGENT_MANIFEST),+ renamedProperties: { agentUniversalIdentifier: 'universalIdentifier' },+ workspaceLocalProperties: [],+ knownGaps: {+ userWorkspaceId:+ 'member role assignments are reported as excluded, only agent roles are exported',+ apiKeyId:+ 'API key role assignments are reported as excluded, only agent roles are exported',+ },+ },+ {+ metadataName: 'skill',+ emittedProperties: Object.keys(+ fromFlatSkillToSkillManifest({+ flatSkill: fromSkillManifestToUniversalFlatSkill({+ skillManifest: SKILL_MANIFEST,+ applicationUniversalIdentifier: APP_UID,+ now: NOW,+ }),+ }),+ ),+ renamedProperties: {},+ workspaceLocalProperties: [],+ knownGaps: {+ isActive:+ 'no manifest slot and no overrides; a deactivated skill is reported as unsupported',+ isSystem:+ 'always false for application skills; any other value is reported as unsupported',+ },+ },];describe('export coverage of the compared properties', () => {diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-agents-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-agents-manifest.util.spec.tsnew file mode 100644index 00000000000..21ba9391691--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-agents-manifest.util.spec.ts@@ -0,0 +1,389 @@+import {+ type AgentManifest,+ getRoleTargetUniversalIdentifier,+} from 'twenty-shared/application';++import { fromAgentManifestToUniversalFlatRoleTarget } from 'src/engine/core-modules/application/application-manifest/converters/from-agent-manifest-to-universal-flat-role-target.util';+import { fromRoleManifestToUniversalFlatRole } from 'src/engine/core-modules/application/application-manifest/converters/from-role-manifest-to-universal-flat-role.util';+import { addAllFlatEntitiesToFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/__tests__/add-all-flat-entities-to-flat-entity-maps.test-util';+import { reconstructAgentsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-agents-manifest.util';+import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';+import { fromAgentManifestToUniversalFlatAgent } from 'src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util';+import { type FlatAgent } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';+import { type FlatRoleTarget } from 'src/engine/metadata-modules/flat-role-target/types/flat-role-target.type';+import { type FlatRole } from 'src/engine/metadata-modules/flat-role/types/flat-role.type';++const APP_ID = 'application-id';+const STANDARD_APP_ID = 'standard-application-id';+const WORKSPACE_ID = 'workspace-id';+const NOW = '2026-09-14T10:00:00.000Z';+const APP_UNIVERSAL_IDENTIFIER = '10000000-0000-4000-8000-000000000001';+const SUPPORT_ROLE_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000001';+const UNSUPPORTED_ROLE_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000002';+const STANDARD_ROLE_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000003';+const MISSING_ROLE_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000004';+const SUPPORT_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000001';+const STANDARD_ROLE_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000002';+const UNSUPPORTED_ROLE_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000003';+const MISSING_ROLE_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000004';+const TWO_ROLES_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000005';+const WORKSPACE_ROLE_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000006';+const CONFIGURED_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000007';+const DELETED_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000008';+const FOREIGN_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-000000000009';+const UNASSIGNED_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-00000000000a';+const WORKSPACE_AGENT_UNIVERSAL_IDENTIFIER =+ '30000000-0000-4000-8000-00000000000b';+const WORKSPACE_ROLE_TARGET_UNIVERSAL_IDENTIFIER =+ '40000000-0000-4000-8000-000000000001';+const SECOND_ROLE_TARGET_UNIVERSAL_IDENTIFIER =+ '40000000-0000-4000-8000-000000000002';++const buildAgentManifest = (universalIdentifier: string): AgentManifest => ({+ universalIdentifier,+ name: `agent-${universalIdentifier.slice(-1)}`,+ label: 'Agent',+ prompt: 'Help the user.',+ responseFormat: { type: 'text' },+});++const buildFlatAgent = (+ universalIdentifier: string,+ overrides: Partial<FlatAgent> = {},+): FlatAgent => ({+ ...fromAgentManifestToUniversalFlatAgent({+ agentManifest: buildAgentManifest(universalIdentifier),+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,+ now: NOW,+ }),+ id: `${universalIdentifier}-id`,+ workspaceId: WORKSPACE_ID,+ applicationId: APP_ID,+ ...overrides,+});++const buildFlatRole = ({+ universalIdentifier,+ applicationId = APP_ID,+}: {+ universalIdentifier: string;+ applicationId?: string;+}): FlatRole =>+ ({+ ...fromRoleManifestToUniversalFlatRole({+ roleManifest: { universalIdentifier, label: 'Role' },+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,+ now: NOW,+ }),+ id: `${universalIdentifier}-id`,+ workspaceId: WORKSPACE_ID,+ applicationId,+ }) as FlatRole;++const buildFlatRoleTarget = ({+ agentUniversalIdentifier,+ roleUniversalIdentifier,+ universalIdentifier,+}: {+ agentUniversalIdentifier: string;+ roleUniversalIdentifier: string;+ universalIdentifier?: string;+}): FlatRoleTarget => {+ const universalFlatRoleTarget = fromAgentManifestToUniversalFlatRoleTarget({+ agentUniversalIdentifier,+ roleUniversalIdentifier,+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,+ now: NOW,+ });++ return {+ ...universalFlatRoleTarget,+ universalIdentifier:+ universalIdentifier ?? universalFlatRoleTarget.universalIdentifier,+ id: `${universalIdentifier ?? agentUniversalIdentifier}-role-target-id`,+ workspaceId: WORKSPACE_ID,+ applicationId: APP_ID,+ roleId: `${roleUniversalIdentifier}-id`,+ agentId: `${agentUniversalIdentifier}-id`,+ };+};++const buildMaps = ({+ agents = [],+ roles = [],+ roleTargets = [],+}: {+ agents?: FlatAgent[];+ roles?: FlatRole[];+ roleTargets?: FlatRoleTarget[];+}): AllFlatEntityMaps => {+ const maps = createEmptyAllFlatEntityMaps();++ return {+ ...maps,+ flatAgentMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: agents,+ flatEntityMaps: maps.flatAgentMaps,+ }),+ flatRoleMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: roles,+ flatEntityMaps: maps.flatRoleMaps,+ }),+ flatRoleTargetMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: roleTargets,+ flatEntityMaps: maps.flatRoleTargetMaps,+ }),+ };+};++const applicationAgents = [+ buildFlatAgent(SUPPORT_AGENT_UNIVERSAL_IDENTIFIER, {+ icon: 'IconRobot',+ triggers: [+ {+ id: '50000000-0000-4000-8000-000000000001',+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ isActive: true,+ instructions: null,+ },+ ],+ }),+ buildFlatAgent(STANDARD_ROLE_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(UNSUPPORTED_ROLE_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(MISSING_ROLE_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(TWO_ROLES_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(WORKSPACE_ROLE_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(CONFIGURED_AGENT_UNIVERSAL_IDENTIFIER, {+ modelConfiguration: { webSearch: { enabled: true } },+ }),+ buildFlatAgent(DELETED_AGENT_UNIVERSAL_IDENTIFIER, { deletedAt: NOW }),+ buildFlatAgent(UNASSIGNED_AGENT_UNIVERSAL_IDENTIFIER),+ buildFlatAgent(WORKSPACE_AGENT_UNIVERSAL_IDENTIFIER, {+ isCustom: true,+ isSystem: false,+ }),+];+const applicationRoles = [+ buildFlatRole({ universalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER }),+ buildFlatRole({ universalIdentifier: UNSUPPORTED_ROLE_UNIVERSAL_IDENTIFIER }),+];+const applicationRoleTargets = [+ buildFlatRoleTarget({+ agentUniversalIdentifier: SUPPORT_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: STANDARD_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: STANDARD_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: UNSUPPORTED_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: UNSUPPORTED_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: MISSING_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: MISSING_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: TWO_ROLES_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: TWO_ROLES_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: STANDARD_ROLE_UNIVERSAL_IDENTIFIER,+ universalIdentifier: SECOND_ROLE_TARGET_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: WORKSPACE_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ universalIdentifier: WORKSPACE_ROLE_TARGET_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: DELETED_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ }),+ buildFlatRoleTarget({+ agentUniversalIdentifier: FOREIGN_AGENT_UNIVERSAL_IDENTIFIER,+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ }),+];++const applicationAllFlatEntityMaps = buildMaps({+ agents: applicationAgents,+ roles: applicationRoles,+ roleTargets: applicationRoleTargets,+});+const allFlatEntityMaps = buildMaps({+ agents: applicationAgents,+ roles: [+ ...applicationRoles,+ buildFlatRole({+ universalIdentifier: STANDARD_ROLE_UNIVERSAL_IDENTIFIER,+ applicationId: STANDARD_APP_ID,+ }),+ ],+ roleTargets: applicationRoleTargets,+});++const { agents, coverage } = reconstructAgentsManifest({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ resolvableRoleUniversalIdentifiers: new Set([+ SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ ]),+});++const roleTargetUniversalIdentifierOf = (agentUniversalIdentifier: string) =>+ getRoleTargetUniversalIdentifier({+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,+ agentUniversalIdentifier,+ });++const findCoverage = (metadataName: string, universalIdentifier: string) =>+ coverage.find(+ (entry) =>+ entry.metadataName === metadataName &&+ entry.universalIdentifier === universalIdentifier,+ );++describe('reconstructAgentsManifest', () => {+ it('should export an agent with its exported role and triggers', () => {+ expect(+ agents.find(+ ({ universalIdentifier }) =>+ universalIdentifier === SUPPORT_AGENT_UNIVERSAL_IDENTIFIER,+ ),+ ).toEqual({+ ...buildAgentManifest(SUPPORT_AGENT_UNIVERSAL_IDENTIFIER),+ icon: 'IconRobot',+ roleUniversalIdentifier: SUPPORT_ROLE_UNIVERSAL_IDENTIFIER,+ triggers: [+ {+ universalIdentifier: '50000000-0000-4000-8000-000000000001',+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ },+ ],+ });+ expect(+ findCoverage('agent', SUPPORT_AGENT_UNIVERSAL_IDENTIFIER)?.status,+ ).toBe(ApplicationExportCoverageStatus.EXPORTED);+ expect(+ findCoverage(+ 'roleTarget',+ roleTargetUniversalIdentifierOf(SUPPORT_AGENT_UNIVERSAL_IDENTIFIER),+ )?.status,+ ).toBe(ApplicationExportCoverageStatus.EXPORTED);+ });++ it('should export an agent bound to a role outside the application and one without a role', () => {+ expect(+ agents.map(({ universalIdentifier }) => universalIdentifier),+ ).toEqual([+ SUPPORT_AGENT_UNIVERSAL_IDENTIFIER,+ STANDARD_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ UNASSIGNED_AGENT_UNIVERSAL_IDENTIFIER,+ ]);+ expect(+ agents.find(+ ({ universalIdentifier }) =>+ universalIdentifier === STANDARD_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ )?.roleUniversalIdentifier,+ ).toBe(STANDARD_ROLE_UNIVERSAL_IDENTIFIER);+ expect(+ agents.find(+ ({ universalIdentifier }) =>+ universalIdentifier === UNASSIGNED_AGENT_UNIVERSAL_IDENTIFIER,+ ),+ ).not.toHaveProperty('roleUniversalIdentifier');+ });++ it.each([+ [WORKSPACE_AGENT_UNIVERSAL_IDENTIFIER, 'agent created in the workspace'],+ [+ UNSUPPORTED_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ 'agent on an unsupported role',+ ],+ [+ MISSING_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ 'agent on a role that does not exist',+ ],+ [TWO_ROLES_AGENT_UNIVERSAL_IDENTIFIER, 'agent with more than one role'],+ [+ WORKSPACE_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ 'agent whose role was assigned outside its definition',+ ],+ [+ CONFIGURED_AGENT_UNIVERSAL_IDENTIFIER,+ 'agent with values a definition cannot express: modelConfiguration',+ ],+ ])(+ 'should report agent %s as unsupported: %s',+ (universalIdentifier, reason) => {+ expect(findCoverage('agent', universalIdentifier)).toEqual({+ metadataName: 'agent',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason,+ });+ },+ );++ it('should leave a soft-deleted agent to the classifier', () => {+ expect(+ findCoverage('agent', DELETED_AGENT_UNIVERSAL_IDENTIFIER),+ ).toBeUndefined();+ });++ it.each([+ [+ roleTargetUniversalIdentifierOf(+ UNSUPPORTED_ROLE_AGENT_UNIVERSAL_IDENTIFIER,+ ),+ 'role target of an agent that is not exported',+ ],+ [+ SECOND_ROLE_TARGET_UNIVERSAL_IDENTIFIER,+ 'role target of an agent that is not exported',+ ],+ [+ WORKSPACE_ROLE_TARGET_UNIVERSAL_IDENTIFIER,+ 'role target of an agent that is not exported',+ ],+ [+ roleTargetUniversalIdentifierOf(DELETED_AGENT_UNIVERSAL_IDENTIFIER),+ 'role target of an agent that is not exported',+ ],+ [+ roleTargetUniversalIdentifierOf(FOREIGN_AGENT_UNIVERSAL_IDENTIFIER),+ 'role target of an agent outside the application',+ ],+ ])(+ 'should report role target %s as unsupported: %s',+ (universalIdentifier, reason) => {+ expect(findCoverage('roleTarget', universalIdentifier)).toEqual({+ metadataName: 'roleTarget',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason,+ });+ },+ );+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-skills-manifest.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-skills-manifest.util.spec.tsnew file mode 100644index 00000000000..f672e388047--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/reconstruct-skills-manifest.util.spec.ts@@ -0,0 +1,94 @@+import { type SkillManifest } from 'twenty-shared/application';++import { fromSkillManifestToUniversalFlatSkill } from 'src/engine/core-modules/application/application-manifest/converters/from-skill-manifest-to-universal-flat-skill.util';+import { addAllFlatEntitiesToFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/__tests__/add-all-flat-entities-to-flat-entity-maps.test-util';+import { reconstructSkillsManifest } from 'src/engine/core-modules/application/application-manifest/utils/reconstruct-skills-manifest.util';+import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';+import { createEmptyAllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-all-flat-entity-maps.constant';+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';++const APP_UNIVERSAL_IDENTIFIER = '10000000-0000-4000-8000-000000000001';+const NOW = '2026-09-14T10:00:00.000Z';+const OUTREACH_SKILL_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000001';+const DEACTIVATED_SKILL_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000002';+const SYSTEM_SKILL_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000003';+const WORKSPACE_SKILL_UNIVERSAL_IDENTIFIER =+ '20000000-0000-4000-8000-000000000004';++const buildSkillManifest = (universalIdentifier: string): SkillManifest => ({+ universalIdentifier,+ name: `skill-${universalIdentifier.slice(-1)}`,+ label: 'Skill',+ content: 'Follow the outreach playbook.',+});++const buildFlatSkill = (+ universalIdentifier: string,+ overrides: Partial<FlatSkill> = {},+): FlatSkill => ({+ ...fromSkillManifestToUniversalFlatSkill({+ skillManifest: buildSkillManifest(universalIdentifier),+ applicationUniversalIdentifier: APP_UNIVERSAL_IDENTIFIER,+ now: NOW,+ }),+ id: `${universalIdentifier}-id`,+ workspaceId: 'workspace-id',+ applicationId: 'application-id',+ ...overrides,+});++const { skills, coverage } = reconstructSkillsManifest({+ applicationAllFlatEntityMaps: {+ flatSkillMaps: addAllFlatEntitiesToFlatEntityMaps({+ flatEntities: [+ buildFlatSkill(OUTREACH_SKILL_UNIVERSAL_IDENTIFIER),+ buildFlatSkill(DEACTIVATED_SKILL_UNIVERSAL_IDENTIFIER, {+ isActive: false,+ }),+ buildFlatSkill(SYSTEM_SKILL_UNIVERSAL_IDENTIFIER, { isSystem: true }),+ buildFlatSkill(WORKSPACE_SKILL_UNIVERSAL_IDENTIFIER, {+ isCustom: true,+ }),+ ],+ flatEntityMaps: createEmptyAllFlatEntityMaps().flatSkillMaps,+ }),+ },+});++describe('reconstructSkillsManifest', () => {+ it('should export an active application skill', () => {+ expect(skills).toEqual([+ buildSkillManifest(OUTREACH_SKILL_UNIVERSAL_IDENTIFIER),+ ]);+ expect(coverage).toContainEqual({+ metadataName: 'skill',+ universalIdentifier: OUTREACH_SKILL_UNIVERSAL_IDENTIFIER,+ status: ApplicationExportCoverageStatus.EXPORTED,+ });+ });++ it.each([+ [WORKSPACE_SKILL_UNIVERSAL_IDENTIFIER, 'skill created in the workspace'],+ [+ DEACTIVATED_SKILL_UNIVERSAL_IDENTIFIER,+ 'skill deactivated in this workspace',+ ],+ [+ SYSTEM_SKILL_UNIVERSAL_IDENTIFIER,+ 'skill with values a definition cannot express: isSystem',+ ],+ ])(+ 'should report skill %s as unsupported: %s',+ (universalIdentifier, reason) => {+ expect(coverage).toContainEqual({+ metadataName: 'skill',+ universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason,+ });+ },+ );+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-unreproduced-properties-reason.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-unreproduced-properties-reason.util.tsnew file mode 100644index 00000000000..6f8fc859a7e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-unreproduced-properties-reason.util.ts@@ -0,0 +1,37 @@+import { type AllMetadataName } from 'twenty-shared/metadata';+import { isDefined } from 'twenty-shared/utils';++import { compareByCodePoint } from 'src/engine/core-modules/application/application-manifest/utils/compare-by-code-point.util';+import { MANIFEST_ENTITY_REGISTRY } from 'src/engine/core-modules/application/application-manifest/utils/find-manifest-entity-descriptor-by-universal-identifier.util';+import { type MetadataUniversalFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/metadata-universal-flat-entity.type';+import { compareTwoFlatEntity } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/compare-two-universal-flat-entity.util';++// Compares as the sync does, so an exported definition can never produce an update on apply+export const getUnreproducedPropertiesReason = <+ TMetadataName extends AllMetadataName,+>({+ metadataName,+ flatEntity,+ reproducedUniversalFlatEntity,+}: {+ metadataName: TMetadataName;+ flatEntity: MetadataUniversalFlatEntity<TMetadataName>;+ reproducedUniversalFlatEntity: MetadataUniversalFlatEntity<TMetadataName>;+}): string | undefined => {+ const comparison = compareTwoFlatEntity({+ fromUniversalFlatEntity: flatEntity,+ toUniversalFlatEntity: reproducedUniversalFlatEntity,+ metadataName,+ });++ if (!isDefined(comparison)) {+ return undefined;+ }++ const properties = [+ ...Object.keys(comparison.update),+ ...comparison.nonUpdatablePropertyDivergences,+ ].sort(compareByCodePoint);++ return `${MANIFEST_ENTITY_REGISTRY[metadataName].entityKind} with values a definition cannot express: ${properties.join(', ')}`;+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-agents-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-agents-manifest.util.tsnew file mode 100644index 00000000000..5b846f635fa--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-agents-manifest.util.ts@@ -0,0 +1,201 @@+import { type AgentManifest } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { fromAgentManifestToUniversalFlatRoleTarget } from 'src/engine/core-modules/application/application-manifest/converters/from-agent-manifest-to-universal-flat-role-target.util';+import { fromFlatAgentToAgentManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-agent-to-agent-manifest.util';+import { type ApplicationExportCoverageEntry } from 'src/engine/core-modules/application/application-manifest/types/application-export.type';+import { buildExportedCoverageEntry } from 'src/engine/core-modules/application/application-manifest/utils/build-exported-coverage-entry.util';+import { getUnreproducedPropertiesReason } from 'src/engine/core-modules/application/application-manifest/utils/get-unreproduced-properties-reason.util';+import { getUnresolvableReferenceReason } from 'src/engine/core-modules/application/application-manifest/utils/get-unresolvable-reference-reason.util';+import { sortFlatEntitiesByUniversalIdentifier } from 'src/engine/core-modules/application/application-manifest/utils/sort-flat-entities-by-universal-identifier.util';+import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';+import { fromAgentManifestToUniversalFlatAgent } from 'src/engine/core-modules/application/utils/from-agent-manifest-to-universal-flat-agent.util';+import { type FlatAgent } from 'src/engine/metadata-modules/flat-agent/types/flat-agent.type';+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';+import { type FlatRoleTarget } from 'src/engine/metadata-modules/flat-role-target/types/flat-role-target.type';++export const reconstructAgentsManifest = ({+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ resolvableRoleUniversalIdentifiers,+}: {+ applicationAllFlatEntityMaps: AllFlatEntityMaps;+ allFlatEntityMaps: AllFlatEntityMaps;+ resolvableRoleUniversalIdentifiers: ReadonlySet<string>;+}): {+ agents: AgentManifest[];+ coverage: ApplicationExportCoverageEntry[];+} => {+ const agents: AgentManifest[] = [];+ const coverage: ApplicationExportCoverageEntry[] = [];+ const flatRoleTargetsByAgentUniversalIdentifier = new Map<+ string,+ FlatRoleTarget[]+ >();++ for (const flatRoleTarget of sortFlatEntitiesByUniversalIdentifier(+ applicationAllFlatEntityMaps.flatRoleTargetMaps,+ )) {+ const { agentUniversalIdentifier } = flatRoleTarget;++ if (isDefined(agentUniversalIdentifier)) {+ flatRoleTargetsByAgentUniversalIdentifier.set(agentUniversalIdentifier, [+ ...(flatRoleTargetsByAgentUniversalIdentifier.get(+ agentUniversalIdentifier,+ ) ?? []),+ flatRoleTarget,+ ]);+ }+ }++ const convertFlatAgent = ({+ flatAgent,+ flatRoleTargets,+ }: {+ flatAgent: FlatAgent;+ flatRoleTargets: FlatRoleTarget[];+ }): { manifest: AgentManifest } | { reason: string } => {+ if (flatAgent.isCustom) {+ return { reason: 'agent created in the workspace' };+ }++ if (flatRoleTargets.length > 1) {+ return { reason: 'agent with more than one role' };+ }++ const [flatRoleTarget] = flatRoleTargets;+ const unresolvableRoleReason = getUnresolvableReferenceReason({+ metadataName: 'agent',+ referenceMetadataName: 'role',+ referenceUniversalIdentifier: flatRoleTarget?.roleUniversalIdentifier,+ applicationAllFlatEntityMaps,+ allFlatEntityMaps,+ resolvableReferenceUniversalIdentifiers:+ resolvableRoleUniversalIdentifiers,+ });++ if (isDefined(unresolvableRoleReason)) {+ return { reason: unresolvableRoleReason };+ }++ const manifest = fromFlatAgentToAgentManifest({+ flatAgent,+ roleUniversalIdentifier: flatRoleTarget?.roleUniversalIdentifier,+ });+ const reproduction = {+ applicationUniversalIdentifier: flatAgent.applicationUniversalIdentifier,+ now: flatAgent.updatedAt,+ };+ const unreproducedAgentReason = getUnreproducedPropertiesReason({+ metadataName: 'agent',+ flatEntity: flatAgent,+ reproducedUniversalFlatEntity: fromAgentManifestToUniversalFlatAgent({+ agentManifest: manifest,+ ...reproduction,+ }),+ });++ if (isDefined(unreproducedAgentReason)) {+ return { reason: unreproducedAgentReason };+ }++ if (!isDefined(flatRoleTarget)) {+ return { manifest };+ }++ const reproducedFlatRoleTarget = fromAgentManifestToUniversalFlatRoleTarget(+ {+ agentUniversalIdentifier: flatAgent.universalIdentifier,+ roleUniversalIdentifier: flatRoleTarget.roleUniversalIdentifier,+ ...reproduction,+ },+ );++ if (+ reproducedFlatRoleTarget.universalIdentifier !==+ flatRoleTarget.universalIdentifier+ ) {+ return { reason: 'agent whose role was assigned outside its definition' };+ }++ const unreproducedRoleTargetReason = getUnreproducedPropertiesReason({+ metadataName: 'roleTarget',+ flatEntity: flatRoleTarget,+ reproducedUniversalFlatEntity: reproducedFlatRoleTarget,+ });++ return isDefined(unreproducedRoleTargetReason)+ ? { reason: unreproducedRoleTargetReason }+ : { manifest };+ };++ const exportedAgentUniversalIdentifiers = new Set<string>();++ for (const flatAgent of sortFlatEntitiesByUniversalIdentifier(+ applicationAllFlatEntityMaps.flatAgentMaps,+ )) {+ // Left to the classifier, which reports soft-deleted entities as excluded+ if (isDefined(flatAgent.deletedAt)) {+ continue;+ }++ const conversion = convertFlatAgent({+ flatAgent,+ flatRoleTargets:+ flatRoleTargetsByAgentUniversalIdentifier.get(+ flatAgent.universalIdentifier,+ ) ?? [],+ });++ if ('reason' in conversion) {+ coverage.push({+ metadataName: 'agent',+ universalIdentifier: flatAgent.universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: conversion.reason,+ });+ continue;+ }++ exportedAgentUniversalIdentifiers.add(flatAgent.universalIdentifier);+ coverage.push(+ buildExportedCoverageEntry({+ metadataName: 'agent',+ flatEntity: flatAgent,+ }),+ );+ agents.push(conversion.manifest);+ }++ for (const [+ agentUniversalIdentifier,+ flatRoleTargets,+ ] of flatRoleTargetsByAgentUniversalIdentifier) {+ for (const flatRoleTarget of flatRoleTargets) {+ if (exportedAgentUniversalIdentifiers.has(agentUniversalIdentifier)) {+ coverage.push(+ buildExportedCoverageEntry({+ metadataName: 'roleTarget',+ flatEntity: flatRoleTarget,+ }),+ );+ continue;+ }++ coverage.push({+ metadataName: 'roleTarget',+ universalIdentifier: flatRoleTarget.universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: isDefined(+ applicationAllFlatEntityMaps.flatAgentMaps.byUniversalIdentifier[+ agentUniversalIdentifier+ ],+ )+ ? 'role target of an agent that is not exported'+ : 'role target of an agent outside the application',+ });+ }+ }++ return { agents, coverage };+};diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-skills-manifest.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-skills-manifest.util.tsnew file mode 100644index 00000000000..06d6410cb54--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/reconstruct-skills-manifest.util.ts@@ -0,0 +1,76 @@+import { type SkillManifest } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { fromFlatSkillToSkillManifest } from 'src/engine/core-modules/application/application-manifest/converters/from-flat-skill-to-skill-manifest.util';+import { fromSkillManifestToUniversalFlatSkill } from 'src/engine/core-modules/application/application-manifest/converters/from-skill-manifest-to-universal-flat-skill.util';+import { type ApplicationExportCoverageEntry } from 'src/engine/core-modules/application/application-manifest/types/application-export.type';+import { buildExportedCoverageEntry } from 'src/engine/core-modules/application/application-manifest/utils/build-exported-coverage-entry.util';+import { getUnreproducedPropertiesReason } from 'src/engine/core-modules/application/application-manifest/utils/get-unreproduced-properties-reason.util';+import { sortFlatEntitiesByUniversalIdentifier } from 'src/engine/core-modules/application/application-manifest/utils/sort-flat-entities-by-universal-identifier.util';+import { ApplicationExportCoverageStatus } from 'src/engine/core-modules/application/enums/application-export-coverage-status.enum';+import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';++const convertFlatSkill = (+ flatSkill: FlatSkill,+): { manifest: SkillManifest } | { reason: string } => {+ if (flatSkill.isCustom) {+ return { reason: 'skill created in the workspace' };+ }++ // A skill has no overrides, so apply would reactivate it+ if (!flatSkill.isActive) {+ return { reason: 'skill deactivated in this workspace' };+ }++ const manifest = fromFlatSkillToSkillManifest({ flatSkill });+ const reason = getUnreproducedPropertiesReason({+ metadataName: 'skill',+ flatEntity: flatSkill,+ reproducedUniversalFlatEntity: fromSkillManifestToUniversalFlatSkill({+ skillManifest: manifest,+ applicationUniversalIdentifier: flatSkill.applicationUniversalIdentifier,+ now: flatSkill.updatedAt,+ }),+ });++ return isDefined(reason) ? { reason } : { manifest };+};++export const reconstructSkillsManifest = ({+ applicationAllFlatEntityMaps,+}: {+ applicationAllFlatEntityMaps: Pick<AllFlatEntityMaps, 'flatSkillMaps'>;+}): {+ skills: SkillManifest[];+ coverage: ApplicationExportCoverageEntry[];+} => {+ const skills: SkillManifest[] = [];+ const coverage: ApplicationExportCoverageEntry[] = [];++ for (const flatSkill of sortFlatEntitiesByUniversalIdentifier(+ applicationAllFlatEntityMaps.flatSkillMaps,+ )) {+ const conversion = convertFlatSkill(flatSkill);++ if ('reason' in conversion) {+ coverage.push({+ metadataName: 'skill',+ universalIdentifier: flatSkill.universalIdentifier,+ status: ApplicationExportCoverageStatus.UNSUPPORTED,+ reason: conversion.reason,+ });+ continue;+ }++ coverage.push(+ buildExportedCoverageEntry({+ metadataName: 'skill',+ flatEntity: flatSkill,+ }),+ );+ skills.push(conversion.manifest);+ }++ return { skills, coverage };+};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 012b9c496fc..cfd40a0a106 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@@ -18,9 +18,11 @@ import { createOneView } from 'test/integration/metadata/suites/view/utils/creatimport { destroyOneView } from 'test/integration/metadata/suites/view/utils/destroy-one-view.util';import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';import {+ type AgentManifest,type FieldManifest,getFieldUniversalIdentifier,getIndexFieldUniversalIdentifier,+ getRoleTargetUniversalIdentifier,getSystemFormFieldPageLayoutWidgetUniversalIdentifier,getSystemPageLayoutTabUniversalIdentifier,getSystemPageLayoutWidgetUniversalIdentifier,@@ -35,6 +37,7 @@ import {type ObjectManifest,type PageLayoutManifest,type PageLayoutTabManifest,+ type SkillManifest,type StandalonePageLayoutWidgetManifest,type StandaloneViewFieldManifest,SYSTEM_VIEW_KEYS,@@ -1738,3 +1741,152 @@ describe('Application export - workflows', () => {expect(dryRun.data.syncApplication.actions).toEqual([]);}, 60000);});++const AI_TEST_APP_ID = '7e3d1c2b-0300-4a7b-8c9d-0e1f2a3b4c5d';+const AI_TEST_ROLE_ID = '7e3d1c2b-0301-4a7b-8c9d-0e1f2a3b4c5d';+const TRIAGE_AGENT_ID = '7e3d1c2b-0302-4a7b-8c9d-0e1f2a3b4c5d';+const DIGEST_AGENT_ID = '7e3d1c2b-0303-4a7b-8c9d-0e1f2a3b4c5d';+const DIGEST_CRON_TRIGGER_ID = '7e3d1c2b-0304-4a7b-8c9d-0e1f2a3b4c5d';+const DIGEST_EVENT_TRIGGER_ID = '7e3d1c2b-0305-4a7b-8c9d-0e1f2a3b4c5d';+const TRIAGE_SKILL_ID = '7e3d1c2b-0306-4a7b-8c9d-0e1f2a3b4c5d';++const EXPORTED_AGENTS: AgentManifest[] = [+ {+ universalIdentifier: TRIAGE_AGENT_ID,+ name: 'export-triage-agent',+ label: 'Triage Agent',+ prompt: 'Triage the incoming request.',+ responseFormat: { type: 'text' },+ roleUniversalIdentifier: AI_TEST_ROLE_ID,+ },+ {+ universalIdentifier: DIGEST_AGENT_ID,+ name: 'export-digest-agent',+ label: 'Digest Agent',+ icon: 'IconRobot',+ description: 'Summarizes the week',+ prompt: 'Summarize what changed this week.',+ responseFormat: {+ type: 'json',+ schema: {+ type: 'object',+ properties: { summary: { type: 'string', description: 'Summary' } },+ required: ['summary'],+ additionalProperties: false,+ },+ },+ triggers: [+ {+ universalIdentifier: DIGEST_CRON_TRIGGER_ID,+ type: 'CRON',+ settings: { pattern: '0 9 * * 1' },+ isActive: false,+ instructions: 'Send the weekly digest',+ },+ {+ universalIdentifier: DIGEST_EVENT_TRIGGER_ID,+ type: 'DATABASE_EVENT',+ settings: { eventName: 'company.updated', updatedFields: ['name'] },+ },+ ],+ },+];++const EXPORTED_SKILLS: SkillManifest[] = [+ {+ universalIdentifier: TRIAGE_SKILL_ID,+ name: 'export-triage-skill',+ label: 'Triage',+ icon: 'IconBrain',+ description: 'How to triage requests',+ content: 'Classify the request, then route it.',+ },+];++const aiManifest = buildBaseManifest({+ appId: AI_TEST_APP_ID,+ roleId: AI_TEST_ROLE_ID,+ overrides: {+ roles: [+ {+ universalIdentifier: AI_TEST_ROLE_ID,+ label: 'Test Role',+ description: 'A test role',+ canBeAssignedToAgents: true,+ },+ ],+ agents: EXPORTED_AGENTS,+ skills: EXPORTED_SKILLS,+ },+});++describe('Application export - agents and skills', () => {+ beforeAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: AI_TEST_APP_ID,+ });+ await setupApplicationForSync({+ applicationUniversalIdentifier: AI_TEST_APP_ID,+ name: 'Export Agents Test Application',+ description: 'App for testing the agent and skill export',+ sourcePath: 'export-agents',+ });++ await syncApplication({ manifest: aiManifest, expectToFail: false });+ }, 60000);++ afterAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: AI_TEST_APP_ID,+ });+ });++ it('exports the synced agents and skills as they were declared', async () => {+ const { data, errors } = await exportApplication({+ universalIdentifier: AI_TEST_APP_ID,+ expectToFail: false,+ });++ expect(errors).toBeUndefined();++ const { manifest: exportedManifest, coverage } = data.exportApplication;+ const statusOf = (universalIdentifier: string) =>+ coverage.find(+ (entry) => entry.universalIdentifier === universalIdentifier,+ )?.status;++ expect(exportedManifest.agents).toEqual(EXPORTED_AGENTS);+ expect(exportedManifest.skills).toEqual(EXPORTED_SKILLS);++ for (const universalIdentifier of [+ TRIAGE_AGENT_ID,+ DIGEST_AGENT_ID,+ TRIAGE_SKILL_ID,+ getRoleTargetUniversalIdentifier({+ applicationUniversalIdentifier: AI_TEST_APP_ID,+ agentUniversalIdentifier: TRIAGE_AGENT_ID,+ }),+ ]) {+ expect(statusOf(universalIdentifier)).toBe(+ ApplicationExportCoverageStatus.EXPORTED,+ );+ }+ }, 60000);++ it('round-trips the exported agents and skills through an additive dry-run sync without any action', async () => {+ const { data } = await exportApplication({+ universalIdentifier: AI_TEST_APP_ID,+ expectToFail: false,+ });++ const dryRun = await syncApplication({+ manifest: data.exportApplication.manifest,+ dryRun: true,+ inferDeletionFromMissingEntities: false,+ expectToFail: false,+ });++ expect(dryRun.errors).toBeUndefined();+ expect(dryRun.data.syncApplication.actions).toEqual([]);+ }, 60000);+});