Modern Apps git

← Modern-Apps.git

lint-comment-sweep-warn-then-error

Commit
9cd53f7c75dc3275bc7b7831f5fdedd72b172d73
Author
vayun-mathur <[email protected]>
When
2026-10-15 21:09 UTC (1 month ago)
Parents
f8da98d

Diff

.editorconfig
diff --git a/.editorconfig b/.editorconfignew file mode 100644index 0000000000..61ab964d4b--- /dev/null+++ b/.editorconfig@@ -0,0 +1,23 @@+root = true++[*]+end_of_line = lf+charset = utf-8+trim_trailing_whitespace = true+insert_final_newline = true++[*.{kt,kts}]+indent_style = space+indent_size = 4+max_line_length = 120++[*.{rs,toml}]+indent_style = space+indent_size = 4++[*.{xml,gradle}]+indent_style = space+indent_size = 4++[Makefile]+indent_style = tab
AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex 3255640e10..81887abfa5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -41,7 +41,7 @@ Monorepo: ~100 Gradle modules + Rust workspace. Do scoped work only. | aosp-stubs | `library/aosp-stubs/` | compile-only hidden-API stubs | | sdk:games/cast/openassistant | `sdk/games/`, `sdk/cast/`, `sdk/openassistant/` | achievements / casting / assistant tools | | build-logic | `build-logic/` | `common-conventions-app`, `launcherIcon`, `rustNativeLib` |-| lint-rules | `lint-rules/` | ToastUsage + DirectComposeAnimation (fatal) + 6 advisory |+| lint-rules | `lint-rules/` | ToastUsage + DirectComposeAnimation + FileLength + DirectAndroidLog (fatal) + 9 advisory |  ### Apps (Gradle key → dir) Reference: `backup/` satisfies every rule; `notes/` second + `intents/` demo. `camera` + `games/voxels` hand-commit screenshots.@@ -102,7 +102,7 @@ Rules: `dev` default, `release` only when asked, `debug` blocked. Never uninstal ``` Never grep repo-wide when a filter will do. Always excluded: `target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/ *.log *.onnx metadata_data/photos/`. -`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `cargo check --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir):+`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `:<module>:lint` + `cargo check/clippy/fmt/doc --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir; fmt is advisory-only until the tree is fmt-clean): ``` ./check <module> [...]   # e.g. ./check notes backup; ./check voxels ./check all              # every app + library module (pure-JVM modules excluded)
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex bea020c1db..fd83498e9d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -83,12 +83,32 @@ unused_extern_crates = "deny" unused_import_braces = "deny" unused_results = "deny" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(fuzzing)', 'cfg(rust_analyzer)', 'cfg(blaze)'] }+# Lint sweep (warn-then-error): rustdoc link/tag hygiene lands as warnings+# first, promotes to deny with the rest of the comment sweep at promotion.+# (Table is `workspace.lints.rustdoc`, not dotted keys under `rust` — cargo+# rejects `lints.rust.rustdoc::X` as an invalid lint name.)+[workspace.lints.rustdoc]+broken_intra_doc_links = "warn"+invalid_html_tags = "warn"  [workspace.lints.clippy] expect_used = "deny" indexing_slicing = "deny" panic = "deny" unwrap_used = "deny"+# Lint sweep (warn-then-error): catches TODO!/unimplemented!/dbg! left in the+# tree plus doc-comment drift; promotes to deny at promotion.+todo = "warn"+dbg_macro = "warn"+empty_line_after_doc_comments = "warn"+doc_markdown = "warn"+# Lint sweep: conservative warn set. missing_panics_doc keeps `# Panics`+# sections honest on public fns; needless_borrow and len_without_is_empty are+# mechanical. All promote to deny at promotion once the inheriting slices are+# green. Existing deny set above is unchanged.+missing_panics_doc = "warn"+needless_borrow = "warn"+len_without_is_empty = "warn"  # Centralized Rust versions – armv8-only (aarch64-linux-android) 
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex def750c84a..33949a0f28 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -143,6 +143,8 @@ configure<com.android.build.api.dsl.ApplicationExtension> {         disable += listOf("MissingTranslation")         // Advisory: reported by `./gradlew lint`, never blocking. Each of these is Error         // (ExtraTranslation is Fatal) by default and has a pre-existing backlog.+        // Lint sweep (warn-then-error): the three comment detectors land here+        // as warnings; they promote to fatal with the rest at promotion.         warning += listOf(             "HardcodedText",             // Repo rules from :lint-rules. Only the three gates below are not advisory.@@ -151,6 +153,9 @@ configure<com.android.build.api.dsl.ApplicationExtension> {             "PackageStructure",             "RawScaffoldInApp",             "Room2Usage",+            "ExceptionMarkerFormat",+            "TodoEvasion",+            "CommentedOutCode",             // Built-in checks.             "ContextCastToActivity",             "ExtraTranslation",
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex 2325101273..ed8121bb3f 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -37,6 +37,9 @@ configure<com.android.build.api.dsl.LibraryExtension> {         // FileLength caps Kotlin file size, same as apps: split first.         // DirectAndroidLog keeps all logging on the repo facade.         fatal += listOf("ToastUsage", "FileLength", "DirectAndroidLog")+        // Lint sweep (warn-then-error): mirror the app warnings so+        // library modules surface marker-shape drift without failing the build.+        warning += listOf("ExceptionMarkerFormat", "TodoEvasion", "CommentedOutCode")     } } 
build-logic/src/main/kotlin/common-conventions-wear.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts b/build-logic/src/main/kotlin/common-conventions-wear.gradle.ktsindex 2daf49a610..87a1c8ac3d 100644--- a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts@@ -7,6 +7,12 @@ plugins {     id("com.google.devtools.ksp") } +// Lint-sweep decision (warn-then-error rollout): this convention is+// intentionally NOT wired to detekt or :lint-rules. No module applies it+// (settings.gradle.kts has no wear consumers), so there is no slice to keep+// green. If a wear module lands, wire `dev.detekt` + the app lint block at+// warning parity with common-conventions-app before its first commit.+ val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()  fun readVersionInfo(): Pair<Int, String> {
check
diff --git a/check b/checkindex d90a426e08..ca78a96ac3 100644--- a/check+++ b/check@@ -1,9 +1,9 @@ #!/usr/bin/env bash # Static verification without building or installing:-#   ./gradlew :<mod>:detekt [...] + cargo check --locked -p <crate> [...] (rust modules only)+#   ./gradlew :<mod>:detekt :<mod>:lint [...] + cargo check/clippy/fmt/doc (rust modules only) # # Usage:-#   ./check <module> [module...]     # detekt (detekt.yml) + cargo check+#   ./check <module> [module...]     # detekt (detekt.yml) + lint + cargo check/clippy/fmt/doc #   ./check games/voxels maps        # multi-module, one gradlew invocation #   ./check voxels                    # shorthand -> games:voxels (same as ./install) #   ./check all                       # every app + library module@@ -16,7 +16,11 @@ # --locked`: workspace members together via `-p` from the repo root, standalone # crates (own [workspace]) individually in their own dir (host target: fast smoke # check; the real aarch64 cross-build runs inside the Gradle build via-# cargoNdkBuild). No rust modules -> cargo step skipped.+# cargoNdkBuild). Lint-sweep Phase 4 adds, per in-scope crate: `cargo clippy+# --locked --all-targets` (blocking on deny/error lints; warnings never fail),+# `cargo fmt --check` (advisory report only until the tree is fmt-clean, then+# it promotes to blocking), and `cargo doc --locked --no-deps` (blocking on+# rustdoc errors). No rust modules -> cargo steps skipped. set -euo pipefail  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -83,7 +87,10 @@ done [[ ${#MODS[@]} -gt 0 ]] || { echo "Error: no valid modules." >&2; exit 1; }  TASKS=()-for mod in "${MODS[@]}"; do TASKS+=(":$(echo "$mod" | tr '/' ':'):detekt"); done+for mod in "${MODS[@]}"; do+  gmod="$(echo "$mod" | tr '/' ':')"+  TASKS+=(":$gmod:detekt" ":$gmod:lint")+done echo "Modules (${#MODS[@]}): ${MODS[*]}" echo "Gradle tasks: ${TASKS[*]}" echo ""@@ -91,7 +98,7 @@ echo "" DETEKT_RC=0 "$SCRIPT_DIR/gradlew" "${TASKS[@]}" --continue --console=plain || DETEKT_RC=$? echo ""-[[ $DETEKT_RC -ne 0 ]] && echo "Warning: detekt reported failures (exit $DETEKT_RC)."+[[ $DETEKT_RC -ne 0 ]] && echo "Warning: detekt/lint reported failures (exit $DETEKT_RC)."  # --- cargo check (rust modules only) --- # Workspace members share one root `cargo check -p ...` invocation; standalone@@ -133,9 +140,73 @@ for rdir in ${STANDALONE_DIRS[@]:-}; do   ( cd "$rdir" && "$CARGO_BIN" check --locked ) || CARGO_RC=$?   [[ $CARGO_RC -ne 0 ]] && echo "Warning: cargo check ($rdir) reported failures (exit $CARGO_RC)." done+# --- cargo clippy (rust modules only, lint-sweep Phase 4) ---+# Same scope as cargo check. Each crate's own `[lints]` table governs severity,+# so warnings never fail this step; only deny/error lints do. Runs with+# --all-targets so tests/examples/benches are covered too.+CLIPPY_RC=0+if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+  echo ""+  CLIPPY_ARGS=()+  for c in "${ROOT_CRATES[@]}"; do CLIPPY_ARGS+=(-p "$c"); done+  echo "Running: cargo clippy --locked ${CLIPPY_ARGS[*]} --all-targets"+  ( cd "$ROOT" && "$CARGO_BIN" clippy --locked "${CLIPPY_ARGS[@]}" --all-targets ) || CLIPPY_RC=$?+  [[ $CLIPPY_RC -ne 0 ]] && echo "Warning: cargo clippy (workspace) reported failures (exit $CLIPPY_RC)."+fi+for rdir in ${STANDALONE_DIRS[@]:-}; do+  echo ""+  echo "Running: cargo clippy --locked --all-targets (in $rdir)"+  ( cd "$rdir" && "$CARGO_BIN" clippy --locked --all-targets ) || CLIPPY_RC=$?+  [[ $CLIPPY_RC -ne 0 ]] && echo "Warning: cargo clippy ($rdir) reported failures (exit $CLIPPY_RC)."+done+# --- cargo fmt (advisory only, lint-sweep Phase 4) ---+# The tree carries fmt drift today, so this step reports but never fails.+# Promotes to blocking once `cargo fmt --check` is clean on the owning slice.+if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+  echo ""+  FMT_ARGS=()+  for c in "${ROOT_CRATES[@]}"; do FMT_ARGS+=(-p "$c"); done+  echo "Running: cargo fmt --check ${FMT_ARGS[*]} (advisory)"+  FMT_OUT="$(cd "$ROOT" && "$CARGO_BIN" fmt --check "${FMT_ARGS[@]}" 2>&1)" || true+  FMT_COUNT="$(echo "$FMT_OUT" | grep -c '^Diff in' || true)"+  if [[ "$FMT_COUNT" -gt 0 ]]; then+    echo "rustfmt drift: $FMT_COUNT hunks in scope (advisory; run cargo fmt -p <crate> to clean)."+  else+    echo "rustfmt: clean."+  fi+fi+for rdir in ${STANDALONE_DIRS[@]:-}; do+  echo ""+  echo "Running: cargo fmt --check (in $rdir, advisory)"+  FMT_OUT="$(cd "$rdir" && "$CARGO_BIN" fmt --check 2>&1)" || true+  FMT_COUNT="$(echo "$FMT_OUT" | grep -c '^Diff in' || true)"+  if [[ "$FMT_COUNT" -gt 0 ]]; then+    echo "rustfmt drift: $FMT_COUNT hunks in $rdir (advisory)."+  else+    echo "rustfmt: clean ($rdir)."+  fi+done+# --- cargo doc (rust modules only, lint-sweep Phase 4) ---+# Catches rustdoc::broken_intra_doc_links / invalid_html_tags. Both land as+# warnings first (warn-then-error), so this fails only on rustdoc errors.+DOC_RC=0+if [[ ${#ROOT_CRATES[@]} -gt 0 ]]; then+  echo ""+  DOC_ARGS=()+  for c in "${ROOT_CRATES[@]}"; do DOC_ARGS+=(-p "$c"); done+  echo "Running: cargo doc --locked --no-deps ${DOC_ARGS[*]}"+  ( cd "$ROOT" && "$CARGO_BIN" doc --locked --no-deps "${DOC_ARGS[@]}" ) || DOC_RC=$?+  [[ $DOC_RC -ne 0 ]] && echo "Warning: cargo doc (workspace) reported failures (exit $DOC_RC)."+fi+for rdir in ${STANDALONE_DIRS[@]:-}; do+  echo ""+  echo "Running: cargo doc --locked --no-deps (in $rdir)"+  ( cd "$rdir" && "$CARGO_BIN" doc --locked --no-deps ) || DOC_RC=$?+  [[ $DOC_RC -ne 0 ]] && echo "Warning: cargo doc ($rdir) reported failures (exit $DOC_RC)."+done if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 ]]; then-  echo "No Rust crates in scope; cargo step skipped."+  echo "No Rust crates in scope; cargo steps skipped." fi -if [[ $DETEKT_RC -ne 0 || $CARGO_RC -ne 0 ]]; then exit 1; fi+if [[ $DETEKT_RC -ne 0 || $CARGO_RC -ne 0 || $CLIPPY_RC -ne 0 || $DOC_RC -ne 0 ]]; then exit 1; fi exit 0
check.bat
diff --git a/check.bat b/check.batindex 4434471e11..c39f10f484 100644--- a/check.bat+++ b/check.bat@@ -8,7 +8,7 @@ exit /b %errorlevel% : end batch #> # check.bat - Static verification without building or installing. # (PowerShell twin of ./check.)-#   check.bat <module> [module...]     # detekt + cargo check+#   check.bat <module> [module...]     # detekt + lint + cargo check/clippy/fmt/doc #   check.bat games/voxels maps        # multi-module, one gradlew invocation #   check.bat voxels                    # shorthand -> games:voxels (same as install.bat) #   check.bat all                       # every app + library module@@ -21,7 +21,11 @@ exit /b %errorlevel% # --locked`: workspace members together via `-p` from the repo root, standalone # crates (own [workspace]) individually in their own dir (host target: fast smoke # check; the real aarch64 cross-build runs inside the Gradle build via-# cargoNdkBuild). No rust modules -> cargo step skipped.+# cargoNdkBuild). Lint-sweep Phase 4 adds, per in-scope crate: `cargo clippy+# --locked --all-targets` (blocking on deny/error lints; warnings never fail),+# `cargo fmt --check` (advisory report only until the tree is fmt-clean), and+# `cargo doc --locked --no-deps` (blocking on rustdoc errors). No rust modules+# -> cargo steps skipped. $ErrorActionPreference = 'Stop'  $CheckRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }@@ -29,7 +33,7 @@ $CheckRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd(' function Show-CheckHelp {   @' Usage:-  check.bat <module> [module...]     # detekt (config/detekt/detekt.yml) + cargo check+  check.bat <module> [module...]     # detekt (detekt.yml) + lint + cargo check/clippy/fmt/doc   check.bat games/voxels maps        # multi-module, one gradlew invocation   check.bat voxels                    # shorthand -> games:voxels (same as install.bat)   check.bat all                       # every app + library module@@ -42,7 +46,10 @@ Rust: a module with src/main/rust/Cargo.toml is checked with `cargo check --locked`: workspace members together via `-p` from the repo root, standalone crates (own [workspace]) individually in their own dir (host target: fast smoke check; the real aarch64 cross-build runs inside the Gradle build via-cargoNdkBuild). No rust modules -> cargo step skipped.+cargoNdkBuild). Lint-sweep Phase 4 adds, per in-scope crate: `cargo clippy+--locked --all-targets` (blocking on deny/error lints), `cargo fmt --check`+(advisory until the tree is fmt-clean), `cargo doc --locked --no-deps`.+No rust modules -> cargo steps skipped. '@ } @@ -136,7 +143,9 @@ if ($CheckMods.Count -eq 0) {  $CheckTasks = @() foreach ($CheckMod in $CheckMods) {-  $CheckTasks += ":$($CheckMod.Replace('/', ':')):detekt"+  $CheckGmod = $CheckMod.Replace('/', ':')+  $CheckTasks += ":${CheckGmod}:detekt"+  $CheckTasks += ":${CheckGmod}:lint" } Write-Output "Modules ($($CheckMods.Count)): $($CheckMods -join ' ')" Write-Output "Gradle tasks: $($CheckTasks -join ' ')"@@ -166,7 +175,7 @@ else {   exit 1 } Write-Output ''-if ($CheckDetektRc -ne 0) { Write-Output "Warning: detekt reported failures (exit $CheckDetektRc)." }+if ($CheckDetektRc -ne 0) { Write-Output "Warning: detekt/lint reported failures (exit $CheckDetektRc)." }  # --- cargo check (rust modules only) --- # Workspace members share one root `cargo check -p ...` invocation; standalone
clippy.toml
diff --git a/clippy.toml b/clippy.tomlnew file mode 100644index 0000000000..1be16e0494--- /dev/null+++ b/clippy.toml@@ -0,0 +1,10 @@+# Clippy foundations (Phase 1 — advisory, warn-then-error rollout).+# Public-API posture: docs required on public items only, so breaking-change+# lints stay off until Phase 3 inheritance rollout is green.+msrv = "1.85.0"+avoid-breaking-exported-api = false++# Test modules get scoped allows (not crate-wide) once workspace inheritance+# rolls out — see plan Phase 3. Documented here so `allow-unwrap-in-tests`+# stays an explicit per-module decision, not a silent global.+# allow-unwrap-in-tests = false
detekt.yml
diff --git a/detekt.yml b/detekt.ymlindex 88de3014b1..b2e58cf680 100644--- a/detekt.yml+++ b/detekt.yml@@ -1,3 +1,9 @@+# Lint rollout policy: warn-then-error.+# New or tightened rules land as `warning` (detekt / Android Lint) / `warn`+# (Rust) first, are cleaned per module, then promote to error/fatal/deny.+# Never flip warningsAsErrors / abortOnError globally before the owning+# slice is green. Base marker ban (FIXME:/STOPSHIP:/TODO:) stays blocking;+# new marker shapes (HACK:/XXX:, evasions) land warning-first. config:   validation: true   warningsAsErrors: false@@ -54,8 +60,14 @@ comments:     matchDeclarationsOrder: true     allowParamOnConstructorProperties: false     exhaustive: true+  # Lint-sweep trial (warn-then-error): public classes and functions+  # need KDoc at warning severity. Public-API-only posture: private/internal+  # stay exempt (detekt only reports public API for these rules), tests stay+  # excluded below. Promotes to error once the owning slices are green;+  # UndocumentedPublicProperty stays off until then.   UndocumentedPublicClass:-    active: false+    active: true+    severity: warning     excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']     searchInNestedClass: true     searchInInnerClass: true@@ -650,6 +662,15 @@ style:         value: 'STOPSHIP:'       - reason: 'Forbidden TODO todo marker in comment, please do the changes.'         value: 'TODO:'+      # Warn-then-error extension: HACK:/XXX: land as detekt findings+      # alongside the TodoEvasion lint check, then join the hard ban at promotion.+      # Evasion shapes (TODO(scope):, bare banners) are covered by the+      # TodoEvasionDetector lint rule, which sees comment PSI that detekt's+      # exact-substring match cannot express.+      - reason: 'Forbidden HACK marker in comment, please fix the problem instead of working around it.'+        value: 'HACK:'+      - reason: 'Forbidden XXX marker in comment, please fix the problem instead of marking it.'+        value: 'XXX:'     allowedPatterns: ''   ForbiddenImport:     active: false
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex 6eb076af7e..fe5305d986 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -208,5 +208,3 @@ pub fn globe_lonlat(center_lon: f64, center_lat: f64, x: f64, y: f64, z: f64) ->     let lon = ((lon + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;     (lon, lat.clamp(-90.0, 90.0)) }--// device-verifier: mtime bump to force cargo recompile (no semantic change)
lint-rules/src/main/java/com/vayunmathur/lint/CommentOnlyMatcher.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/CommentOnlyMatcher.kt b/lint-rules/src/main/java/com/vayunmathur/lint/CommentOnlyMatcher.ktnew file mode 100644index 0000000000..8b3d8098e7--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/CommentOnlyMatcher.kt@@ -0,0 +1,52 @@+package com.vayunmathur.lint++import com.intellij.openapi.util.TextRange+import com.intellij.psi.PsiComment+import com.intellij.psi.PsiRecursiveElementVisitor+import org.jetbrains.kotlin.psi.KtFile++/**+ * Shared comment-only matching for marker-based detectors.+ *+ * Several detectors historically used whole-file `KtFile.text.contains(MARKER)`,+ * which cannot tell a marker inside a `//` comment from the same text inside a+ * string literal — a string containing e.g. `"// TOAST EXCEPTION:"` would+ * silently opt the file out. All marker checks must go through here so they+ * only look at PSI comment elements.+ *+ * KDoc is covered: in the Kotlin PSI it surfaces as a [PsiComment] subtype,+ * so a single [PsiComment] walk sees `//`, block comments, and KDoc alike.+ */+object CommentOnlyMatcher {++    /**+     * All comment elements in [file] in source order.+     */+    fun commentsIn(file: KtFile): List<PsiComment> {+        val out = mutableListOf<PsiComment>()+        file.accept(+            object : PsiRecursiveElementVisitor() {+                override fun visitComment(comment: PsiComment) {+                    super.visitComment(comment)+                    out.add(comment)+                }+            },+        )+        return out+    }++    /**+     * Text ranges of every comment in [file], for offset-in-comment checks+     * (e.g. skipping `androidx.room.` matches that live in KDoc).+     */+    fun commentRangesIn(file: KtFile): List<TextRange> =+        commentsIn(file).map { it.textRange }++    /** True if any comment in [file] contains [marker] verbatim. */+    fun containsMarkerInComments(file: KtFile, marker: String): Boolean =+        commentsIn(file).any { it.text.contains(marker) }++    /** True if [offset] falls inside any of [ranges]. */+    fun isInRanges(offset: Int, ranges: List<TextRange>): Boolean =+        ranges.any { it.startOffset <= offset && offset < it.endOffset }+}
lint-rules/src/main/java/com/vayunmathur/lint/CommentedOutCodeDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/CommentedOutCodeDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/CommentedOutCodeDetector.ktnew file mode 100644index 0000000000..dc9629d0aa--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/CommentedOutCodeDetector.kt@@ -0,0 +1,187 @@+package com.vayunmathur.lint++import com.android.tools.lint.client.api.UElementHandler+import com.android.tools.lint.detector.api.Category+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Implementation+import com.android.tools.lint.detector.api.Issue+import com.android.tools.lint.detector.api.JavaContext+import com.android.tools.lint.detector.api.Location+import com.android.tools.lint.detector.api.Scope+import com.android.tools.lint.detector.api.Severity+import com.android.tools.lint.detector.api.SourceCodeScanner+import com.intellij.psi.PsiComment+import org.jetbrains.kotlin.psi.KtFile+import org.jetbrains.uast.UElement+import org.jetbrains.uast.UFile+import java.io.File++/**+ * Flags commented-out Kotlin code.+ *+ * The tree is clean today but nothing enforces it, and version control makes+ * commented-out code pure noise: stale copies rot, readers cannot tell whether+ * the block is load-bearing documentation or a revert waiting to happen, and+ * the history already keeps the old shape. Delete it; the commit that removed+ * it is the backup.+ *+ * Heuristic: a `//` comment line whose body parses as the start of a Kotlin+ * declaration or statement (val/var/fun/class/import/return/assignment/call).+ * Two or more consecutive matching lines report once on the run. Single+ * illustrative lines (e.g. `// e.g. foo.bar()`) stay silent, as do KDoc,+ * block comments, section banners, and the repo's own exception markers.+ *+ * Comment-only via [CommentOnlyMatcher]: string literals are never scanned.+ *+ * Warn-then-error: WARNING now (zero-today baseline), promote once green.+ */+class CommentedOutCodeDetector : Detector(), SourceCodeScanner {++    override fun getApplicableUastTypes(): List<Class<out UElement>> =+        listOf(UFile::class.java)++    override fun createUastHandler(context: JavaContext): UElementHandler =+        object : UElementHandler() {+            override fun visitFile(node: UFile) {+                val packageName = node.packageName+                if (packageName.isEmpty()) return+                if (!packageName.startsWith("com.vayunmathur.")) return+                if (LintPackageExclusions.isExcluded(packageName)) return+                val ktFile = node.sourcePsi as? KtFile ?: return+                val source = ktFile.text+                val file = context.file ?: return+                val comments = CommentOnlyMatcher.commentsIn(ktFile)+                var index = 0+                while (index < comments.size) {+                    val run = collectRun(source, comments, index)+                    if (run != null) {+                        val (start, length, count) = run+                        report(+                            context, node, file, source, start, length,+                            "Commented-out code ($count consecutive lines). Delete it — " ++                                "version control keeps the old shape, and stale copies rot. " ++                                "If the block documents intent, rewrite it as prose instead.",+                        )+                        index = runEnd(source, comments, index)+                    } else {+                        index+++                    }+                }+            }+        }++    /** Start/length/line-count of a commented-code run at [index], or null. */+    private fun collectRun(+        source: String,+        comments: List<PsiComment>,+        index: Int,+    ): Triple<Int, Int, Int>? {+        val first = comments[index]+        if (!isLineComment(first)) return null+        if (!looksLikeCode(stripSlashes(first.text))) return null+        var end = index+        while (end + 1 < comments.size) {+            val next = comments[end + 1]+            if (!isLineComment(next)) break+            if (!adjacentLine(source, comments[end], next)) break+            if (!looksLikeCode(stripSlashes(next.text))) break+            end+++        }+        if (end - index + 1 < MIN_RUN_LINES) return null+        val start = comments[index].textRange.startOffset+        val stop = comments[end].textRange.endOffset+        return Triple(start, stop - start, end - index + 1)+    }++    /** Index just past the run starting at [index]. */+    private fun runEnd(+        source: String,+        comments: List<PsiComment>,+        index: Int,+    ): Int {+        var end = index+        while (end + 1 < comments.size) {+            val next = comments[end + 1]+            if (!isLineComment(next)) break+            if (!adjacentLine(source, comments[end], next)) break+            if (!looksLikeCode(stripSlashes(next.text))) break+            end+++        }+        return end + 1+    }++    private fun isLineComment(comment: PsiComment): Boolean =+        comment.text.startsWith("//") && !comment.text.startsWith("///") && !comment.text.startsWith("//!")++    private fun stripSlashes(text: String): String =+        text.removePrefix("//").trimStart()++    private fun adjacentLine(+        source: String,+        prev: PsiComment,+        next: PsiComment,+    ): Boolean {+        val between = source.substring(prev.textRange.endOffset, next.textRange.startOffset)+        return ADJACENT_LINE.matches(between)+    }++    /** Heuristic: body reads as the start of a Kotlin declaration/statement. */+    private fun looksLikeCode(body: String): Boolean {+        if (body.isEmpty()) return false+        if (body.startsWith("----") || body.startsWith("====") || body.startsWith("****")) return false+        if (body.contains("EXCEPTION")) return false+        if (body.startsWith("e.g.") || body.startsWith("i.e.") || body.startsWith("see ")) return false+        return CODE_LIKE.any { it.containsMatchIn(body) }+    }++    private fun report(+        context: JavaContext,+        node: UFile,+        file: File,+        source: String,+        start: Int,+        length: Int,+        message: String,+    ) {+        context.report(+            ISSUE,+            node,+            Location.create(file, source, start, start + length),+            message,+        )+    }++    companion object {+        private const val MIN_RUN_LINES = 2++        /** Only whitespace and exactly one line break between adjacent `//` lines. */+        private val ADJACENT_LINE = Regex("^\\h*\\R\\h*$")++        private val CODE_LIKE = listOf(+            Regex("""^(val|var|fun|class|object|interface|enum|data|sealed|abstract|override|private|public|internal|protected|suspend|lateinit|const)\b"""),+            Regex("""^import\s+[\w.]+"""),+            Regex("""^return\b"""),+            Regex("""^[A-Za-z_][\w<>?]*\s*[:=]\s*\S"""),+            Regex("""^[A-Za-z_][\w.]*\s*\("""),+            Regex("""^\}\s*(else\b|catch\b|finally\b)?"""),+        )++        val ISSUE: Issue = Issue.create(+            id = "CommentedOutCode",+            briefDescription = "Commented-out code",+            explanation = """+                Commented-out code rots: readers cannot tell whether the block is \+                load-bearing documentation or a revert waiting to happen, and version \+                control already keeps the old shape. Delete the block — the commit that \+                removed it is the backup. If it documents intent, rewrite it as prose.+                """.trimIndent(),+            category = Category.PRODUCTIVITY,+            priority = 4,+            severity = Severity.WARNING,+            implementation = Implementation(+                CommentedOutCodeDetector::class.java,+                Scope.JAVA_FILE_SCOPE,+            ),+        )+    }+}
lint-rules/src/main/java/com/vayunmathur/lint/DirectComposeAnimationDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/DirectComposeAnimationDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/DirectComposeAnimationDetector.ktindex f21f80520e..3be0d120a2 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/DirectComposeAnimationDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/DirectComposeAnimationDetector.kt@@ -44,8 +44,9 @@ class DirectComposeAnimationDetector : Detector(), SourceCodeScanner {         if (isExemptPackage(packageName)) return null          // Documented per-file opt-out, matching the repo's other escape hatches.-        val fileText = (context.uastFile?.sourcePsi as? KtFile)?.text-        if (fileText != null && fileText.contains(EXCEPTION_MARKER)) return null+        // Comment-only: a marker inside a string literal must not opt the file out.+        val ktFile = context.uastFile?.sourcePsi as? KtFile+        if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return null          return object : UElementHandler() {             override fun visitImportStatement(node: UImportStatement) {
lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.ktnew file mode 100644index 0000000000..da60006952--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/ExceptionMarkerFormatDetector.kt@@ -0,0 +1,234 @@+package com.vayunmathur.lint++import com.android.tools.lint.client.api.UElementHandler+import com.android.tools.lint.detector.api.Category+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Implementation+import com.android.tools.lint.detector.api.Issue+import com.android.tools.lint.detector.api.JavaContext+import com.android.tools.lint.detector.api.Location+import com.android.tools.lint.detector.api.Scope+import com.android.tools.lint.detector.api.Severity+import com.android.tools.lint.detector.api.SourceCodeScanner+import com.intellij.psi.PsiComment+import org.jetbrains.kotlin.psi.KtFile+import org.jetbrains.uast.UElement+import org.jetbrains.uast.UFile+import java.io.File++/**+ * Validates the shape of the repo's per-file exception-marker comments.+ *+ * The markers are fail-closed: a typo'd marker or a missing colon silently does+ * NOT opt the file out, so enforcement disappears with no signal. This detector+ * catches the near-misses — `EXEPTION` typos, `TOAST EXCEPTION` without the+ * required colon, a `PACKAGE STRUCTURE EXCEPTION` that is not the verbatim JNI+ * form, and markers with no reason — while the owning detectors keep enforcing+ * the opt-out itself.+ *+ * Canonical shapes (kept in sync with the owning detectors):+ *  - `// PACKAGE STRUCTURE EXCEPTION (JNI)` verbatim+ *    (see [PackageStructureDetector]; real files may append `: <reason>`)+ *  - `// RAW SCAFFOLD EXCEPTION: <reason>` with a non-empty reason+ *  - `// TOAST EXCEPTION: <reason>` with colon and non-empty reason+ *    (see [ToastDetector])+ *  - `// RAW ANIMATION EXCEPTION: <reason>` with colon and non-empty reason+ *+ * A reason may continue on immediately following `//` lines, which the shared+ * scaffold/animation markers use for multi-line justifications.+ *+ * Comment-only via [CommentOnlyMatcher]: a marker inside a string literal must+ * neither opt a file out nor trip this check.+ *+ * Warn-then-error: WARNING now, promote to ERROR once the owning slices are+ * green (a bare `// RAW SCAFFOLD EXCEPTION` with no reason is the one known+ * live shape this will surface first).+ */+class ExceptionMarkerFormatDetector : Detector(), SourceCodeScanner {++    override fun getApplicableUastTypes(): List<Class<out UElement>> =+        listOf(UFile::class.java)++    override fun createUastHandler(context: JavaContext): UElementHandler =+        object : UElementHandler() {+            override fun visitFile(node: UFile) {+                val packageName = node.packageName+                if (packageName.isEmpty()) return+                if (!packageName.startsWith("com.vayunmathur.")) return+                // Rule-definition sources carry marker shapes in KDoc as examples+                // by necessity; scanning them would self-flag.+                if (isLintRulesPackage(packageName)) return+                val ktFile = node.sourcePsi as? KtFile ?: return+                val source = ktFile.text+                val file = context.file ?: return+                val comments = CommentOnlyMatcher.commentsIn(ktFile)+                comments.forEachIndexed { index, comment ->+                    checkComment(context, node, file, source, comments, index, comment)+                }+            }+        }++    private fun checkComment(+        context: JavaContext,+        node: UFile,+        file: File,+        source: String,+        comments: List<PsiComment>,+        index: Int,+        comment: PsiComment,+    ) {+        val text = comment.text+        val base = comment.textRange.startOffset++        if (text.contains(TYPO_KEYWORD)) {+            report(context, node, file, source, base + text.indexOf(TYPO_KEYWORD), TYPO_KEYWORD.length,+                "Typo'd exception marker (`EXEPTION`). No detector recognises this spelling, " ++                    "so the file is NOT opted out. Use one of the canonical marker comments.")+            return+        }++        if (text.contains(PACKAGE_KEYWORD) && !text.contains(PackageStructureDetector.JNI_MARKER)) {+            report(context, node, file, source, base + text.indexOf(PACKAGE_KEYWORD), PACKAGE_KEYWORD.length,+                "Malformed Package Structure exception marker. The only form that opts out is the " ++                    "verbatim `${PackageStructureDetector.JNI_MARKER}` marker comment.")+            return+        }++        if (text.contains(SCAFFOLD_KEYWORD)) {+            if (!text.contains(SCAFFOLD_PREFIX)) {+                report(context, node, file, source, base + text.indexOf(SCAFFOLD_KEYWORD), SCAFFOLD_KEYWORD.length,+                    "Malformed Raw Scaffold exception marker. Use " ++                        "`// RAW SCAFFOLD EXCEPTION: <reason>` with a non-empty reason.")+                return+            }+            val reason = reasonAfter(text, SCAFFOLD_PREFIX)+            if (!hasReason(source, comments, index, reason)) {+                report(context, node, file, source, base + text.indexOf(SCAFFOLD_PREFIX), SCAFFOLD_PREFIX.length,+                    "Exception marker without a reason. A bare `// RAW SCAFFOLD EXCEPTION` opts " ++                        "the file out but records nothing — append `: <reason>`.")+            }+            return+        }++        if (text.contains(TOAST_KEYWORD)) {+            if (!text.contains(TOAST_PREFIX)) {+                report(context, node, file, source, base + text.indexOf(TOAST_KEYWORD), TOAST_KEYWORD.length,+                    "Malformed Toast exception marker: the colon is required and a marker without " ++                        "it does NOT opt the file out. Use `// TOAST EXCEPTION: <reason>`.")+                return+            }+            val reason = reasonAfter(text, TOAST_PREFIX)+            if (!hasReason(source, comments, index, reason)) {+                report(context, node, file, source, base + text.indexOf(TOAST_PREFIX), TOAST_PREFIX.length,+                    "Exception marker without a reason. Append `: <reason>` to " ++                        "`// TOAST EXCEPTION:` so the opt-out stays reviewable.")+            }+            return+        }++        if (text.contains(ANIMATION_KEYWORD)) {+            if (!text.contains(ANIMATION_PREFIX)) {+                report(context, node, file, source, base + text.indexOf(ANIMATION_KEYWORD), ANIMATION_KEYWORD.length,+                    "Malformed Raw Animation exception marker: the colon is required and a marker " ++                        "without it does NOT opt the file out. Use " ++                        "`// RAW ANIMATION EXCEPTION: <reason>`.")+                return+            }+            val reason = reasonAfter(text, ANIMATION_PREFIX)+            if (!hasReason(source, comments, index, reason)) {+                report(context, node, file, source, base + text.indexOf(ANIMATION_PREFIX), ANIMATION_PREFIX.length,+                    "Exception marker without a reason. Append `: <reason>` to " ++                        "`// RAW ANIMATION EXCEPTION:` so the opt-out stays reviewable.")+            }+        }+    }++    /**+     * Text after [prefix] with a single optional leading colon stripped.+     * Only the first colon is structural; reasons may contain their own.+     */+    private fun reasonAfter(text: String, prefix: String): String {+        var rest = text.substring(text.indexOf(prefix) + prefix.length)+        if (rest.startsWith(":")) rest = rest.substring(1)+        return rest.trim()+    }++    /**+     * True if [reason] is non-blank, or the immediately following `//` comment+     * on the next line carries the reason as a continuation.+     */+    private fun hasReason(+        source: String,+        comments: List<PsiComment>,+        index: Int,+        reason: String,+    ): Boolean {+        if (reason.isNotBlank()) return true+        val next = comments.getOrNull(index + 1) ?: return false+        if (!next.text.startsWith("//")) return false+        val between = source.substring(comments[index].textRange.endOffset, next.textRange.startOffset)+        if (!ADJACENT_LINE.matches(between)) return false+        val body = next.text.removePrefix("//").trim()+        return body.isNotBlank() && !body.contains("EXCEPTION")+    }++    private fun report(+        context: JavaContext,+        node: UFile,+        file: File,+        source: String,+        start: Int,+        length: Int,+        message: String,+    ) {+        context.report(+            ISSUE,+            node,+            Location.create(file, source, start, start + length),+            message,+        )+    }++    companion object {+        /**+         * Rule-definition sources (`lint-rules/` itself) document marker shapes+         * in KDoc as examples by necessity; scanning them would self-flag.+         */+        internal fun isLintRulesPackage(packageName: String): Boolean =+            packageName == "com.vayunmathur.lint" ||+                packageName.startsWith("com.vayunmathur.lint.")++        private const val TYPO_KEYWORD = "EXEPTION"+        private const val PACKAGE_KEYWORD = "PACKAGE STRUCTURE EXCEPTION"+        private const val SCAFFOLD_KEYWORD = "RAW SCAFFOLD EXCEPTION"+        private const val SCAFFOLD_PREFIX = "// RAW SCAFFOLD EXCEPTION"+        private const val TOAST_KEYWORD = "TOAST EXCEPTION"+        private const val TOAST_PREFIX = "// TOAST EXCEPTION:"+        private const val ANIMATION_KEYWORD = "RAW ANIMATION EXCEPTION"+        private const val ANIMATION_PREFIX = "// RAW ANIMATION EXCEPTION:"++        /** Adjacent `//` line: only whitespace and exactly one line break between comments. */+        private val ADJACENT_LINE = Regex("^\\h*\\R\\h*$")++        val ISSUE: Issue = Issue.create(+            id = "ExceptionMarkerFormat",+            briefDescription = "Malformed exception-marker comment",+            explanation = """+                The repo's per-file exception markers are fail-closed: a typo'd marker or a \+                missing colon silently does NOT opt the file out, so enforcement disappears \+                with no signal. Use the canonical shapes — `// PACKAGE STRUCTURE EXCEPTION \+                (JNI)` verbatim, `// RAW SCAFFOLD EXCEPTION: <reason>`, `// TOAST EXCEPTION: \+                <reason>`, `// RAW ANIMATION EXCEPTION: <reason>` — each with a non-empty \+                reason (which may continue on following `//` lines), so every opt-out stays \+                reviewable.+                """.trimIndent(),+            category = Category.CORRECTNESS,+            priority = 6,+            severity = Severity.WARNING,+            implementation = Implementation(+                ExceptionMarkerFormatDetector::class.java,+                Scope.JAVA_FILE_SCOPE,+            ),+        )+    }+}
lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt b/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.ktindex 2364eda71e..d54c86b1dc 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/ModernAppsIssueRegistry.kt@@ -19,6 +19,9 @@ class ModernAppsIssueRegistry : IssueRegistry() {         RawScaffoldInAppDetector.ISSUE,         Room2UsageDetector.ISSUE,         WindowInsetsInReusableComponentDetector.ISSUE,+        ExceptionMarkerFormatDetector.ISSUE,+        TodoEvasionDetector.ISSUE,+        CommentedOutCodeDetector.ISSUE,     )      override val api: Int = CURRENT_API
lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.ktindex d5f64248ba..9efd9bf670 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt@@ -123,7 +123,9 @@ class PackageStructureDetector : Detector(), SourceCodeScanner {         // below is skipped, so a future JNI file only needs to add the comment.         // Belt-and-suspenders: an explicit allow-set of the currently-frozen FQNs acts         // as a fallback in case the marker is ever accidentally dropped.-        private const val JNI_MARKER = "// PACKAGE STRUCTURE EXCEPTION (JNI)"+        // Internal (not private) so ExceptionMarkerFormatDetector can validate the+        // verbatim shape against the same constant instead of a copy.+        internal const val JNI_MARKER = "// PACKAGE STRUCTURE EXCEPTION (JNI)"          private val JNI_EXEMPT_FQNS = setOf(             "com.vayunmathur.euicc.EuiccNative",@@ -136,7 +138,11 @@ class PackageStructureDetector : Detector(), SourceCodeScanner {         )          fun isJniException(node: UFile): Boolean {-            val text = (node.sourcePsi as? KtFile)?.text ?: node.sourcePsi?.text+            val ktFile = node.sourcePsi as? KtFile+            if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, JNI_MARKER)) return true+            // Fall back to raw text for non-Kotlin sources, where the marker is+            // still a comment but there is no KtFile to walk.+            val text = if (ktFile == null) node.sourcePsi?.text else null             if (text != null && text.contains(JNI_MARKER)) return true             val pkg = node.packageName             return node.classes.any { clazz ->
lint-rules/src/main/java/com/vayunmathur/lint/RawScaffoldInAppDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/RawScaffoldInAppDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/RawScaffoldInAppDetector.ktindex 531d73b8c3..d3c1382eb5 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/RawScaffoldInAppDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/RawScaffoldInAppDetector.kt@@ -50,8 +50,9 @@ class RawScaffoldInAppDetector : Detector(), SourceCodeScanner {         if (isLibraryPackage(packageName)) return          // Documented per-file opt-out.-        val fileText = (context.uastFile?.sourcePsi as? KtFile)?.text-        if (fileText != null && fileText.contains(EXCEPTION_MARKER)) return+        // Comment-only: a marker inside a string literal must not opt the file out.+        val ktFile = context.uastFile?.sourcePsi as? KtFile+        if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return          context.report(             ISSUE,
lint-rules/src/main/java/com/vayunmathur/lint/Room2UsageDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/Room2UsageDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/Room2UsageDetector.ktindex 402d6f681e..1edd859a75 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/Room2UsageDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/Room2UsageDetector.kt@@ -10,6 +10,7 @@ import com.android.tools.lint.detector.api.Location import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner+import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.uast.UElement import org.jetbrains.uast.UFile @@ -27,6 +28,10 @@ import org.jetbrains.uast.UFile  * because several databases reference Room 2 by fully-qualified name with no import at all  * (`object : androidx.room.migration.Migration(1, 2)`), which an import-only or  * `getApplicableMethodNames()` check would miss entirely.+ *+ * Matches inside comments (including KDoc) are skipped, so a doc comment that+ * mentions `androidx.room.` while explaining the Room 2 → Room 3 migration does+ * not break the build.  */ class Room2UsageDetector : Detector(), SourceCodeScanner { @@ -38,18 +43,24 @@ class Room2UsageDetector : Detector(), SourceCodeScanner {             override fun visitFile(node: UFile) {                 val source = node.sourcePsi?.text ?: return                 val file = context.file ?: return+                // Skip matches inside comments/KDoc: a doc comment explaining the+                // Room 2 -> Room 3 migration must not break the build.+                val ktFile = node.sourcePsi as? KtFile+                val commentRanges = ktFile?.let { CommentOnlyMatcher.commentRangesIn(it) }.orEmpty()                  var from = source.indexOf(ROOM2_PREFIX)                 while (from >= 0) {-                    context.report(-                        ISSUE,-                        node,-                        Location.create(file, source, from, from + ROOM2_PREFIX.length),-                        "Room 2 is not used in this repo. Replace `androidx.room.` with " +-                            "`androidx.room3.` (`@TypeConverter`/`@TypeConverters` became " +-                            "`@ColumnTypeConverter`/`@ColumnTypeConverters`, and " +-                            "`RoomDatabase.withTransaction` became `withWriteTransaction`).",-                    )+                    if (!CommentOnlyMatcher.isInRanges(from, commentRanges)) {+                        context.report(+                            ISSUE,+                            node,+                            Location.create(file, source, from, from + ROOM2_PREFIX.length),+                            "Room 2 is not used in this repo. Replace `androidx.room.` with " ++                                "`androidx.room3.` (`@TypeConverter`/`@TypeConverters` became " ++                                "`@ColumnTypeConverter`/`@ColumnTypeConverters`, and " ++                                "`RoomDatabase.withTransaction` became `withWriteTransaction`).",+                        )+                    }                     from = source.indexOf(ROOM2_PREFIX, from + ROOM2_PREFIX.length)                 }             }
lint-rules/src/main/java/com/vayunmathur/lint/ToastDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/ToastDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/ToastDetector.ktindex 8c9fa5b21d..2e947dfc7a 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/ToastDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/ToastDetector.kt@@ -40,8 +40,9 @@ class ToastDetector : Detector(), SourceCodeScanner {         if (!context.evaluator.isMemberInClass(method, TOAST_CLASS)) return          // Documented per-file opt-out, matching the repo's other escape hatches.-        val fileText = (context.uastFile?.sourcePsi as? KtFile)?.text-        if (fileText != null && fileText.contains(EXCEPTION_MARKER)) return+        // Comment-only: a marker inside a string literal must not opt the file out.+        val ktFile = context.uastFile?.sourcePsi as? KtFile+        if (ktFile != null && CommentOnlyMatcher.containsMarkerInComments(ktFile, EXCEPTION_MARKER)) return          context.report(             ISSUE,
lint-rules/src/main/java/com/vayunmathur/lint/TodoEvasionDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/TodoEvasionDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/TodoEvasionDetector.ktnew file mode 100644index 0000000000..e53a62f7ef--- /dev/null+++ b/lint-rules/src/main/java/com/vayunmathur/lint/TodoEvasionDetector.kt@@ -0,0 +1,127 @@+package com.vayunmathur.lint++import com.android.tools.lint.client.api.UElementHandler+import com.android.tools.lint.detector.api.Category+import com.android.tools.lint.detector.api.Detector+import com.android.tools.lint.detector.api.Implementation+import com.android.tools.lint.detector.api.Issue+import com.android.tools.lint.detector.api.JavaContext+import com.android.tools.lint.detector.api.Location+import com.android.tools.lint.detector.api.Scope+import com.android.tools.lint.detector.api.Severity+import com.android.tools.lint.detector.api.SourceCodeScanner+import org.jetbrains.kotlin.psi.KtFile+import org.jetbrains.uast.UElement+import org.jetbrains.uast.UFile+import java.io.File++/**+ * Catches TODO-marker shapes that evade detekt's `ForbiddenComment` ban.+ *+ * detekt matches exact comment substrings, so each of these live shapes slips+ * past `ForbiddenComment` (`FIXME:`/`STOPSHIP:`/`TODO:`) untouched:+ *  - scoped markers with a parenthesised owner — `TODO(scope): ...`,+ *    `TODO(b/12345): ...`+ *  - bare `TODO` / `FIXME` words in section banners with no colon+ *    (`// ---- TODO / FIXME ----`)+ *+ * The base ban stays blocking in detekt; these evasion shapes land here as a+ * warning first and join the ban at promotion (Phase 4). Comment-only via+ * [CommentOnlyMatcher]: an identifier or string literal that happens to+ * contain `TODO` must not trip this check.+ */+class TodoEvasionDetector : Detector(), SourceCodeScanner {++    override fun getApplicableUastTypes(): List<Class<out UElement>> =+        listOf(UFile::class.java)++    override fun createUastHandler(context: JavaContext): UElementHandler =+        object : UElementHandler() {+            override fun visitFile(node: UFile) {+                val packageName = node.packageName+                if (packageName.isEmpty()) return+                if (!packageName.startsWith("com.vayunmathur.")) return+                if (LintPackageExclusions.isExcluded(packageName)) return+                // Rule-definition sources carry marker shapes in KDoc as examples+                // by necessity; scanning them would self-flag.+                if (ExceptionMarkerFormatDetector.isLintRulesPackage(packageName)) return+                val ktFile = node.sourcePsi as? KtFile ?: return+                val source = ktFile.text+                val file = context.file ?: return+                for (comment in CommentOnlyMatcher.commentsIn(ktFile)) {+                    val text = comment.text+                    if (BASE_BANNED.any { text.contains(it) }) continue+                    val base = comment.textRange.startOffset+                    val scoped = SCOPED_MARKER.find(text)+                    if (scoped != null) {+                        report(+                            context, node, file, source,+                            base + scoped.range.first, scoped.value.length,+                            "TODO marker with a parenthesised scope (`${scoped.value}`) evades " ++                                "the detekt `ForbiddenComment` ban, which matches `TODO:` exactly. " ++                                "Resolve it or file a tracked task — bare markers are banned " ++                                "repo-wide with no scope carve-out.",+                        )+                        continue+                    }+                    val bare = BARE_MARKER.find(text)+                    if (bare != null) {+                        report(+                            context, node, file, source,+                            base + bare.range.first, bare.value.length,+                            "Bare `${bare.value}` marker with no colon evades the detekt " ++                                "`ForbiddenComment` ban. Resolve it or file a tracked task — " ++                                "bare markers are banned repo-wide.",+                        )+                    }+                }+            }+        }++    private fun report(+        context: JavaContext,+        node: UFile,+        file: File,+        source: String,+        start: Int,+        length: Int,+        message: String,+    ) {+        context.report(+            ISSUE,+            node,+            Location.create(file, source, start, start + length),+            message,+        )+    }++    companion object {+        /** Already blocked by detekt `ForbiddenComment`; never double-report. */+        private val BASE_BANNED = listOf("FIXME:", "STOPSHIP:", "TODO:")++        /** `TODO(owner):` / `TODO(b/123):` — scoped markers the ban misses. */+        private val SCOPED_MARKER = Regex("""\bTODO\([^()\n]*\):?""")++        /** Bare `TODO` / `FIXME` banner words with no colon (and no scope paren). */+        private val BARE_MARKER = Regex("""\b(?:TODO|FIXME)\b(?!:)(?!\()""")++        val ISSUE: Issue = Issue.create(+            id = "TodoEvasion",+            briefDescription = "TODO marker shape evades the marker ban",+            explanation = """+                detekt's `ForbiddenComment` ban matches `TODO:`, `FIXME:` and `STOPSHIP:` \+                exactly, so scoped markers (`TODO(owner):`, `TODO(b/123):`) and bare banner \+                words (`TODO`, `FIXME` with no colon) slip past it untouched. Those shapes \+                are banned here too: resolve the item or file a tracked task rather than \+                leaving an untracked marker in the tree.+                """.trimIndent(),+            category = Category.PRODUCTIVITY,+            priority = 5,+            severity = Severity.WARNING,+            implementation = Implementation(+                TodoEvasionDetector::class.java,+                Scope.JAVA_FILE_SCOPE,+            ),+        )+    }+}
notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.ktindex 8f48f4b54d..42981598bc 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt@@ -54,7 +54,7 @@ import com.vayunmathur.notes.platform.NotesListUiState  /**  * The notes list, with no dependency on the ViewModel or the back stack so it can be- * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing+ * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing  * images come from.  */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
rustfmt.toml
diff --git a/rustfmt.toml b/rustfmt.tomlnew file mode 100644index 0000000000..ad3c550c35--- /dev/null+++ b/rustfmt.toml@@ -0,0 +1,10 @@+# Rust formatting foundations (Phase 1 — advisory, no bulk reformat yet).+# `cargo fmt --check` is the warning inventory; bulk reformat deferred to Phase 4.+edition = "2021"+max_width = 100+hard_tabs = false+use_small_heuristics = "Max"+comment_width = 100+wrap_comments = false+format_code_in_doc_comments = true+imports_granularity = "Crate"