The composer is getting dumber by the moment?

I started using cursor and build great code. Then I started refactoring the code, and cursor did a great job on the architecture.
But after a while cursor started suffering and no longer being able to solve issues.
Just a that time, I discovered composer.

And strange enough composer was able to pull it together.

But the longer I went on, the more issues came up.
Working functionality removed, broken, and no longer working, even with composer.
The more I try to fix it, the more issues come up.
It seems like it’s getting alzheimer. not recalling decisions we took together, no longer applying best practices, duplicating functionality…
Sometimes composer suggests code changes, in the chat window, but that code doesn’t even exist in the script.

Maybe it is based on my instructions, or do I need a reset for cursor?
And on top of that is slower then ever.

All feedback, tips and ideas are more then welcome.

2 Likes

I have experienced the same situation. I use a very clear and concise .cursorrules file and include it in the conversation. It starts off great, then as the .cursorrules files grows with the project, it will take a turn for the worse and do much of what you describe.

In my research and experience, I have learned to evolve the .cursorrules file and mark off what it completed, remove the completed item instructions, summarize, and use various AI models to recompose the rules file.

Works great, then all of a sudden, it takes a turn for the worse.

Right now I am trying to understand why it takes a dive, I look forward to hearing from the community.

2 Likes

Do you put your design principles in the .cursorrules and architecture decisions in here to guide the LLM?
Can you share an example of what you put in there?

Did you ever came out of resolving the ‘turned for the worse’, with the help of cursor? or did you fixed it yourself?

Hey guy,
This is my .cursorrules file.
I hope it is useful for you.

