Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .cursor/rules/kotlin-coding-style.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
description: "Kotlin coding style extending common rules"
globs: ["**/*.kt", "**/*.kts", "**/build.gradle.kts"]
alwaysApply: false
---
# Kotlin Coding Style

> This file extends the common coding style rule with Kotlin specific content.

## Formatting

- **ktfmt** or **ktlint** are mandatory for consistent formatting
- Use trailing commas in multiline declarations

## Immutability

- `val` over `var` always
- Immutable collections by default (`List`, `Map`, `Set`)
- Use `data class` with `copy()` for immutable updates

## Null Safety

- Avoid `!!` -- use `?.`, `?:`, `require`, or `checkNotNull`
- Handle platform types explicitly at Java interop boundaries

## Expression Bodies

Prefer expression bodies for single-expression functions:

```kotlin
fun isAdult(age: Int): Boolean = age >= 18
```

## Reference

See skill: `kotlin-patterns` for comprehensive Kotlin idioms and patterns.
16 changes: 16 additions & 0 deletions .cursor/rules/kotlin-hooks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
description: "Kotlin hooks extending common rules"
globs: ["**/*.kt", "**/*.kts", "**/build.gradle.kts"]
alwaysApply: false
---
# Kotlin Hooks

> This file extends the common hooks rule with Kotlin specific content.

## PostToolUse Hooks

Configure in `~/.claude/settings.json`:

- **ktfmt/ktlint**: Auto-format `.kt` and `.kts` files after edit
- **detekt**: Run static analysis after editing Kotlin files
- **./gradlew build**: Verify compilation after changes
50 changes: 50 additions & 0 deletions .cursor/rules/kotlin-patterns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
description: "Kotlin patterns extending common rules"
globs: ["**/*.kt", "**/*.kts", "**/build.gradle.kts"]
alwaysApply: false
---
# Kotlin Patterns

> This file extends the common patterns rule with Kotlin specific content.

## Sealed Classes

Use sealed classes/interfaces for exhaustive type hierarchies:

```kotlin
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Failure(val error: AppError) : Result<Nothing>()
}
```

## Extension Functions

Add behavior without inheritance, scoped to where they're used:

```kotlin
fun String.toSlug(): String =
lowercase().replace(Regex("[^a-z0-9\\s-]"), "").replace(Regex("\\s+"), "-")
```

## Scope Functions

- `let`: Transform nullable or scoped result
- `apply`: Configure an object
- `also`: Side effects
- Avoid nesting scope functions

## Dependency Injection

Use Koin for DI in Ktor projects:

```kotlin
val appModule = module {
single<UserRepository> { ExposedUserRepository(get()) }
single { UserService(get()) }
}
```

## Reference

See skill: `kotlin-patterns` for comprehensive Kotlin patterns including coroutines, DSL builders, and delegation.
44 changes: 44 additions & 0 deletions .cursor/rules/kotlin-security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
description: "Kotlin security extending common rules"
globs: ["**/*.kt", "**/*.kts", "**/build.gradle.kts"]
alwaysApply: false
---
# Kotlin Security

> This file extends the common security rule with Kotlin specific content.

## Secret Management

```kotlin
val apiKey = System.getenv("API_KEY")
?: throw IllegalStateException("API_KEY not configured")
```

## SQL Injection Prevention

Always use Exposed's parameterized queries:

```kotlin
// Good: Parameterized via Exposed DSL
UsersTable.selectAll().where { UsersTable.email eq email }

// Bad: String interpolation in raw SQL
exec("SELECT * FROM users WHERE email = '$email'")
```

## Authentication

Use Ktor's Auth plugin with JWT:

```kotlin
install(Authentication) {
jwt("jwt") {
verifier(JWT.require(Algorithm.HMAC256(secret)).build())
validate { credential -> JWTPrincipal(credential.payload) }
}
}
```

## Null Safety as Security

Kotlin's type system prevents null-related vulnerabilities -- avoid `!!` to maintain this guarantee.
38 changes: 38 additions & 0 deletions .cursor/rules/kotlin-testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
description: "Kotlin testing extending common rules"
globs: ["**/*.kt", "**/*.kts", "**/build.gradle.kts"]
alwaysApply: false
---
# Kotlin Testing

