#!/usr/bin/env bash # android-project-full-audit helper. # All state lives in an audit workspace (AUDIT_DIR). Safe for concurrent use by # several subagents: every write goes through a mkdir-based lock. # # Usage: # audit.sh init # inventory + library skeleton # audit.sh tree # package/file-tree organization view # audit.sh signals # import-based library hints (NOT evidence) # audit.sh batch [size] # split pending files into batches # audit.sh next [n] # next n pending files (single-agent mode) # audit.sh patterns [category] # pattern slugs already documented (+ counts) # audit.sh finding [""] # body on stdin # title required for a new slug; omit for a refinement of an existing slug # audit.sh none <audit-dir> <category> "<what was looked for>" # record an absence # audit.sh also <audit-dir> <category> <slug> <source-path> # another occurrence # audit.sh mark <audit-dir> <source-path> <status> [note] # status: contributed | redundant | trivial | skipped # audit.sh coverage <audit-dir> # progress report (always exits 0) # audit.sh phase <audit-dir> <name> # timestamp the start of a phase (for durations) # audit.sh finish <audit-dir> # stop the clock; write usage.md (tokens + duration) # audit.sh usage <audit-dir> [--json] # token usage + duration so far # audit.sh gate <audit-dir> # exit 1 if pending files or status/finding mismatches set -euo pipefail SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TEMPLATES="$SELF_DIR/../templates" CATEGORIES="build-and-modules file-organization architecture ui navigation networking serialization persistence concurrency dependency-injection background-work platform-integration security-auth observability testing features observations" die() { echo "audit.sh: $*" >&2; exit 2; } now_ms() { python3 -I -c 'import time; print(int(time.time()*1000))'; } lock() { local l="$AUDIT_DIR/.lock" i=0 until mkdir "$l" 2>/dev/null; do i=$((i+1)); [ $i -gt 600 ] && die "could not acquire lock $l (stale? rmdir it)" sleep 0.1 done trap 'rmdir "$AUDIT_DIR/.lock" 2>/dev/null || true' EXIT } unlock() { rmdir "$AUDIT_DIR/.lock" 2>/dev/null || true; trap - EXIT; } need_dir() { AUDIT_DIR="${1:?audit-dir required}"; [ -f "$AUDIT_DIR/ledger.tsv" ] || die "no ledger in $AUDIT_DIR (run init first)"; } valid_cat() { case " $CATEGORIES " in *" $1 "*) ;; *) die "unknown category '$1'. Valid: $CATEGORIES";; esac; } # Normalise a source path to be project-relative (accepts absolute paths too). relpath() { local p="$1" root; root="$(cat "$AUDIT_DIR/.project_root")" [ "$p" = "(project)" ] && { printf '%s' "$p"; return; } case "$p" in "$root"/*) p="${p#"$root"/}";; esac printf '%s' "${p#./}" } cmd_init() { local proj="${1:?project-dir required}" out="${2:?audit-dir required}" [ -d "$proj" ] || die "project dir not found: $proj" proj="$(cd "$proj" && pwd)" if [ -f "$out/ledger.tsv" ] && awk -F'\t' 'NR>1 && $7!="pending" {f=1} END {exit !f}' "$out/ledger.tsv" && [ "${FORCE:-}" != 1 ]; then die "$out already has audit progress. Resume with 'coverage'/'next'/'batch', or re-run with FORCE=1 to start over (wipe $out first)." fi mkdir -p "$out/library" "$out/batches" AUDIT_DIR="$(cd "$out" && pwd)" echo "$proj" > "$AUDIT_DIR/.project_root" now_ms > "$AUDIT_DIR/.started_at"; rm -f "$AUDIT_DIR/.finished_at" printf '%s\tinventory\n' "$(cat "$AUDIT_DIR/.started_at")" > "$AUDIT_DIR/timeline.tsv" # Module roots = dirs holding a build.gradle(.kts), excluding build outputs. ( cd "$proj" && find . \( -name build -o -name .gradle -o -name .git -o -name .idea -o -name node_modules -o -name .cxx -o -name .android-audit \) -prune -o \ \( -name 'build.gradle' -o -name 'build.gradle.kts' \) -print ) \ | sed 's#^\./##; s#/\{0,1\}build\.gradle\(\.kts\)\{0,1\}$##' | sort -u > "$AUDIT_DIR/modules.txt" # Candidate source files. Documentation (*.md, docs/) is deliberately excluded: # this audit is about current implementation, not what docs claim. ( cd "$proj" && find . \ \( -name build -o -name .gradle -o -name .git -o -name .idea -o -name node_modules -o -name .cxx \ -o -name generated -o -name intermediates -o -name .android-audit -o -name docs -o -name doc \) -prune -o \ -type f \( -name '*.kt' -o -name '*.kts' -o -name '*.java' -o -name '*.gradle' -o -name '*.toml' \ -o -name 'gradle.properties' -o -name 'gradle-wrapper.properties' -o -name '*.pro' -o -name '*.aidl' -o -name '*.proto' -o -name '*.sq' \ -o -name '*.sqm' -o -name 'AndroidManifest.xml' -o -name '*.xml' -o -name '*.yml' -o -name '*.yaml' \) -print ) \ | sed 's#^\./##' \ | awk ' # drop resource noise: drawables, mipmaps, fonts, raw, anim, colors, translated values /\/res\/(drawable|mipmap|font|raw|anim|animator|color|interpolator)[^\/]*\// { next } /\/res\/values-[^\/]+\// { next } /\.xml$/ && !/AndroidManifest\.xml$/ && !/\/res\// && !/^\.github\// && !/lint\.xml$/ && !/detekt/ { next } /\.ya?ml$/ && !/^\.github\// && !/detekt/ && !/^\.gitlab-ci/ && !/bitrise|codemagic|circleci/ { next } { print }' \ | sort > "$AUDIT_DIR/.files" # Build ledger: id module sourceset kind lines path status note awk -v root="$proj" ' FILENAME==ARGV[1] { mods[++m]=$0; next } { path=$0; best=""; bl=-1 for (i=1;i<=m;i++) { mod=mods[i] if (mod=="" ) { if (bl<0) { best="(root)"; bl=0 } continue } if (index(path, mod "/")==1 && length(mod)>bl) { best=mod; bl=length(mod) } } if (best=="") best="(root)" ss="-"; if (match(path, /\/src\/[^\/]+\//)) ss=substr(path, RSTART+5, RLENGTH-6) k="other" if (path ~ /AndroidManifest\.xml$/) k="manifest" else if (path ~ /(build\.gradle(\.kts)?|settings\.gradle(\.kts)?|\.toml|gradle(-wrapper)?\.properties|\.pro)$/ || path ~ /(^|\/)buildSrc\// || path ~ /(^|\/)build-logic\//) k="build" else if (path ~ /\/res\/navigation/) k="res-navigation" else if (path ~ /\/res\/layout/) k="res-layout" else if (path ~ /\/res\/values/) k="res-values" else if (path ~ /\/res\/xml\//) k="res-xml" else if (path ~ /^\.github\/|ci|bitrise|codemagic|\.ya?ml$/) k="ci" else if (ss ~ /[tT]est/) k="test" else if (path ~ /\.kt$/) k="kotlin" else if (path ~ /\.java$/) k="java" else if (path ~ /\.(proto|aidl|sq|sqm)$/) k="schema" cmd="wc -l < \"" root "/" path "\""; cmd | getline n; close(cmd); gsub(/ /,"",n) printf "%d\t%s\t%s\t%s\t%s\t%s\tpending\t\n", ++id, best, ss, k, n, path }' "$AUDIT_DIR/modules.txt" "$AUDIT_DIR/.files" > "$AUDIT_DIR/ledger.body" { printf 'id\tmodule\tsourceset\tkind\tlines\tpath\tstatus\tnote\n'; cat "$AUDIT_DIR/ledger.body"; } > "$AUDIT_DIR/ledger.tsv" rm -f "$AUDIT_DIR/ledger.body" "$AUDIT_DIR/.files" [ -f "$AUDIT_DIR/occurrences.tsv" ] || printf 'category\tslug\tpath\n' > "$AUDIT_DIR/occurrences.tsv" for c in $CATEGORIES; do f="$AUDIT_DIR/library/$c.md" [ -f "$f" ] || cp "$TEMPLATES/library/$c.md" "$f" done # Non-source resources: counted, not read. ( cd "$proj" && find . \( -name build -o -name .gradle -o -name .git \) -prune -o -type f -path '*/res/*' -print ) \ | awk -F/ '{ for(i=1;i<=NF;i++) if ($i=="res") { d=$(i+1); sub(/-.*/,"",d); c[d]++ } } END { for (k in c) printf "%s\t%d\n", k, c[k] }' \ | sort > "$AUDIT_DIR/resource-counts.tsv" ( cd "$proj" && find . \( -name build -o -name .gradle -o -name .git -o -name node_modules -o -name .android-audit \) -prune -o \ -type f \( -iname '*.md' -o -iname '*.adoc' -o -iname '*.rst' \) -print ) | sed 's#^\./##' | sort > "$AUDIT_DIR/docs.txt" ( cd "$proj" && find . \( -name build -o -name .gradle -o -name .git \) -prune -o -type f \( -name 'local.properties' -o -name '*.keystore' -o -name '*.jks' \ -o -name 'google-services.json' -o -name 'secrets.properties' -o -name '.env' \) -print ) | sed 's#^\./##' | sort > "$AUDIT_DIR/secret-files.txt" echo "Project: $proj" echo "Audit dir: $AUDIT_DIR" echo "Modules: $(grep -c . "$AUDIT_DIR/modules.txt" || true)" echo "Files in ledger: $(($(wc -l < "$AUDIT_DIR/ledger.tsv")-1))" echo "Docs found (NOT audited; only for optional drift check): $(grep -c . "$AUDIT_DIR/docs.txt" || true) -> docs.txt" echo "Secret-bearing files (never open; note existence/role only): $(grep -c . "$AUDIT_DIR/secret-files.txt" || true) -> secret-files.txt" echo echo "By kind:"; awk -F'\t' 'NR>1{c[$4]++; l[$4]+=$5} END{for(k in c) printf " %-15s %5d files %8d lines\n", k, c[k], l[k]}' "$AUDIT_DIR/ledger.tsv" | sort echo "By module:"; awk -F'\t' 'NR>1{c[$2]++; l[$2]+=$5} END{for(k in c) printf " %-40s %5d files %8d lines\n", k, c[k], l[k]}' "$AUDIT_DIR/ledger.tsv" | sort } cmd_tree() { need_dir "$1" echo "== Modules (from build.gradle presence) =="; sed 's/^$/(root)/; s/^/ /' "$AUDIT_DIR/modules.txt" echo echo "== Package directories per module/source set (source files per package) ==" awk -F'\t' 'NR>1 && ($4=="kotlin"||$4=="java"||$4=="test") { p=$6; sub(/\/[^\/]+$/, "", p) if (match(p, /\/src\/[^\/]+\/(java|kotlin)\//)) p=substr(p, RSTART+RLENGTH) key=$2 " [" $3 "]"; d[key SUBSEP p]++ } END { for (k in d) { split(k, a, SUBSEP); printf "%s\t%s\t%d\n", a[1], a[2], d[k] } }' "$AUDIT_DIR/ledger.tsv" \ | sort -t$'\t' -k1,1 -k2,2 \ | awk -F'\t' '{ if ($1!=last) { print "\n" $1; last=$1 } printf " %-70s %4d\n", $2 "/", $3 }' echo echo "== Resource dirs (counted, not read) =="; sed 's/^/ /' "$AUDIT_DIR/resource-counts.tsv" } cmd_signals() { need_dir "$1"; local root; root="$(cat "$AUDIT_DIR/.project_root")" echo "Import/plugin hits — HINTS ONLY. Confirm by reading files before recording anything." awk -F'\t' 'NR>1 && ($4=="kotlin"||$4=="java"||$4=="build"||$4=="test") {print $6}' "$AUDIT_DIR/ledger.tsv" > "$AUDIT_DIR/.sig" while IFS='|' read -r label re; do hits=$(cd "$root" && tr '\n' '\0' < "$AUDIT_DIR/.sig" | xargs -0 grep -lE -- "$re" 2>/dev/null || true) [ -n "$hits" ] || continue printf ' %-34s %4d files e.g. %s\n' "$label" "$(printf '%s\n' "$hits" | wc -l)" "$(printf '%s\n' "$hits" | head -1)" done <<'EOF' Jetpack Compose|import androidx\.compose\. Views/XML (ViewBinding/DataBinding)|viewBinding|dataBinding|import android\.view\.LayoutInflater|setContentView\(R\.layout Fragments|import androidx\.fragment\.app\.Fragment Navigation (androidx)|import androidx\.navigation\. Compose type-safe nav|@Serializable[[:space:]]*(data )?(object|class) .*(Route|Screen|Destination) Voyager/Decompose/Appyx|cafe\.adriel\.voyager|com\.arkivanov\.decompose|com\.bumble\.appyx Kotlin Coroutines|import kotlinx\.coroutines\. Flow|import kotlinx\.coroutines\.flow\. RxJava|import io\.reactivex LiveData|import androidx\.lifecycle\.LiveData|MutableLiveData ViewModel|import androidx\.lifecycle\.ViewModel OkHttp|import okhttp3\. Retrofit|import retrofit2\. Ktor client|import io\.ktor\.client Apollo GraphQL|import com\.apollographql gRPC|import io\.grpc kotlinx.serialization|import kotlinx\.serialization\. Moshi|import com\.squareup\.moshi Gson|import com\.google\.gson Room|import androidx\.room\. SQLDelight|app\.cash\.sqldelight|com\.squareup\.sqldelight Realm|import io\.realm DataStore|import androidx\.datastore\. SharedPreferences|SharedPreferences Hilt|import dagger\.hilt\.|@HiltAndroidApp|@AndroidEntryPoint Dagger|import dagger\.(Module|Component|Provides) Koin|import org\.koin\. Anvil/kotlin-inject|com\.squareup\.anvil|me\.tatarka\.inject WorkManager|import androidx\.work\. Foreground/Services|: (Lifecycle)?Service\(|extends Service BroadcastReceiver|BroadcastReceiver Coil|import coil3?\. Glide|import com\.bumptech\.glide Paging|import androidx\.paging\. Media3/ExoPlayer|import androidx\.media3\.|com\.google\.android\.exoplayer2 CameraX|import androidx\.camera\. Firebase|import com\.google\.firebase\. Play Services|import com\.google\.android\.gms\. Biometric|import androidx\.biometric\. Security crypto/Keystore|androidx\.security\.crypto|java\.security\.KeyStore|AndroidKeyStore Timber|import timber\.log JUnit4|import org\.junit\.(Test|Before|Rule) JUnit5|import org\.junit\.jupiter MockK|import io\.mockk Mockito|import org\.mockito Turbine|import app\.cash\.turbine Robolectric|import org\.robolectric Espresso|import androidx\.test\.espresso Compose UI test|import androidx\.compose\.ui\.test Roborazzi/Paparazzi|roborazzi|app\.cash\.paparazzi KMP (commonMain)|commonMain|kotlin\("multiplatform"\)|kotlin\.multiplatform Convention plugins|class .*: Plugin<Project> Baseline profiles|androidx\.baselineprofile|BaselineProfileRule EOF rm -f "$AUDIT_DIR/.sig" } cmd_batch() { need_dir "$1"; local size="${2:-40}" rm -f "$AUDIT_DIR"/batches/batch-*.txt # Pending files, grouped by module then path, so a batch stays within one area. # Build + manifest files are expected to be handled in the orientation pass, so they sort first. awk -F'\t' 'NR>1 && $7=="pending" { pr=($4=="build"||$4=="manifest")?0:1; print pr "\t" $2 "\t" $6 }' "$AUDIT_DIR/ledger.tsv" \ | sort -t$'\t' -k1,1n -k2,2 -k3,3 \ | awk -F'\t' -v size="$size" -v dir="$AUDIT_DIR/batches" ' { if (n==0 || cnt>=size || ($2!=lastmod && cnt>=size/2)) { n++; cnt=0; f=sprintf("%s/batch-%03d.txt", dir, n) } print $3 > f; cnt++; lastmod=$2 } END { print n+0 " batches written to " dir }' for f in "$AUDIT_DIR"/batches/batch-*.txt; do [ -f "$f" ] && printf ' %s %3d files %s\n' "$(basename "$f")" "$(wc -l < "$f")" "$(head -1 "$f")"; done } cmd_next() { need_dir "$1"; local n="${2:-10}" awk -F'\t' -v n="$n" 'NR>1 && $7=="pending" { pr=($4=="build"||$4=="manifest")?0:1; print pr "\t" $2 "\t" $6 }' "$AUDIT_DIR/ledger.tsv" \ | sort -t$'\t' -k1,1n -k2,2 -k3,3 | head -n "$n" | cut -f3 } cmd_patterns() { need_dir "$1"; local cat="${2:-}" local files; if [ -n "$cat" ]; then valid_cat "$cat"; files="$AUDIT_DIR/library/$cat.md"; else files="$AUDIT_DIR/library/*.md"; fi # shellcheck disable=SC2086 grep -H '^### \[' $files 2>/dev/null | sed 's#.*/library/\([^.]*\)\.md:\#\#\# \[\([^]]*\)\] *\(.*\)#\1\t\2\t\3#' \ | while IFS=$'\t' read -r c s t; do occ=$(awk -F'\t' -v c="$c" -v s="$s" '$1==c && $2==s' "$AUDIT_DIR/occurrences.tsv" | wc -l) printf '%-22s %-40s +%-3d %s\n' "$c" "$s" "$occ" "$t" done } cmd_finding() { need_dir "$1"; local cat="${2:?category}" slug="${3:?slug}" src="${4:?source-path}" title="${5:-}" valid_cat "$cat" [[ "$slug" =~ ^[a-z0-9][a-z0-9-]*$ ]] || die "slug must be kebab-case: $slug" src="$(relpath "$src")" local body; body="$(cat)"; [ -n "$body" ] || die "finding body (stdin) is empty" local f="$AUDIT_DIR/library/$cat.md" lock if grep -q "^### \[$slug\]" "$f"; then # Same pattern already documented: insert the refinement right after that entry's block. printf '\n#### +[%s] refinement from `%s`\n%s\n\n' "$slug" "$src" "$body" > "$f.ins" awk -v slug="$slug" -v ins="$f.ins" ' function flush() { while ((getline l < ins) > 0) print l; close(ins); done=1 } /^### \[/ { if (inblk && !done) flush(); inblk = (index($0, "### [" slug "]")==1) } { print } END { if (!done) flush() }' "$f" > "$f.tmp" && mv "$f.tmp" "$f"; rm -f "$f.ins" else [ -n "$title" ] || { unlock; die "title required for new slug [$slug]"; } printf '\n### [%s] %s\n- **Exemplar:** `%s`\n%s\n' "$slug" "$title" "$src" "$body" >> "$f" fi unlock echo "recorded $cat/$slug from $src" } cmd_phase() { need_dir "$1"; local name="${2:?phase name}" lock; printf '%s\t%s\n' "$(now_ms)" "${name//$'\t'/ }" >> "$AUDIT_DIR/timeline.tsv"; unlock echo "phase '$name' started" } cmd_usage() { need_dir "$1"; shift; python3 -I "$SELF_DIR/usage.py" "$AUDIT_DIR" "$@"; } cmd_finish() { need_dir "$1" [ -f "$AUDIT_DIR/.finished_at" ] || now_ms > "$AUDIT_DIR/.finished_at" python3 -I "$SELF_DIR/usage.py" "$AUDIT_DIR" > "$AUDIT_DIR/usage.md" python3 -I "$SELF_DIR/usage.py" "$AUDIT_DIR" --json > "$AUDIT_DIR/usage.json" cat "$AUDIT_DIR/usage.md" } cmd_none() { need_dir "$1"; local cat="${2:?category}" what="${3:?what was looked for}" valid_cat "$cat"; lock printf '\n### [none] None found in code\n- **Exemplar:** `(project)`\n- Looked for: %s\n' "$what" >> "$AUDIT_DIR/library/$cat.md" unlock; echo "recorded absence in $cat" } cmd_also() { need_dir "$1"; local cat="${2:?category}" slug="${3:?slug}" src="${4:?source-path}" valid_cat "$cat"; src="$(relpath "$src")" grep -q "^### \[$slug\]" "$AUDIT_DIR/library/$cat.md" || die "no pattern [$slug] in $cat.md — record it with 'finding' first" lock; printf '%s\t%s\t%s\n' "$cat" "$slug" "$src" >> "$AUDIT_DIR/occurrences.tsv"; unlock } cmd_mark() { need_dir "$1"; local src="${2:?source-path}" st="${3:?status}" note="${4:-}" case "$st" in contributed|redundant|trivial|skipped) ;; *) die "status must be contributed|redundant|trivial|skipped";; esac src="$(relpath "$src")"; note="${note//$'\t'/ }"; note="${note//$'\n'/ }" lock awk -F'\t' -v OFS='\t' -v p="$src" -v s="$st" -v n="$note" ' NR>1 && $6==p { $7=s; $8=n; hit=1 } { print } END { if (!hit) exit 3 }' "$AUDIT_DIR/ledger.tsv" > "$AUDIT_DIR/ledger.tmp" \ && mv "$AUDIT_DIR/ledger.tmp" "$AUDIT_DIR/ledger.tsv" \ || { rm -f "$AUDIT_DIR/ledger.tmp"; unlock; die "path not in ledger: $src"; } unlock } cmd_coverage() { need_dir "$1" awk -F'\t' 'NR>1 { c[$7]++; t++ } END { for (k in c) printf " %-12s %5d (%.0f%%)\n", k, c[k], 100*c[k]/t; printf " %-12s %5d\n", "total", t }' "$AUDIT_DIR/ledger.tsv" echo "Patterns documented: $(grep -h '^### \[' "$AUDIT_DIR"/library/*.md | wc -l) extra occurrences: $(($(wc -l < "$AUDIT_DIR/occurrences.tsv")-1))" local p; p=$(awk -F'\t' 'NR>1 && $7=="pending"' "$AUDIT_DIR/ledger.tsv" | wc -l) if [ "$p" -gt 0 ]; then echo "PENDING: $p (first 20):"; awk -F'\t' 'NR>1 && $7=="pending" {print " " $6}' "$AUDIT_DIR/ledger.tsv" | head -20 else echo "All files accounted for."; fi } # Files whose status disagrees with the library: contributed with no finding, redundant with no occurrence. mismatches() { cat "$AUDIT_DIR"/library/*.md | grep -oE '^- \*\*Exemplar:\*\* `[^`]+`|^#### \+\[[^]]+\] refinement from `[^`]+`' \ | sed 's/.*`\([^`]*\)`$/\1/' | sort -u > "$AUDIT_DIR/.contrib" awk -F'\t' 'NR>1 {print $3}' "$AUDIT_DIR/occurrences.tsv" | sort -u > "$AUDIT_DIR/.occ" awk -F'\t' -v c="$AUDIT_DIR/.contrib" -v o="$AUDIT_DIR/.occ" ' BEGIN { while ((getline l < c) > 0) C[l]=1; while ((getline l < o) > 0) O[l]=1 } NR>1 && $7=="contributed" && !($6 in C) { print " contributed but no finding cites it: " $6 } NR>1 && $7=="redundant" && !($6 in O) && !($6 in C) { print " redundant but no occurrence logged: " $6 }' "$AUDIT_DIR/ledger.tsv" rm -f "$AUDIT_DIR/.contrib" "$AUDIT_DIR/.occ" } cmd_gate() { need_dir "$1"; cmd_coverage "$1" local p m; p=$(awk -F'\t' 'NR>1 && $7=="pending"' "$AUDIT_DIR/ledger.tsv" | wc -l); m="$(mismatches)" [ -n "$m" ] && { echo "Status/library mismatches:"; echo "$m"; } [ "$p" -eq 0 ] && [ -z "$m" ] && { echo "GATE: PASS"; return 0; } echo "GATE: FAIL"; return 1 } sub="${1:-}"; shift || true case "$sub" in init) cmd_init "$@";; tree) cmd_tree "$@";; signals) cmd_signals "$@";; batch) cmd_batch "$@";; next) cmd_next "$@";; patterns) cmd_patterns "$@";; finding) cmd_finding "$@";; also) cmd_also "$@";; mark) cmd_mark "$@";; coverage) cmd_coverage "$@";; gate) cmd_gate "$@";; none) cmd_none "$@";; phase) cmd_phase "$@";; usage) cmd_usage "$@";; finish) cmd_finish "$@";; ""|-h|--help|help) sed -n '2,28p' "$0";; *) sed -n '2,28p' "$0"; exit 2;; esac