{
    "examples": {
        "description": "使用示例,可直接复制使用",
        "createBasicModule": {
            "description": "创建基础CRUD模块",
            "command": "cursor createFeatureModule --name Machine --description '机器管理' --fields 'name,description,status'",
            "output": [
                "创建 MachineEntity.java",
                "创建 MachineRepository.java",
                "创建 MachineDTO.java, MachineCreateDTO.java, MachineUpdateDTO.java",
                "创建 MachineService.java, MachineServiceImpl.java",
                "创建 MachineController.java",
                "创建 MachineException.java, MachineExceptionHandler.java"
            ]
        },
        "createBusinessService": {
            "description": "创建纯业务服务(不涉及数据库)",
            "command": "cursor createBusinessService --name ImageGeneration --businessType ai/generation --description 'AI图片生成服务'",
            "output": [
                "创建 src/main/java/com/shnet/admin/service/ai/generation/ImageGenerationService.java"
            ]
        },
        "createScheduler": {
            "description": "创建定时任务",
            "examples": [
                {
                    "name": "leader专属定时任务",
                    "command": "cursor createScheduler --name TaskClean --description '任务清理' --schedule '0 0 2 * * ?' --leaderOnly true"
                },
                {
                    "name": "所有节点执行的定时任务",
                    "command": "cursor createScheduler --name HealthCheck --description '健康检查' --schedule '0/30 * * * * ?' --leaderOnly false"
                }
            ]
        },
        "createComplexProcessor": {
            "description": "创建复杂业务处理器",
            "steps": [
                "1. 需求分析和伪代码设计:",
                "cursor complexBusinessProcess --phase analysis --name OrderProcess --description '订单处理流程:\n1. 接收订单请求\n2. 校验订单数据\n3. 检查库存\n4. 计算价格\n5. 生成订单\n6. 通知相关系统'",
                "",
                "2. 创建处理器相关类:",
                "cursor createComplexProcessor --name ImageGeneration --types \"Text2Image,Image2Image\""
            ],
            "output": [
                "创建 ImageGenerationProcessor.java (接口)",
                "创建 ImageGenerationContext.java (上下文)",
                "创建 AbstractImageGenerationProcessor.java (抽象类)",
                "创建 Text2ImageProcessor.java, Image2ImageProcessor.java (具体实现)",
                "创建 ImageGenerationProcessorFactory.java (工厂类)"
            ]
        },
        "logUsage": {
            "description": "日志记录示例",
            "code": [
                "// 记录操作日志",
                "Map<String, Object> logData = new HashMap<>();",
                "logData.put(\"newConfig\", savedConfig);",
                "",
                "logService.createLog(new LogCreateDto(",
                "    new LogDataDto(\"addMachineConfig\", logData),",
                "    \"info\",",
                "    \"Added new machine configuration\",",
                "    \"TaskService\",",
                "    getCurrentUserId()",
                "));"
            ]
        },
        "controllerUsage": {
            "description": "Controller 层使用示例",
            "code": [
                "@Tag(name = \"机器管理\", description = \"机器管理相关接口\")",
                "@RestController",
                "@RequestMapping(\"/admin/machines\")",
                "@Validated",
                "@Slf4j",
                "public class MachineController extends BaseController {",
                "",
                "    @Operation(summary = \"创建机器\", description = \"创建新的机器配置\")",
                "    @PostMapping(\"/create\")",
                "    @PreAuthorize(\"hasPermission(null, null, 'operate_machines')\")",
                "    public ResponseEntity<ApiResult> createMachine(@RequestBody @Valid MachineCreateDTO createDTO) {",
                "        String userId = getCurrentUserId();",
                "        MachineDTO result = machineService.createMachine(userId, createDTO);",
                "        return renderOk(mapOf(\"machine\", result));",
                "    }",
                "}"
            ]
        }
    },
    "projectType": {
        "language": "java",
        "framework": "spring-boot",
        "description": "这是一个基于Spring Boot的Java后台管理系统",
        "orm": "spring-data-mongodb",
        "database": "mongodb",
        "features": [
            "RESTful API",
            "Swagger文档",
            "Spring Data MongoDB",
            "统一响应格式",
            "统一异常处理"
        ]
    },
    "projectRules": {
        "description": "Java Spring Boot 后台管理系统项目规范",
        "codeStyle": {
            "language": "java",
            "framework": "spring-boot",
            "indentation": 4,
            "lineLength": 120
        },
        "architecture": {
            "packageStructure": {
                "controller": {
                    "description": "处理HTTP请求,返回ResponseEntity<ApiResult>",
                    "baseClass": "BaseController",
                    "imports": {
                        "required": [
                            "com.shnet.admin.controller.base.BaseController",
                            "com.shnet.admin.core.api.ApiResult"
                        ]
                    },
                    "dataStructure": {
                        "request": "只能使用 *DTO 作为请求参数",
                        "response": "只能使用 *DTO 作为响应数据,禁止直接返回 Entity"
                    },
                    "annotations": {
                        "class": [
                            "@Tag(name = \"${description}\", description = \"${description}相关接口\")",
                            "@ApiResponse(responseCode = \"200\", description = \"请求已处理,具体结果参考ApiResult的code和message\")",
                            "@RestController",
                            "@RequestMapping(\"/admin/${path}\")",
                            "@Validated",
                            "@Slf4j"
                        ],
                        "method": [
                            "@Operation(summary = \"${summary}\", description = \"${description}\")",
                            "@PreAuthorize(\"hasPermission(null, null, '${permission}')\")",
                            "@ApiResponse(responseCode = \"200\", description = \"请求已处理,具体结果参考ApiResult的code和message\")"
                        ]
                    },
                    "responseHandling": {
                        "description": "统一使用HTTP 200状态码,具体错误信息通过ApiResult传递",
                        "format": {
                            "success": {
                                "httpStatus": 200,
                                "apiResult": {
                                    "code": "OK",
                                    "message": null
                                }
                            },
                            "error": {
                                "httpStatus": 200,
                                "apiResult": {
                                    "code": "对应的错误码",
                                    "message": "具体的错误信息"
                                }
                            }
                        }
                    }
                },
                "service": {
                    "description": "业务逻辑层,实现具体业务功能",
                    "types": {
                        "database": {
                            "description": "涉及数据库操作的服务",
                            "structure": {
                                "interface": "src/main/java/com/shnet/admin/service/*Service.java",
                                "implementation": "src/main/java/com/shnet/admin/service/impl/*ServiceImpl.java"
                            },
                            "pattern": "接口+实现类模式",
                            "userContext": {
                                "description": "用户上下文传递",
                                "parameter": "String userId",
                                "usage": "用于记录操作日志"
                            }
                        },
                        "business": {
                            "description": "纯业务逻辑服务(不涉及数据库)",
                            "structure": "src/main/java/com/shnet/admin/service/${businessType}/*Service.java",
                            "pattern": "只需实现类",
                            "example": "leaderElection/LeaderElectionService.java"
                        }
                    }
                },
                "mongodb": "MongoDB数据访问层接口,存放所有Repository接口",
                "mongodb.entity": "MongoDB实体类定义,存放所有Entity类",
                "dto": "数据传输对象,用于接口请求和响应",
                "config": "配置类",
                "utils": "工具类",
                "core": {
                    "description": "核心功能包,包含基础组件和通用功能",
                    "subPackages": {
                        "api": "API响应相关类,如ApiResult、ApiCode等",
                        "page": {
                            "description": "统一分页封装",
                            "classes": {
                                "Page": "分页数据封装类,所有列表接口必须使用此类"
                            },
                            "usage": {
                                "description": "分页查询规范",
                                "methods": {
                                    "mongoTemplate": {
                                        "description": "使用MongoTemplate进行复杂查询和分页",
                                        "example": [
                                            "// 1. 构建查询条件",
                                            "Query query = new Query();",
                                            "if (StringUtils.isNotBlank(param)) {",
                                            "    query.addCriteria(Criteria.where(\"field\").regex(param));",
                                            "}",
                                            "",
                                            "// 2. 获取总数",
                                            "long total = mongoTemplate.count(query, EntityClass.class);",
                                            "",
                                            "// 3. 添加分页条件",
                                            "query.skip((page - 1) * size).limit(size);",
                                            "",
                                            "// 4. 执行查询",
                                            "List<EntityClass> list = mongoTemplate.find(query, EntityClass.class);",
                                            "",
                                            "// 5. 使用Page封装结果",
                                            "return new Page<>(list, total, page, size);"
                                        ]
                                    }
                                }
                            }
                        },
                        "exception": {
                            "description": "异常处理相关类",
                            "components": {
                                "AbstractBusinessException": "所有业务异常的基类",
                                "ExceptionHandler": "异常处理器接口",
                                "*Exception": "具体业务异常类",
                                "*ExceptionHandler": "具体业务异常处理器"
                            }
                        },
                        "distributionLock": "分布式锁实现",
                        "security": "安全相关功能",
                        "utils": "核心工具类"
                    }
                },
                "processor": {
                    "description": "复杂业务处理流包",
                    "structure": {
                        "base": "src/main/java/com/shnet/admin/processor/base",
                        "impl": "src/main/java/com/shnet/admin/processor/impl"
                    },
                    "patterns": {
                        "strategy": "不同实现策略的选择",
                        "template": "定义算法骨架,让子类实现具体步骤",
                        "chain": "责任链模式处理复杂流程",
                        "factory": "创建具体策略实例"
                    }
                },
                "schedule": {
                    "description": "定时任务包,存放所有定时任务类",
                    "baseClass": "BaseScheduler",
                    "structure": {
                        "path": "src/main/java/com/shnet/admin/schedule",
                        "naming": "*Scheduler"
                    },
                    "executionMode": {
                        "leaderOnly": {
                            "description": "只允许leader节点执行的定时任务",
                            "implementation": [
                                "@Override",
                                "protected boolean isLeaderOnly() {",
                                "    return true;",
                                "}"
                            ]
                        },
                        "allNodes": {
                            "description": "所有节点都可以执行的定时任务",
                            "implementation": [
                                "@Override",
                                "protected boolean isLeaderOnly() {",
                                "    return false;",
                                "}"
                            ]
                        }
                    },
                    "annotations": {
                        "required": [
                            "@Component",
                            "@EnableScheduling"
                        ],
                        "scheduling": "@Scheduled"
                    }
                }
            },
            "paths": {
                "repository": "src/main/java/com/shnet/admin/mongodb",
                "entity": "src/main/java/com/shnet/admin/mongodb/entity",
                "core": "src/main/java/com/shnet/admin/core"
            }
        },
        "conventions": {
            "naming": {
                "controller": "*Controller",
                "service": {
                    "interface": "*Service",
                    "implementation": "*ServiceImpl"
                },
                "repository": "*Repository",
                "entity": "*Entity",
                "dto": "*DTO"
            },
            "annotations": {
                "controller": [
                    "@RestController",
                    "@RequestMapping",
                    "@Tag",
                    "@Validated",
                    "@Slf4j"
                ],
                "service": [
                    "@Service",
                    "@Autowired"
                ],
                "repository": [],
                "entity": [
                    "@Document",
                    "@Data",
                    "@Id",
                    "@Version"
                ]
            },
            "service": {
                "database": {
                    "interface": {
                        "location": "src/main/java/com/shnet/admin/service",
                        "naming": "*Service"
                    },
                    "implementation": {
                        "location": "src/main/java/com/shnet/admin/service/impl",
                        "naming": "*ServiceImpl"
                    }
                },
                "business": {
                    "location": "src/main/java/com/shnet/admin/service/${businessType}",
                    "naming": "*Service"
                }
            }
        },
        "documentation": {
            "swagger": {
                "controller": {
                    "required": ["@Tag", "@Operation", "@Parameter"],
                    "responseFormat": "ResponseEntity<ApiResult>"
                }
            },
            "methods": {
                "format": "/**\n * @param [参数名] [参数描述]\n * @return [返回值描述]\n */"
            }
        },
        "security": {
            "authentication": "@PreAuthorize",
            "validation": ["@Valid", "@Validated"]
        },
        "errorHandling": {
            "exceptions": {
                "custom": "BusinessException",
                "validation": "MethodArgumentNotValidException"
            },
            "response": "ApiResult",
            "baseException": {
                "class": "AbstractBusinessException",
                "requiredFields": {
                    "ERROR_CODE_PREFIX": "String (业务异常前缀)",
                    "HTTP_STATUS": "HttpStatus (默认HttpStatus.OK)"
                }
            },
            "exceptionHandler": {
                "interface": "ExceptionHandler",
                "implementation": {
                    "annotations": ["@Component"],
                    "template": [
                        "@Component",
                        "public class ${name}ExceptionHandler implements ExceptionHandler<${name}Exception> {",
                        "    // ExceptionHandler接口提供默认实现",
                        "}"
                    ]
                }
            }
        },
        "sourceRoot": {
            "description": "源代码根目录位置",
            "rule": "源代码目录(src/)应与.cursorrules文件位于同一目录下",
            "example": {
                "cursorrules": "ai-admin/.cursorrules",
                "sourceCode": "ai-admin/src/..."
            }
        }
    },
    "prompts": {
        "createController": "创建一个RESTful控制器,包含标准的CRUD操作和适当的权限控制",
        "createService": "创建一个服务接口及其实现类,包含业务逻辑和事务管理",
        "createDTO": "创建一个DTO类,包含必要的验证注解和序列化配置",
        "createEntity": "创建一个实体类,包含JPA注解和审计字段"
    },
    "bestPractices": {
        "controller": [
            "使用统一的响应格式 ResponseEntity<ApiResult>",
            "添加适当的OpenAPI文档注解",
            "实现参数验证",
            "权限控制"
        ],
        "service": [
            "业务逻辑封装",
            "事务管理",
            "异常处理",
            "日志记录"
        ],
        "general": [
            "使用统一的异常处理",
            "遵循阿里巴巴Java开发规范",
            "添加适当的注释和文档"
        ]
    },
    "taskChains": {
        "createFeatureModule": {
            "description": "创建完整的功能模块,包含Controller、Service、DTO、Entity等",
            "steps": [
                {
                    "name": "createEntity"
                },
                {
                    "name": "createRepository"
                },
                {
                    "name": "createDTO",
                    "variants": [
                        {
                            "suffix": "CreateDTO",
                            "purpose": "创建请求对象",
                            "validation": true
                        },
                        {
                            "suffix": "UpdateDTO",
                            "purpose": "更新请求对象",
                            "validation": true
                        },
                        {
                            "suffix": "DTO",
                            "purpose": "响应对象"
                        }
                    ]
                },
                {
                    "name": "createService"
                },
                {
                    "name": "createController"                },
                {
                    "name": "createException"
                },
                {
                    "name": "createComplexProcessor",
                    "description": "创建复杂业务处理器",
                    "steps": [
                        {
                            "name": "createProcessorInterface"
                        },
                        {
                            "name": "createProcessorContext"
                            
                        },
                        {
                            "name": "createAbstractProcessor"
                        },
                        {
                            "name": "createStrategyFactory"
                        }
                    ]
                },
                {
                    "name": "createScheduler",
                    "description": "创建定时任务类",
                    "parameters": {
                        "name": "定时任务名称",
                        "description": "定时任务描述",
                        "schedule": "定时任务表达式",
                        "leaderOnly": "是否只允许leader执行"
                    },
                    "template": {
                        "path": "src/main/java/com/shnet/admin/schedule/${name}Scheduler.java",
                        "baseClass": "BaseScheduler",
                        "imports": [
                            "org.springframework.scheduling.annotation.EnableScheduling",
                            "org.springframework.scheduling.annotation.Scheduled",
                            "org.springframework.stereotype.Component",
                            "lombok.extern.slf4j.Slf4j"
                        ],
                        "annotations": [
                            "@Slf4j",
                            "@Component",
                            "@EnableScheduling"
                        ],
                        "methods": {
                            "isLeaderOnly": {
                                "description": "是否只允许leader执行",
                                "template": [
                                    "@Override",
                                    "protected boolean isLeaderOnly() {",
                                    "    return ${leaderOnly};",
                                    "}"
                                ]
                            },
                            "execute": {
                                "description": "定时任务执行入口",
                                "template": [
                                    "@Scheduled(${schedule})",
                                    "public void execute() {",
                                    "    if (!canExecuteSchedule()) {",
                                    "        return;",
                                    "    }",
                                    "    try {",
                                    "        doExecute();",
                                    "    } catch (Exception e) {",
                                    "        log.error(\"${description}执行异常\", e);",
                                    "    }",
                                    "}"
                                ]
                            },
                            "doExecute": {
                                "description": "具体任务实现",
                                "template": [
                                    "private void doExecute() {",
                                    "    // 实现具体的任务逻辑",
                                    "}"
                                ]
                            }
                        }
                    }
                }
            ],
            "usage": {
                "command": "createFeatureModule",
                "parameters": {
                    "name": "模块名称(英文)",
                    "description": "模块描述(中文)",
                    "fields": "字段定义列表",
                    "security": "权限配置"
                },
                "example": {
                    "name": "Product",
                    "description": "产品管理",
                    "fields": [
                        {
                            "name": "name",
                            "type": "String",
                            "validation": "@NotBlank(message = \"名称不能为空\")",
                            "description": "产品名称"
                        }
                    ],
                    "security": "operate_products"
                }
            }
        },
        "createBusinessService": {
            "description": "创建纯业务逻辑服务类",
            "parameters": {
                "name": "服务名称",
                "businessType": "业务类型(用作包名)",
                "description": "服务描述"
            },
            "template": {
                "path": "src/main/java/com/shnet/admin/service/${businessType}/${name}Service.java",
                "annotations": ["@Service"],
                "imports": []
            }
        },
        "complexBusinessProcess": {
            "steps": [
                {
                    "phase": "需求分析",
                    "actions": [
                        "明确业务目标和范围",
                        "识别关键流程和决策点",
                        "定义输入输出",
                        "确定性能和扩展性要求"
                    ]
                },
                {
                    "phase": "伪代码设计",
                    "template": [
                        "1. 流程概述",
                        "2. 核心步骤拆解",
                        "3. 关键决策点",
                        "4. 异常处理",
                        "5. 扩展点预留"
                    ]
                },
                {
                    "phase": "方案讨论",
                    "focus": [
                        "流程合理性",
                        "扩展性考虑",
                        "性能影响",
                        "维护成本"
                    ]
                },
                {
                    "phase": "代码实现",
                    "patterns": {
                        "strategy": {
                            "usage": "多种实现方式选择",
                            "structure": {
                                "interface": "${name}Strategy",
                                "implementations": "${name}${Type}Strategy"
                            }
                        },
                        "template": {
                            "usage": "固定流程不同实现",
                            "structure": {
                                "abstract": "Abstract${name}Processor",
                                "concrete": "${name}${Type}Processor"
                            }
                        }
                    }
                }
            ]
        }
    },
    "logging": {
        "service": {
            "interface": "LogService",
            "methods": {
                "createLog": {
                    "parameters": ["LogCreateDto logCreateDto"],
                    "usage": "记录用户操作日志",
                    "example": {
                        "description": "参考 MachineConfigServiceImpl.addMachineConfig 方法",
                        "code": [
                            "// 构建日志数据",
                            "Map<String, Object> logData = new HashMap<>();",
                            "logData.put(\"newConfig\", savedConfig);",
                            "",
                            "// 创建日志",
                            "logService.createLog(new LogCreateDto(",
                            "    new LogDataDto(\"addMachineConfig\", logData),  // 操作类型和数据",
                            "    \"info\",                                        // 日志级别",
                            "    \"Added new machine configuration\",             // 日志描述",
                            "    \"TaskService\",                                 // 服务名称",
                            "    userID                                          // 用户ID",
                            "));"
                        ]
                    }
                }
            },
            "dto": {
                "LogCreateDto": {
                    "fields": [
                        "LogDataDto logData",
                        "String level",
                        "String message",
                        "String service",
                        "String userId"
                    ]
                },
                "LogDataDto": {
                    "fields": [
                        "String operation",
                        "Map<String, Object> data"
                    ]
                }
            }
        }
    }
}

