
ECC 的 Cursor Kotlin 规则kotlin-patterns.md 如何为 .kt 文件注入 Kotlin 惯用模式约束【免费下载链接】ECCThe agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.项目地址: https://gitcode.com/GitHub_Trending/ev/ECC本文以 ECC 仓库中 kotlin-patterns.md 规则文件为主体完整拆解 Cursor 规则的前置元数据globs 匹配与按需加载机制、Sealed 类、扩展函数、作用域函数与 Koin 依赖注入四大 Kotlin 模式约束并结合同目录规则族、kotlin-patterns skill 与 Cursor 安装目标 的源码说明这条规则在 ECC agent harness 中如何被触发、如何延伸、又如何分发到实际项目中。读完你可以掌握为 Cursor 编写语言级规则文件的方法、规则与 skill 的分层协作关系以及一套可直接落地的 Kotlin 编码约束。一、规则文件本体一个“按需加载”的 Kotlin 模式约束.cursor/rules/kotlin-patterns.md 是 ECC 为 Cursor 编辑器提供的 Kotlin 语言规则文件。与alwaysApply: true的全局规则不同它通过前置元数据声明自己的适用范围只在编辑 Kotlin 相关文件时才注入上下文--- description: Kotlin patterns extending common rules globs: [**/*.kt, **/*.kts, **/build.gradle.kts] alwaysApply: false ---三个字段的含义globs文件匹配模式。**/*.kt与**/*.kts覆盖 Kotlin 源码和 Kotlin 脚本**/build.gradle.kts把 Gradle Kotlin DSL 构建脚本也纳入约束——这与 kotlin-patterns skill 中“Configuring Gradle Kotlin DSL builds”的使用场景对应alwaysApply: false规则不随会话常驻仅在 globs 命中时被加载避免污染其他语言任务的上下文预算description向 Agent 说明该规则定位——“在 common 规则基础上扩展 Kotlin 专属内容”。从文件结构看正文以一行提示This file extends the common patterns rule with Kotlin-specific content开篇明确它是一条增量规则基础约束来自 common-patterns.md本文件只补充 Kotlin 专属部分。这种“common 打底 语言扩展”的分层写法在.cursor/rules/目录中是统一模式Kotlin 规则族共五个文件规则文件覆盖主题kotlin-coding-style.md格式化ktfmt/ktlint、不可变性、空安全、表达式体kotlin-patterns.mdSealed 类、扩展函数、作用域函数、依赖注入kotlin-testing.mdKotest MockK、runTest协程测试、Kover 覆盖率kotlin-security.mdKotlin 安全约束kotlin-hooks.mdKotlin 相关的 hook 配置五个文件使用完全相同的 globs 声明意味着打开任意.kt文件时这一整套约束会同时生效——模式、风格、测试、安全形成闭环。二、Sealed Classes用密封类型建模穷举层级规则给出的核心示例是泛型Result类型sealed class Resultout T { data class SuccessT(val data: T) : ResultT() data class Failure(val error: AppError) : ResultNothing() }要点解析sealed class声明受限制的继承层级所有子类必须在同一文件内定义使when表达式可以做到编译期穷举——遗漏分支直接报错而不是运行时才暴露out T是泛型协变声明允许SuccessNothing这类子类型关系成立Failure声明为ResultNothing表达“失败分支不携带成功数据”这一语义Nothing是 Kotlin 的底部类型top-level 中任何类型都是它的子类型。这与 common 规则中 API Response Format 的“统一响应包络”思想一脉相承用类型系统而非约定俗成的字段命名来强制success/data/error的互斥关系。在 ECC 的 kotlin-patterns skill 中这个模式被进一步扩展为带Loading分支的三态版本并配上了穷举消费函数sealed class Resultout T { data class SuccessT(val data: T) : ResultT() data class Failure(val error: AppError) : ResultNothing() data object Loading : ResultNothing() } fun T ResultT.getOrNull(): T? when (this) { is Result.Success - data is Result.Failure - null is Result.Loading - null }skill 中还给出了sealed interface建模 API 错误的进阶用法ApiError.NotFound/Unauthorized/Validation/Internal各自映射到 404/401/422/500 状态码展示了同一“穷举层级”思想在错误域的应用。规则文件给出最小可用形态skill 给出完整版——这正是 ECC “规则管底线、skill 管深度”的分层设计。三、Extension Functions不继承、不污染的全局扩展规则给出的示例是把行为“加”到String上且限定在使用的地方fun String.toSlug(): String lowercase().replace(Regex([^a-z0-9\\s-]), ).replace(Regex(\\s), -)“scoped to where theyre used” 这句约束的含义在 skill 的示例中有明确落地——作用域化的扩展函数把扩展函数声明为类内部的private成员避免污染全局命名空间class UserService { private fun User.isActive(): Boolean status Status.ACTIVE lastLogin.isAfter(Instant.now().minus(30, ChronoUnit.DAYS)) fun getActiveUsers(): ListUser userRepository.findAll().filter { it.isActive() } }此外 skill 补充了两个实用形态带默认参数的时间转换扩展Instant.toLocalDate(zone)和集合扩展ListT.secondOrNull()基于标准库getOrNull(1)一行实现说明规则约束的是“扩展函数应当领域化、私有化、可测试”而非仅仅“可以用扩展函数”。四、Scope Functions四种作用域函数的分工与反模式规则对五个作用域函数给出了明确的职责划分规则原文列了三个skill 补全了run/withlet转换可空或受限结果返回 lambda 结果——val length: Int? name?.let { it.trim().length }apply配置对象返回对象本身——User().apply { name Alice; email ... }also副作用日志、埋点返回对象本身——createUser(request).also { logger.info(Created user: ${it.id}) }run带接收者的块执行返回 lambda 结果——connection.run { prepareStatement(sql); executeQuery() }withrun的非扩展形式——with(StringBuilder()) { appendLine(...); toString() }规则明确禁止的一条反模式是嵌套作用域函数skill 给出了对照示例// Bad: Nesting scope functions user?.let { u - u.address?.let { addr - addr.city?.let { city - println(city) } // 嵌套三层可读性崩塌 } } // Good: Chain safe calls instead val city user?.address?.city city?.let { println(it) }这条约束与同目录 kotlin-coding-style.md 中“避免!!使用?.、?:、require”的空安全条款互相配合安全调用链优先作用域函数只在确有“转换/配置/副作用”语义时使用。五、Dependency InjectionKoin 模块在 Ktor 项目中的声明方式规则给出的是 Koin 声明式模块且特意绑定 Ktor 场景规则原文val appModule module { singleUserRepository { ExposedUserRepository(get()) } single { UserService(get()) } }singleT注册单例{ ExposedUserRepository(get()) }中的get()在装配时从容器解析依赖这里解析的是数据库连接/事务对象实现构造器注入而非字段注入single { UserService(get()) }隐式按类型注册UserServiceget()拉取UserRepository从 skill 的 Gradle Kotlin DSL 配置 看ECC 的推荐技术栈组合是Ktor 3.4.0 Exposed 1.0.0 Koin 4.2.0io.insert-koin:koin-ktor kotlinx-coroutines 1.10.2Koin 模块即作为该栈的标准 DI 层。规则层面更完整的版本来自 rules/kotlin/patterns.md它是本规则在非 Cursor 平台的对应物区分了两种 DI 选型KMP 项目用 Koin纯 Android 项目用 Hilt// Koin — declare modules val dataModule module { singleItemRepository { ItemRepositoryImpl(get(), get()) } factory { GetItemsUseCase(get()) } viewModelOf(::ItemListViewModel) }注意factory每次解析新建适合无状态 UseCase 与 ViewModel 之外的短生命周期对象与single的生命周期区别这是规则文件最小示例中未展开、但实操中必须理解的参数差异。六、从规则到 Skillkotlin-patterns的引用闭环规则文件末尾的 Reference 段落指向 skillSee skill:kotlin-patternsfor comprehensive Kotlin patterns including coroutines, DSL builders, and delegation.在 ECC 的架构中.cursor/rules/是常驻约束层短小、可按 globs 自动加载skills/是深度知识层按需激活的完整手册。两者内容同源且互相呼应规则文件的 Sealed 类示例两态Result是 skill 中三态Result的简化版规则文件的toSlug()扩展函数在 skill 中补齐了.trim(-)收尾和“作用域化扩展”最佳实践规则文件未覆盖的协程、DSL、委托三大主题全部由 skill 承接。skill 额外提供的关键模式读者若需完整 Kotlin 工程约束应一并阅读 skills/kotlin-patterns/SKILL.md结构化并发——coroutineScope并行取数、supervisorScope让子任务失败互相独立suspend fun fetchUserWithPosts(userId: String): UserProfile coroutineScope { val user async { userService.getUser(userId) } val posts async { postService.getUserPosts(userId) } UserProfile(user user.await(), posts posts.await()) }类型安全 DSL Builder——用DslMarker防止隐式接收者歧义DslMarker annotation class HtmlDsl HtmlDsl class HTML { fun body(init: Body.() - Unit) { children Body().apply(init) } // ... } fun html(init: HTML.() - Unit): HTML HTML().apply(init)接口委托——UserRepository by delegate一行实现透传只覆写需要加日志的方法。此外 skill 末尾的“Quick Reference”表格把 16 条 Kotlin 惯用法valovervar、value class、when表达式、Flow、sequence懒求值、by委托等汇总为速查表可直接作为 code review 的 checklist 使用。七、配套约束构建配置与测试规则如何咬合Kotlin 规则族中另外两个文件为 patterns 规则提供了执行保障构建层kotlin-patterns skill 给出了完整的build.gradle.kts参考配置关键项包括plugins { kotlin(jvm) version 2.3.10 id(io.ktor.plugin) version 3.4.0 id(org.jetbrains.kotlinx.kover) version 0.9.7 id(io.gitlab.arturbosch.detekt) version 1.23.8 } kotlin { jvmToolchain(21) } detekt { config.setFrom(files(config/detekt/detekt.yml)) buildUponDefaultConfig true }globs中包含**/build.gradle.kts的意义在此体现规则不仅约束业务代码也约束构建脚本本身的写法Kotlin DSL 风格、依赖版本管理。测试层kotlin-testing.md 规定使用KotestStringSpec/FunSpec/BehaviorSpec 风格MockK做 mock协程代码统一用runTesttest(async operation completes) { runTest { val result service.fetchData() result.shouldNotBeEmpty() } }覆盖率由Kover报告。这意味着 patterns 规则里要求写出的ResultT返回值在测试规则里有对应的验证手段——suspend fun getById(id: String): ResultItem这类接口见 rules/kotlin/patterns.md 的 Repository 模式天然适合 Kotest 断言。八、分发机制规则如何进入用户项目从源码结构看.cursor/rules/并非仅供本仓库使用而是 ECC 安装器面向 Cursor 平台的分发源。scripts/lib/install-targets/cursor-project.js 中存在sourceRelativePath: .cursor/rules的声明将规则目录整体作为安装操作的目标路径之一tests/lib/install-targets.test.js 中的断言如检查.cursor/rules/common-coding-style.md、common-agents.md等文件验证了安装清单对这些规则文件的覆盖并处理了“平台规则与原生.cursor/rules内容冲突时优先保留原生内容”的逻辑。换言之当开发者通过 ECC 的安装流程把 harness 部署到一个 Kotlin/Ktor 项目时kotlin-patterns.md会随规则族落入目标项目的.cursor/rules/此后 Cursor 中的 Agent 在触碰任何.kt文件时即自动获得本文第二节至第五节的全部约束——无需在每条提示中手动复述团队约定。九、速查与落地建议结合规则文件本体与 skill 的完整版可提炼出 Kotlin 项目的最小约束集约束落地方式依据穷举类型层级sealed class/interface 穷举when失败态用Nothingkotlin-patterns.md扩展函数私有化领域扩展声明为类内private成员函数SKILL.md Extension Functions 节作用域函数不嵌套优先?.链let/apply/also/run/with按语义选择SKILL.md Scope Functions 节DI 构造器注入KMP 用 Koinsingle/factory区分生命周期Android 用 Hiltrules/kotlin/patterns.md协程测试runTest Kotest MockKKover 出覆盖率kotlin-testing.md构建脚本同受约束globs 覆盖build.gradle.ktsdetekt 静态检查SKILL.md Gradle Kotlin DSL 节最后需要说明适用前提本文所有版本与依赖坐标Kotlin 2.3.10、Ktor 3.4.0、Koin 4.2.0 等均以当前仓库 skill 文档中记录的值为准规则文件本身只声明约束语义不绑定具体依赖版本实际项目中应按自身技术栈调整但“common 打底、语言规则扩展、skill 承接深度”这一三层结构可以直接照搬到其他语言的规则体系建设中。【免费下载链接】ECCThe agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.项目地址: https://gitcode.com/GitHub_Trending/ev/ECC创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考