Skip to content

The open alternative to Salesforce, designed for AI.

Teach the crm-hygiene skill to merge duplicates (#29157)

Félix Malfait599cf544fcc7
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-upgrade-version-command.module.ts
new file mode 100644
index 00000000000..11b8d5efa3f
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-upgrade-version-command.module.ts
@@ -0,0 +1,18 @@
+import { Module } from '@nestjs/common';
+
+import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
+import { UpdateCrmHygieneSkillMergeGuidanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-workspace-command-1793206127866-update-crm-hygiene-skill-merge-guidance.command';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
+
+@Module({
+ imports: [
+ ApplicationModule,
+ WorkspaceCacheModule,
+ WorkspaceIteratorModule,
+ WorkspaceMigrationModule,
+ ],
+ providers: [UpdateCrmHygieneSkillMergeGuidanceCommand],
+})
+export class V2_54_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-workspace-command-1793206127866-update-crm-hygiene-skill-merge-guidance.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-workspace-command-1793206127866-update-crm-hygiene-skill-merge-guidance.command.ts
new file mode 100644
index 00000000000..5684018b9ed
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-workspace-command-1793206127866-update-crm-hygiene-skill-merge-guidance.command.ts
@@ -0,0 +1,137 @@
+import { Command } from 'nest-commander';
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { CRM_HYGIENE_SKILL_CONTENT_BEFORE_MERGE_TOOL } from 'src/database/commands/upgrade-version-command/2-54/constants/crm-hygiene-skill-content-before-merge-tool.constant';
+import { buildSkillContentReplacement } from 'src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { STANDARD_SKILL } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-skill.constant';
+import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';
+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
+
+const CRM_HYGIENE_SKILL_UNIVERSAL_IDENTIFIER =
+ STANDARD_SKILL['crm-hygiene'].universalIdentifier;
+
+@RegisteredWorkspaceCommand('2.54.0', 1793206127866)
+@Command({
+ name: 'upgrade:2-54:update-crm-hygiene-skill-merge-guidance',
+ description:
+ 'Update the crm-hygiene skill so it merges duplicates with merge_many_* instead of saying there is no merge tool',
+})
+export class UpdateCrmHygieneSkillMergeGuidanceCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly applicationService: ApplicationService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.apply(args, 'up');
+ }
+
+ async down(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.apply(args, 'down');
+ }
+
+ private async apply(
+ { workspaceId, options }: RunOnWorkspaceArgs,
+ direction: 'up' | 'down',
+ ): Promise<void> {
+ const { twentyStandardFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+
+ const { flatSkillMaps } = await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ ['flatSkillMaps'],
+ );
+
+ const { allFlatEntityMaps: standardAllFlatEntityMaps } =
+ computeTwentyStandardApplicationAllFlatEntityMaps({
+ now: new Date().toISOString(),
+ workspaceId,
+ twentyStandardApplicationId: twentyStandardFlatApplication.id,
+ });
+
+ const standardContent =
+ standardAllFlatEntityMaps.flatSkillMaps.byUniversalIdentifier[
+ CRM_HYGIENE_SKILL_UNIVERSAL_IDENTIFIER
+ ]?.content;
+
+ if (!isDefined(standardContent)) {
+ throw new Error(
+ 'The crm-hygiene skill is missing from the standard application definition',
+ );
+ }
+
+ const skillToUpdate = buildSkillContentReplacement({
+ skill:
+ flatSkillMaps.byUniversalIdentifier[
+ CRM_HYGIENE_SKILL_UNIVERSAL_IDENTIFIER
+ ],
+ fromContent:
+ direction === 'up'
+ ? CRM_HYGIENE_SKILL_CONTENT_BEFORE_MERGE_TOOL
+ : standardContent,
+ toContent:
+ direction === 'up'
+ ? standardContent
+ : CRM_HYGIENE_SKILL_CONTENT_BEFORE_MERGE_TOOL,
+ });
+
+ if (!isDefined(skillToUpdate)) {
+ this.logger.log(
+ `The crm-hygiene skill is missing or its content was edited in workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ this.logger.log(
+ `${options.dryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId} (${direction}): updating the crm-hygiene skill content`,
+ );
+
+ if (options.dryRun) {
+ return;
+ }
+
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ {
+ shouldDeferActions: false,
+ workspaceId,
+ isSystemBuild: true,
+ applicationUniversalIdentifier:
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ allFlatEntityOperationByMetadataName: {
+ skill: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: [skillToUpdate],
+ },
+ },
+ },
+ );
+
+ if (result.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(
+ result,
+ `Failed to update the crm-hygiene skill for workspace ${workspaceId}`,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/constants/crm-hygiene-skill-content-before-merge-tool.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/constants/crm-hygiene-skill-content-before-merge-tool.constant.ts
new file mode 100644
index 00000000000..b8a46ff48fe
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/constants/crm-hygiene-skill-content-before-merge-tool.constant.ts
@@ -0,0 +1,33 @@
+export const CRM_HYGIENE_SKILL_CONTENT_BEFORE_MERGE_TOOL = `# CRM Hygiene Skill
+
+Audit records for problems, show the user what you found, and fix only what they approve.
+
+## Audit
+
+Ask which object to audit if the user has not said. Then look for these, in this order:
+
+- **Duplicates.** Read the object's duplicateCriteria from its metadata and search on those fields. Two companies sharing a domain, or two people sharing an email, are the reliable cases.
+- **Missing fields.** Identify the fields that make a record useful for that object, then count how many records leave them empty.
+- **Stale records.** Records untouched for a long time, especially opportunities whose close date has passed while they are still open.
+- **Broken links.** Records whose expected relation is empty, such as a person with no company or a deal with no contact.
+
+Use group_by_* to count rather than reading every record, then fetch only the rows you intend to show.
+
+## Report
+
+Lead with counts, so the user sees the shape of the problem before the detail. Then list the worst cases, referencing each record. Say which fix you propose for each group and what it would change.
+
+## Fix
+
+Always confirm before writing. Show what you will change and wait.
+
+- You cannot merge records. There is no merge tool; merging happens in the UI, where the user selects the records and uses the Merge action. Report each duplicate pair with both records referenced and leave the merge to them.
+- Fill missing fields only from data already in the workspace, never from a guess.
+- Apply approved changes in one call rather than one record at a time. These tools carry the object's plural name: update_many_people, upsert_many_companies, and so on. Use update_many_* when every matched record gets the same value, upsert_many_* when each record needs its own.
+- Report what changed afterwards, and say what you deliberately left alone.
+
+## Rules
+
+- Never delete a record in this skill, and never fake a merge by copying fields across and deleting the loser.
+- Never confirm on the user's behalf, and never read a general yes as approval for a second batch.
+- If there is nothing wrong, say so. A clean workspace is a valid result.`;
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/__tests__/build-skill-content-replacement.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/__tests__/build-skill-content-replacement.util.spec.ts
new file mode 100644
index 00000000000..73720b96c75
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/__tests__/build-skill-content-replacement.util.spec.ts
@@ -0,0 +1,58 @@
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+
+import { buildSkillContentReplacement } from 'src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util';
+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
+
+const PREVIOUS_CONTENT = '# CRM Hygiene Skill\n\nThere is no merge tool.';
+const NEXT_CONTENT = '# CRM Hygiene Skill\n\nMerge with merge_many_*.';
+
+const buildSkill = (content: string): FlatSkill => ({
+ id: 'skill-id',
+ universalIdentifier: '20202020-9a63-4d82-b5e7-6f1c8d3a4e20',
+ name: 'crm-hygiene',
+ label: 'CRM Hygiene',
+ icon: 'IconListCheck',
+ description: null,
+ content,
+ isSystem: false,
+ isActive: false,
+ overrides: null,
+ workspaceId: '20202020-1111-4111-8111-111111111111',
+ applicationId: '20202020-2222-4222-8222-222222222222',
+ applicationUniversalIdentifier:
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+});
+
+describe('buildSkillContentReplacement', () => {
+ it('replaces the content of a skill the workspace never edited', () => {
+ expect(
+ buildSkillContentReplacement({
+ skill: buildSkill(PREVIOUS_CONTENT),
+ fromContent: PREVIOUS_CONTENT,
+ toContent: NEXT_CONTENT,
+ }),
+ ).toEqual(buildSkill(NEXT_CONTENT));
+ });
+
+ it('leaves a skill whose content was edited', () => {
+ expect(
+ buildSkillContentReplacement({
+ skill: buildSkill(`${PREVIOUS_CONTENT}\n\nOur own rule.`),
+ fromContent: PREVIOUS_CONTENT,
+ toContent: NEXT_CONTENT,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('does nothing when the workspace has no such skill', () => {
+ expect(
+ buildSkillContentReplacement({
+ skill: undefined,
+ fromContent: PREVIOUS_CONTENT,
+ toContent: NEXT_CONTENT,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util.ts
new file mode 100644
index 00000000000..3051368e39d
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util.ts
@@ -0,0 +1,17 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatSkill } from 'src/engine/metadata-modules/flat-skill/types/flat-skill.type';
+
+// Content edited by the workspace before skills became overridable lives on the row, so it is left alone
+export const buildSkillContentReplacement = ({
+ skill,
+ fromContent,
+ toContent,
+}: {
+ skill: FlatSkill | undefined;
+ fromContent: string;
+ toContent: string;
+}): FlatSkill | undefined =>
+ isDefined(skill) && skill.content === fromContent
+ ? { ...skill, content: toContent }
+ : undefined;
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts
index ec2724f576f..453954dc465 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts
@@ -46,6 +46,7 @@ import { V2_50_UpgradeVersionCommandModule } from 'src/database/commands/upgrade
import { V2_51_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-51/2-51-upgrade-version-command.module';
import { V2_52_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-52/2-52-upgrade-version-command.module';
import { V2_53_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-53/2-53-upgrade-version-command.module';
+import { V2_54_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-54/2-54-upgrade-version-command.module';
import { V2_4_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-4/2-4-upgrade-version-command.module';
import { V2_5_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-5/2-5-upgrade-version-command.module';
import { V2_7_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-7/2-7-upgrade-version-command.module';
@@ -105,6 +106,7 @@ import { V2_9_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-
V2_51_UpgradeVersionCommandModule,
V2_52_UpgradeVersionCommandModule,
V2_53_UpgradeVersionCommandModule,
+ V2_54_UpgradeVersionCommandModule,
],
})
export class WorkspaceCommandProviderModule {}
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
index 4f9ae951446..93875636e9a 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
@@ -1861,14 +1861,15 @@ Lead with counts, so the user sees the shape of the problem before the detail. T
Always confirm before writing. Show what you will change and wait.
-- You cannot merge records. There is no merge tool; merging happens in the UI, where the user selects the records and uses the Merge action. Report each duplicate pair with both records referenced and leave the merge to them.
+- Merge duplicates with merge_many_* (merge_many_companies, merge_many_people, and so on), one call per group. Call it with dryRun: true first and show the user the merged record. When the records disagree, ask which one to keep and pass its position in ids as conflictPriorityIndex. The other records are permanently deleted, so merge only the groups the user approved.
+- If there is no merge_many_* tool for the object, the user's role cannot merge it. Report each group with its records referenced and leave the merge to someone who can.
- Fill missing fields only from data already in the workspace, never from a guess.
- Apply approved changes in one call rather than one record at a time. These tools carry the object's plural name: update_many_people, upsert_many_companies, and so on. Use update_many_* when every matched record gets the same value, upsert_many_* when each record needs its own.
- Report what changed afterwards, and say what you deliberately left alone.
## Rules
-- Never delete a record in this skill, and never fake a merge by copying fields across and deleting the loser.
+- Never delete a record in this skill except through merge_many_*, and never fake a merge by copying fields across and deleting the loser: that loses every record linked to it.
- Never confirm on the user's behalf, and never read a general yes as approval for a second batch.
- If there is nothing wrong, say so. A clean workspace is a valid result.`,
isSystem: false,