As project become bigger and bigger, I realized Composer generate code can’t fit my thought. Though the bulk generate code is great, but it always have some error, so I have to check the generate code every time. This is not good experience.

I design this .cursorrules for solving these some.

For example,
one of my requirement is generate template code. So I design the ‘createBasicModule’ command. When I run this command, it will generate java CURD codes that fit my thought.

For the complex processor, I design the ‘createComplexProcessor’ command. If I do this step by step, first it will generate pseudocode, and then create target classes, finally generate true business code.

The code what generate by this rules is great. AI can follow the project structure and the code also fit the structure. After do this, I decrease check code times, it’s great experience for me.

All of the rules, you don’t have to design manually, you can generate them by AI. When your project structure changed, you need change the rules.

2 Likes

Now cursor should read the .cursorrules what is in root every time. So you can give some context that you need tell cursor let AI know your thought.

2 Likes

I’ll take some time to understand the methodology that you are using. I believe I am starting at a higher level. I speak more in terms of:

  1. Role and Task Definition:
  2. Goals:
  3. Framework and Tools:
  4. Architecture Diagram:
  5. C# Bridge Application Structure:
  6. and so on

As the application progresses I remove the specific instructions while maintaining the 1-5 items.

I then include as the application progresses:

  1. Completed Tasks - and mark the completed tasks as completed
  2. Next Tasks