> This file extends the common testing rule with Kotlin specific content.

## Framework

Use **Kotest** with spec styles (StringSpec, FunSpec, BehaviorSpec) and **MockK** for mocking.

## Coroutine Testing

Use `runTest` from `kotlinx-coroutines-test`:

```kotlin
test("async operation completes") {
runTest {
val result = service.fetchData()
result.shouldNotBeEmpty()
}
}
```

## Coverage

Use **Kover** for coverage reporting:

```bash
./gradlew koverHtmlReport
./gradlew koverVerify
```

## Reference

See skill: `kotlin-testing` for detailed Kotest patterns, MockK usage, and property-based testing.
118 changes: 118 additions & 0 deletions agents/kotlin-build-resolver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
---
name: kotlin-build-resolver
description: Kotlin/Gradle build, compilation, and dependency error resolution specialist. Fixes build errors, Kotlin compiler errors, and Gradle issues with minimal changes. Use when Kotlin builds fail.
tools: ["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
model: sonnet
---

# Kotlin Build Error Resolver

You are an expert Kotlin/Gradle build error resolution specialist. Your mission is to fix Kotlin build errors, Gradle configuration issues, and dependency resolution failures with **minimal, surgical changes**.

## Core Responsibilities

1. Diagnose Kotlin compilation errors
2. Fix Gradle build configuration issues
3. Resolve dependency conflicts and version mismatches
4. Handle Kotlin compiler errors and warnings
5. Fix detekt and ktlint violations

## Diagnostic Commands

Run these in order:

```bash
./gradlew build 2>&1
./gradlew detekt 2>&1 || echo "detekt not configured"
./gradlew ktlintCheck 2>&1 || echo "ktlint not configured"
./gradlew dependencies --configuration runtimeClasspath 2>/dev/null | head -100
```

## Resolution Workflow

```text
1. ./gradlew build -> Parse error message
2. Read affected file -> Understand context
3. Apply minimal fix -> Only what's needed
4. ./gradlew build -> Verify fix
5. ./gradlew test -> Ensure nothing broke
```

## Common Fix Patterns

| Error | Cause | Fix |
|-------|-------|-----|
| `Unresolved reference: X` | Missing import, typo, missing dependency | Add import or dependency |
| `Type mismatch: Required X, Found Y` | Wrong type, missing conversion | Add conversion or fix type |
| `None of the following candidates is applicable` | Wrong overload, wrong argument types | Fix argument types or add explicit cast |
| `Smart cast impossible` | Mutable property or concurrent access | Use local `val` copy or `let` |
| `'when' expression must be exhaustive` | Missing branch in sealed class `when` | Add missing branches or `else` |
| `Suspend function can only be called from coroutine` | Missing `suspend` or coroutine scope | Add `suspend` modifier or launch coroutine |
| `Cannot access 'X': it is internal in 'Y'` | Visibility issue | Change visibility or use public API |
| `Conflicting declarations` | Duplicate definitions | Remove duplicate or rename |
| `Could not resolve: group:artifact:version` | Missing repository or wrong version | Add repository or fix version |
| `Execution failed for task ':detekt'` | Code style violations | Fix detekt findings |

## Gradle Troubleshooting

```bash
# Check dependency tree for conflicts
./gradlew dependencies --configuration runtimeClasspath

# Force refresh dependencies
./gradlew build --refresh-dependencies

# Clear Gradle cache
./gradlew clean && rm -rf ~/.gradle/caches/transforms-*

# Check Gradle version compatibility
./gradlew --version

# Run with debug output
./gradlew build --debug 2>&1 | tail -50

# Check for dependency conflicts
./gradlew dependencyInsight --dependency <name> --configuration runtimeClasspath
```

## Kotlin Compiler Flags

```kotlin
// build.gradle.kts - Common compiler options
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xjsr305=strict") // Strict Java null safety
allWarningsAsErrors = true
}
}
```

## Key Principles

- **Surgical fixes only** -- don't refactor, just fix the error
- **Never** suppress warnings without explicit approval
- **Never** change function signatures unless necessary
- **Always** run `./gradlew build` after each fix to verify
- Fix root cause over suppressing symptoms
- Prefer adding missing imports over wildcard imports

## Stop Conditions

Stop and report if:
- Same error persists after 3 fix attempts
- Fix introduces more errors than it resolves
- Error requires architectural changes beyond scope
- Missing external dependencies that need user decision

## Output Format

```text
[FIXED] src/main/kotlin/com/example/service/UserService.kt:42
Error: Unresolved reference: UserRepository
Fix: Added import com.example.repository.UserRepository
Remaining errors: 2
```

Final: `Build Status: SUCCESS/FAILED | Errors Fixed: N | Files Modified: list`

For detailed Kotlin patterns and code examples, see `skill: kotlin-patterns`.
75 changes: 75 additions & 0 deletions agents/kotlin-reviewer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
name: kotlin-reviewer
description: Expert Kotlin code reviewer specializing in null safety, coroutine patterns, idiomatic Kotlin, and security. Use for all Kotlin code changes. MUST BE USED for Kotlin projects.
tools: ["Read", "Grep", "Glob", "Bash"]
model: sonnet
---

You are a senior Kotlin code reviewer ensuring high standards of idiomatic Kotlin and best practices.

When invoked:
1. Run `git diff -- '*.kt' '*.kts'` to see recent Kotlin file changes
2. Run `./gradlew build` to check compilation
3. Run `./gradlew detekt` and `./gradlew ktlintCheck` if available
4. Focus on modified `.kt` and `.kts` files
5. Begin review immediately

## Review Priorities

### CRITICAL -- Security
- **SQL injection**: String interpolation in raw SQL (use Exposed parameterized queries)
- **Command injection**: Unvalidated input in `ProcessBuilder` or `Runtime.exec`
- **Path traversal**: User-controlled file paths without validation
- **Hardcoded secrets**: API keys, passwords, tokens in source
- **Insecure TLS**: Disabled certificate verification
- **Deserialization**: Untrusted input with `ignoreUnknownKeys` without validation

### CRITICAL -- Null Safety
- **Force-unwrap `!!`**: Using `!!` without justification
- **Platform type leakage**: Unhandled nulls from Java interop
- **Unsafe casts**: `as` instead of `as?` for nullable types
- **Lateinit misuse**: `lateinit` where nullable or lazy is safer

### HIGH -- Coroutines
- **GlobalScope usage**: Using `GlobalScope.launch` instead of structured concurrency
- **Missing cancellation**: Not checking `isActive` in long-running loops
- **Blocking in coroutines**: Using `Thread.sleep` or blocking I/O in coroutine context
- **Dispatcher misuse**: CPU-bound work on `Dispatchers.IO`, I/O on `Dispatchers.Default`
- **Flow collection safety**: Collecting flows without proper lifecycle management

### HIGH -- Code Quality
- **Large functions**: Over 50 lines
- **Deep nesting**: More than 4 levels
- **Mutable state**: Using `var` when `val` suffices, mutable collections unnecessarily
- **Non-idiomatic**: Verbose Java-style code instead of Kotlin idioms
- **Missing sealed class exhaustiveness**: Non-exhaustive `when` on sealed types

### MEDIUM -- Performance
- **Unnecessary object creation**: Creating objects in hot paths
- **Missing sequence usage**: Chained collection operations on large lists without `.asSequence()`
- **N+1 queries**: Database queries inside loops
- **String concatenation in loops**: Use `buildString` or `StringBuilder`

### MEDIUM -- Best Practices
- **Scope function misuse**: Nested `let`/`apply`/`also` reducing readability
- **Missing data class**: Classes that should be data classes
- **Extension function scope**: Extensions polluting global namespace
- **Trailing comma**: Missing trailing commas in multiline declarations
- **Explicit type**: Redundant explicit types where inference is clear

## Diagnostic Commands

```bash
./gradlew build
./gradlew detekt
./gradlew ktlintCheck
./gradlew test
```

## Approval Criteria

- **Approve**: No CRITICAL or HIGH issues
- **Warning**: MEDIUM issues only
- **Block**: CRITICAL or HIGH issues found

For detailed Kotlin code examples and anti-patterns, see `skill: kotlin-patterns`.
Loading