From 3207c797ce1d301a06db742b2a295c9abdb88f53 Mon Sep 17 00:00:00 2001 From: Nelson Osacky Date: Tue, 1 Dec 2026 17:25:23 +0100 Subject: [PATCH] feat(code-review): Add Java, Kotlin, and Android reference The code-review skill had references only for JS/TS, Python, and GitHub workflows. A backtest on getsentry/sentry-java PRs found it caught 1 of 15 generic bugs Cursor Bugbot found on the same commit. Most misses were JVM and Android platform behavior the core contract does not name. The new reference covers missing API-level guards, old optional dependencies, unpaired bind and unregister, leaked descriptors, work after lifecycle end, main-thread blocking, clock choice, lost executor failures, swallowed interrupts, coroutine cancellation treated as failure, and docs that contradict code. False-positive controls cover desugaring, Compat helpers, and guarded callers. Co-Authored-By: Claude Opus 5.5 --- .../src/builtin-skills/code-review/SKILL.md | 1 + .../src/builtin-skills/code-review/SOURCES.md | 6 +- .../src/builtin-skills/code-review/SPEC.md | 5 +- .../references/java-kotlin-android.md | 90 +++++++++++++++++++ packages/warden/src/package.test.ts | 1 + 5 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 packages/warden/src/builtin-skills/code-review/references/java-kotlin-android.md diff --git a/packages/warden/src/builtin-skills/code-review/SKILL.md b/packages/warden/src/builtin-skills/code-review/SKILL.md index 444747aeb..c01fbdedc 100644 --- a/packages/warden/src/builtin-skills/code-review/SKILL.md +++ b/packages/warden/src/builtin-skills/code-review/SKILL.md @@ -15,6 +15,7 @@ Load only matching references: |-----------|-----------| | `references/javascript-typescript.md` | Reviewing JavaScript, TypeScript, Node, React, Next.js, or browser code | | `references/python.md` | Reviewing Python, Django, Flask, FastAPI, Celery, or Python service code | +| `references/java-kotlin-android.md` | Reviewing Java, Kotlin, Android, JVM library, or Kotlin coroutine code | | `references/github-workflows.md` | Reviewing GitHub Actions workflows, local actions, reusable workflows, or scripts and config loaded by workflows | ## Bugs Only Rule diff --git a/packages/warden/src/builtin-skills/code-review/SOURCES.md b/packages/warden/src/builtin-skills/code-review/SOURCES.md index 8535312ae..f2af1f907 100644 --- a/packages/warden/src/builtin-skills/code-review/SOURCES.md +++ b/packages/warden/src/builtin-skills/code-review/SOURCES.md @@ -8,6 +8,7 @@ | Local `architecture-review` and `code-simplifier` skills | Local prior art | Medium | Use boundaries to avoid overlap with style and architecture feedback. | Make exclusions explicit so code review reports only bugs. | | Common production correctness review failure modes | Engineering practice | Medium | Keep examples generic, transformed, and evidence-gated. | Cover logic, state, async, error handling, contracts, persistence, UI, build, and workflow bugs. | | Warden package skill loader and packaging tests | Repository behavior | High | Use for validation scope only. | Add tests that the new built-in skill resolves and is included in the npm package. | +| Cursor Bugbot findings on `getsentry/sentry-java` PRs, October to November 2026 | Public review feedback | Medium | Use only the generalized bug classes; do not encode SDK-specific conventions. | Add a Java/Kotlin/Android reference for the generic bugs `code-review` missed: service binding and descriptor leaks, API-level guards, clocks, old optional dependencies, main-thread and `WebView` affinity, executor and interrupt handling, coroutine cancellation, and docs that contradict code. | | GitHub issue #317 severity feedback | Maintainer issue feedback | High | Use only the generalized severity lesson; do not encode repo-specific private context. | Score tests, golden files, and config bugs by production blast radius when they hide or authorize shipped breakage. | ## Coverage Matrix @@ -18,7 +19,7 @@ | Reachability and reproducibility evidence | Complete | Findings must prove the changed path is reachable and the failure is triggered by a specific input, state, ordering, or configuration. | | False-positive controls | Complete | Exclusions block style, architecture, maintainability, security, performance-only, test-coverage-only, and pattern-only findings. | | Severity and confidence calibration | Complete | Severity is tied to user-visible or operational impact, including high-impact public discovery/config breakage, with lower severity for unproven preconditions. | -| Language and workflow caveats | Complete for initial scope | References cover JS/TS, Python, and GitHub Actions workflow correctness. Other languages use the core contract until repeated examples justify references. | +| Language and workflow caveats | Complete for initial scope | References cover JS/TS, Python, Java/Kotlin/Android, and GitHub Actions workflow correctness. Other languages use the core contract until repeated examples justify references. | ## Source-Backed Decisions @@ -37,6 +38,9 @@ 5. Tests and golden files inherit severity from the shipped behavior they protect. - Reason: a changed test can lock in broken output for a public route or config surface while looking like a low-impact test-only edit. - Decision: do not automatically classify test/tooling findings as low when they mask or authorize high-impact production breakage. +6. Java, Kotlin, and Android need their own reference. + - Reason: a backtest on sentry-java PRs found `code-review` caught 1 of 15 generic bugs Bugbot found on the same commit. Most misses were platform behavior the core contract does not name, such as API-level guards, lifecycle pairing, and clock choice. + - Decision: add `references/java-kotlin-android.md` with those bug classes and false-positive controls for desugaring, `*Compat` helpers, and guarded callers. ## Open Gaps diff --git a/packages/warden/src/builtin-skills/code-review/SPEC.md b/packages/warden/src/builtin-skills/code-review/SPEC.md index dce30bd24..b3c1fada8 100644 --- a/packages/warden/src/builtin-skills/code-review/SPEC.md +++ b/packages/warden/src/builtin-skills/code-review/SPEC.md @@ -13,7 +13,7 @@ In scope: - Logic, state, async, data contract, persistence, edge-case, API, public metadata/config, UI, build, test, and workflow correctness bugs. - Changed production code, user entry points, public APIs, shipped workflows, and tests that can mask shipped regressions. - General bug-finding guidance that applies across application code. -- Focused notes for JavaScript/TypeScript, Python, and GitHub Actions workflow correctness. +- Focused notes for JavaScript/TypeScript, Python, Java/Kotlin/Android, and GitHub Actions workflow correctness. Out of scope: @@ -45,6 +45,7 @@ Out of scope: - Expected bundled files loaded at runtime: - `references/javascript-typescript.md` for JS/TS/Node/React/Next/browser correctness. - `references/python.md` for Python/Django/Flask/FastAPI/Celery correctness. + - `references/java-kotlin-android.md` for Java/Kotlin/Android/JVM and coroutine correctness. - `references/github-workflows.md` for GitHub Actions workflow correctness. ## Source And Evidence Model @@ -100,7 +101,7 @@ Data that must not be stored: ## Known Limitations - The skill cannot prove bugs that require running complex integration environments unless the code path itself is sufficient evidence. -- Language coverage is intentionally strongest for JS/TS, Python, and GitHub Actions workflows. +- Language coverage is intentionally strongest for JS/TS, Python, Java/Kotlin/Android, and GitHub Actions workflows. - It may miss domain-specific business-rule bugs when the changed code does not expose the business contract. ## Maintenance Notes diff --git a/packages/warden/src/builtin-skills/code-review/references/java-kotlin-android.md b/packages/warden/src/builtin-skills/code-review/references/java-kotlin-android.md new file mode 100644 index 000000000..012391722 --- /dev/null +++ b/packages/warden/src/builtin-skills/code-review/references/java-kotlin-android.md @@ -0,0 +1,90 @@ +# Java, Kotlin, And Android Bug Review Notes + +Use this when reviewing Java, Kotlin, Android, JVM library, or Kotlin coroutine code. These notes refine the core `code-review` skill; they do not add style, architecture, security, or performance-only scope. + +## Runtime Boundaries + +- Android code runs on every API level from `minSdk` up. Read `minSdk` and the `Build.VERSION.SDK_INT` checks on the path before deciding which levels reach a call. `@SuppressLint("NewApi")` and `@TargetApi` silence lint; they add no runtime check. +- The JVM loads classes lazily. A type that is missing at runtime fails with `NoClassDefFoundError`, `NoSuchMethodError`, or another `LinkageError` when its class is first loaded or the call is first linked. That can be far from the guarded call, for example when a field, interface, or lambda target uses the type. +- `compileOnly` and optional dependencies may be absent at runtime, or older than the version compiled against. A class-presence check proves the class exists, not that a newer method or type does. +- Threading is part of an API's contract. Views, `WebView`, and many framework callbacks belong to one thread. The thread a callback runs on can depend on the API level and the overload, so read the docs for the level the code runs on. +- An Android app can run in several processes. `Application.onCreate` runs in each, and a service in its own `android:process` starts without the main process's setup. +- Kotlin null safety ends at Java boundaries. Platform types, reflection, deserialized objects, and `lateinit` properties can still be null or uninitialized at runtime. + +## High-Signal Patterns + +| Pattern | Bug Shape | Safer Shape | +|---------|-----------|-------------| +| Missing version guard | A method, overload, class, or interface needs a higher API level than `minSdk` and is reached without an `SDK_INT` check, so older devices crash. | Guard with `SDK_INT` and keep newer-API types in a class that is loaded only behind the guard. | +| API-level behavior change | The same call returns different data, uses a different default, or calls back on a different thread on older levels, and the code assumes the newer behavior. | Handle each level the code supports, or raise the guard. | +| Old optional dependency | A class-presence check passes, then the code calls a method or type that only newer versions of the dependency have. | Catch `LinkageError` around the optional call, or check for the specific member. | +| Unpaired register and unregister | `bindService`, `registerReceiver`, network callbacks, listeners, or observers have an error, timeout, or close path that skips the matching unbind, or unbinds twice and throws `IllegalArgumentException`. | Pair each register with exactly one unregister on every exit path, and track bound state atomically. | +| Leaked descriptors and closeables | `ParcelFileDescriptor`, `Cursor`, streams, HTTP response bodies, or sockets stay open on early return, exception, timeout, or when ownership was never handed off. | Use try-with-resources or `use`, and close in the path where the handoff fails. | +| Work after lifecycle end | A posted or delayed task runs after `onStop`, `onDestroy`, or `close` and attaches a listener to a destroyed `Window`, touches a destroyed `WebView`, or restarts stopped work. | Recheck current state on the thread that does the work. | +| Retained Android objects | A static, singleton, or process-lifetime field holds an `Activity`, `View`, `Window`, or non-application `Context` past destruction on a reachable path. | Hold the application context or a weak reference, and clear it on every teardown path. | +| Blocked main thread | `Future.get`, `await`, `sleep`, binder calls, disk, or network run on the main thread, or under a lock that main-thread code also takes. Waiting on a callback that is delivered to the waiting thread deadlocks. | Move the wait off the main thread and release locks before IPC. | +| Wrong clock | Wall-clock time (`currentTimeMillis`, `Date`, `Instant.now()`) drives a timeout, deadline, or duration, so clock changes shorten or stretch it. On Android, `elapsedRealtime` counts deep sleep and `uptimeMillis` does not, so swapping them changes hang and timeout results after the device sleeps. | Use a monotonic clock that matches whether sleep should count. For related timestamps, read the wall clock once and add monotonic offsets. | +| Lost executor failures | A `Future` from `submit` is never read, so its exception vanishes. A periodic task stops repeating after one throw. `shutdownNow` drops queued tasks, including cleanup the caller relies on. | Handle errors inside the task, read the future, or run required cleanup inline when the task cannot run. | +| Swallowed interrupt | `InterruptedException` is caught without restoring the interrupt flag or exiting, so the caller's cancellation is lost. | Call `Thread.currentThread().interrupt()` or rethrow. | +| Cancellation as failure | `catch (e: Exception)`, `catch (e: Throwable)`, or `runCatching` around a suspend call catches `CancellationException`, so normal cancellation is reported or handled as an error and the coroutine keeps running. | Rethrow `CancellationException`, or catch only the specific failures. | +| Unsafe shared state | Plain fields are written on one thread and read on another, for example during init and close, or a check-then-act on a concurrent map races. | Use `volatile`, atomics, a lock, or atomic map operations. | +| Docs that contradict code | Javadoc or KDoc on a published API promises nullability, thread, units, defaults, or thrown exceptions that the code does not deliver, and callers rely on the doc. | Fix the side that is wrong. | + +## False-Positive Controls + +- A caller's `SDK_INT` check, `@RequiresApi` on a method whose callers are all guarded, or a `minSdk` at or above the required level makes a call safe. AndroidX `*Compat` helpers already guard internally. +- D8 and R8 desugaring backport some Java APIs, such as lambdas, try-with-resources, and `java.time` with core library desugaring. Check the build config before reporting a missing Java API. +- try-with-resources and Kotlin `use` close on every path. A descriptor passed to `detachFd` or adopted by another owner no longer needs closing. +- A discarded `Future` is safe when the task handles all of its own failures. +- A wall-clock value is safe when it is only recorded or sent as a timestamp, never subtracted or compared as a deadline. +- Code is not on the main thread unless the path proves it. Check `@WorkerThread`, the executor, and callers. +- Catching `CancellationException` first and rethrowing it, or calling `ensureActive()`, keeps cancellation intact. +- Doc findings need a published API and a caller that would break by following the doc. Wording, typos, and missing docs are not findings. + +## Minimal Examples + +**Report: missing version guard** + +```java +// minSdk 24 +connectivityManager.registerDefaultNetworkCallback(callback, handler); +``` + +The `Handler` overload is API 26, so API 24 and 25 devices crash with `NoSuchMethodError`. + +**Report: bind leaked on a failure path** + +```java +if (!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { + return false; +} +if (!configureService()) { + return false; +} +``` + +When configuration fails, the connection stays bound and keeps the service process alive for the app's lifetime. + +**Report: cancellation treated as failure** + +```kotlin +try { + upload(file) +} catch (e: Exception) { + markFailed(file) +} +``` + +When the scope is cancelled, `upload` throws `CancellationException`, so a normal shutdown marks the file failed. + +**Do not report: guarded overload** + +```java +if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + connectivityManager.registerDefaultNetworkCallback(callback, handler); +} else { + connectivityManager.registerDefaultNetworkCallback(callback); +} +``` + +The API 26 overload only runs on API 26 and higher. diff --git a/packages/warden/src/package.test.ts b/packages/warden/src/package.test.ts index 32d622607..e02fa38f7 100644 --- a/packages/warden/src/package.test.ts +++ b/packages/warden/src/package.test.ts @@ -40,6 +40,7 @@ describe('npm package contents', () => { expect(ignored.ignores('src/builtin-skills/code-review/references/javascript-typescript.md')).toBe(false); expect(ignored.ignores('src/builtin-skills/code-review/references/github-workflows.md')).toBe(false); expect(ignored.ignores('src/builtin-skills/code-review/references/python.md')).toBe(false); + expect(ignored.ignores('src/builtin-skills/code-review/references/java-kotlin-android.md')).toBe(false); expect(ignored.ignores('src/builtin-skills/integrity-review/SKILL.md')).toBe(false); expect(ignored.ignores('src/builtin-skills/integrity-review/SPEC.md')).toBe(false); expect(ignored.ignores('src/builtin-skills/integrity-review/SOURCES.md')).toBe(false);