This is also what I keep in cursorrules:

TokenizerBridge/
├── src/
│ ├── TokenizerBridge/
│ │ ├── Program.cs
│ │ ├── appsettings.json C
│ │ ├── Models/
│ │ │ ├── TokenizationRequest.cs
│ │ │ ├── TokenizationResponse.cs
│ │ │ └── TokenizerSettings.cs
│ │ ├── Services/
│ │ │ ├── TokenizerService.cs
│ │ │ └── PythonProcessManager.cs
│ │ ├── Consumers/
│ │ │ └── TokenizationRequestConsumer.cs
│ │ │
│ │ └── Configuration/
│ │ ├── BusConfig.cs C
│ │ └── BusConfigurationExtensions.cs C
│ └── TokenizerBridge.Tests/
└── scripts/
└── test_tiktoken.py C

I’ll go through your prompt with AI, as it is beyond my immediate understanding. Let me know what you would like to see from me and I will do the same.

Maybe we should start a new thread?
-Matthew

That’s great tactics and I also maintain these info, for example project structure, tasks what i want, list task, mark task. But I save these info in the README.md.

When the project just begin, I generate codes by the README files and it work very nice. But as project become bigger and bigger, structure become more and more stable, I have to think how to let the generate codes can fit my project. Because through the README, AI will generate code what it feel good itself, for new component and new structure that’s great. But now for my stable structure I want to the generate code can fit my structure as far as possible. So I create this rules for my requirement. And then it just begin and need to improve.

Below is rules explain:

For example, below is a snippet in my project. This is a schedule, and its structure is very stable. It have to follow some class rules.

First it must extends BaseScheduler.
Second override isLeaderOnly function.
Third main fucntion must run canExecuteSchedule fucntion.

package com.xxx.admin.schedule;

import com.xxxThis text will be hidden.admin.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableScheduling
public class TaskResetScheduler extends BaseScheduler {

    @Autowired
    private TaskService taskService;

    @Override
    protected boolean isLeaderOnly() {
        return true;
    }

    /**
     * 每20秒执行一次任务重置检查
     */
    @Scheduled(cron = "*/20 * * * * ?")
    public void checkAndResetTasks() {
        log.info("checkAndResetTasks start");
        if (!canExecuteSchedule()) {
            return;
        }

        try {
            taskService.checkAndResetTasks();
        } catch (Exception e) {
            log.error("Error executing task reset scheduler", e);
        } finally {
            log.info("checkAndResetTasks end");
        }
    }
}

When I simply talk to AI about I need a new schedule class, AI generate code can’t follow above rules. And then additional, I tell AI ‘you can reference exists code for example xxxSchedule.java’, Yes the generate code become better, seem do its best to follow these rules. But, the generate code have some error
sometimes, for example, miss some import, miss package keywords, import error class, use unexpected fuction and so on. For solving these solution, I add below new rules.

{
                    "name": "createScheduler",
                    "description": "创建定时任务类",
                    "parameters": {
                        "name": "定时任务名称",
                        "description": "定时任务描述",
                        "schedule": "定时任务表达式",
                        "leaderOnly": "是否只允许leader执行"
                    },
                    "template": {
                        "path": "src/main/java/com/shnet/admin/schedule/${name}Scheduler.java",
                        "baseClass": "BaseScheduler",
                        "imports": [
                            "org.springframework.scheduling.annotation.EnableScheduling",
                            "org.springframework.scheduling.annotation.Scheduled",
                            "org.springframework.stereotype.Component",
                            "lombok.extern.slf4j.Slf4j"
                        ],
                        "annotations": [
                            "@Slf4j",
                            "@Component",
                            "@EnableScheduling"
                        ],
                        "methods": {
                            "isLeaderOnly": {
                                "description": "是否只允许leader执行",
                                "template": [
                                    "@Override",
                                    "protected boolean isLeaderOnly() {",
                                    "    return ${leaderOnly};",
                                    "}"
                                ]
                            },
                            "execute": {
                                "description": "定时任务执行入口",
                                "template": [
                                    "@Scheduled(${schedule})",
                                    "public void execute() {",
                                    "    if (!canExecuteSchedule()) {",
                                    "        return;",
                                    "    }",
                                    "    try {",
                                    "        doExecute();",
                                    "    } catch (Exception e) {",
                                    "        log.error(\"${description}执行异常\", e);",
                                    "    }",
                                    "}"
                                ]
                            },
                            "doExecute": {
                                "description": "具体任务实现",
                                "template": [
                                    "private void doExecute() {",
                                    "    // 实现具体的任务逻辑",
                                    "}"
                                ]
                            }
                        }
                    }
                }

These rules can make the AI generate code follow class rules. And the generate code is not error any more.

About how to use the cursorrules, the way I come up with it is to use command. So I tell AI that I want to run them via command, and AI help me generate below command and update into the cursorrules file.

"createScheduler": {
            "description": "创建定时任务",
            "examples": [
                {
                    "name": "leader专属定时任务",
                    "command": "cursor createScheduler --name TaskClean --description '任务清理' --schedule '0 0 2 * * ?' --leaderOnly true"
                },
                {
                    "name": "所有节点执行的定时任务",
                    "command": "cursor createScheduler --name HealthCheck --description '健康检查' --schedule '0/30 * * * * ?' --leaderOnly false"
                }
            ]
        }

Now I only run

cursor createScheduler --name TaskClean --description '任务清理' --schedule '0 0 2 * * ?' --leaderOnly true

My new schedule class named TaskCleanScheduler will be generate what is fellow all of my thought.

For complex business, my step is blew:

  1. generate pseudocode
  2. about pseudocode talk with AI until content what is so detail
  3. when we have more detail context, tell AI generate true code via these context

First step also can use command, it make prompt easy by manual.

Hi guy, this is my practice but not best practices. You could share the method if you have any better method.
-Yun Huang

2 Likes