diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/skills/android-project-full-audit/SKILL.md b/skills/android-project-full-audit/SKILL.md new file mode 100644 index 0000000..6603583 --- /dev/null +++ b/skills/android-project-full-audit/SKILL.md @@ -0,0 +1,127 @@ +--- +name: android-project-full-audit +description: Audit-level architecture report for an existing Android project, built by reading the source files themselves (not README/docs, which may be stale). Use when the user wants to understand, audit, map, or document how an Android app is architected — its file/module organization, the libraries and mechanisms behind each implementation category (UI, navigation, networking, concurrency, persistence, DI, background work, etc.) with code pointers, and the user-facing features. Crawls files one by one (optionally fanned out to subagents), records findings into a library of per-category audit docs, then synthesizes a REPORT.md with an implementation table and a features table. +--- + +# Android Project Full Audit + +Goal: a report of how the app is built **as implemented today**. Every claim traces to a source file the auditor actually read. Documentation (README, `docs/`, wiki, ADRs, comments describing intent) is **not evidence** — it is excluded from the crawl and must not be used to fill gaps. Where code is unclear, say so; don't backfill from docs. + +The audit runs in phases. All state lives in an **audit workspace** so the work can be resumed and split across subagents: + +``` +/ + ledger.tsv every in-scope file + status (pending/contributed/redundant/trivial/skipped) + library/.md one audit doc per implementation category — the findings library + occurrences.tsv further files that repeat an already-documented pattern (prevalence) + batches/ file lists for subagents + modules.txt, resource-counts.tsv + timeline.tsv phase start timestamps (duration tracking) + usage.md/.json token usage + duration, written by `finish` + REPORT.md final synthesized report +``` + +**Timing and tokens:** `init` starts the clock. Run `bash $A phase $AUDIT_DIR ` as the first command of each later phase (`orientation`, `per-file`, `gate`, `cross-cutting`, `report`). `bash $A finish $AUDIT_DIR` stops the clock and writes `usage.md`. Usage is read from the harness's own logs: Claude Code transcripts (main session, subagents and headless local workers) or OpenCode's session DB. Calls are counted only inside the audit window, and only from sessions whose transcript mentions `AUDIT_DIR`. Nothing to track by hand. + +## Harness notes (Claude Code and OpenCode) + +This skill is shared by Claude Code and OpenCode, which both load it from `~/.claude/skills/`. +- **`SKILL_DIR`** is the directory containing this SKILL.md. Claude Code provides it; elsewhere use the skill's reported location, normally `~/.claude/skills/android-project-full-audit`. +- **Tool names:** "file-read tool" means `Read` in Claude Code and `read` in OpenCode. "Subagent" means the `Agent` tool with `general-purpose` in Claude Code, and the `task` tool with the `general` agent in OpenCode. +- **Local model:** if you yourself are running on a locally hosted model (e.g. OpenCode pointed at vLLM or Ollama), your subagents already run locally. Never use `local-worker-handoff` from there; it exists only to move work off Anthropic models in Claude Code. + +Helper: `A="$SKILL_DIR/scripts/audit.sh"` (run `bash $A` with no args for usage). It is the only way findings and statuses are written — it validates categories, keeps one entry per pattern slug, and locks for concurrent subagents. + +## Phase 0 — Set up + +1. Confirm the project root (the dir with `settings.gradle(.kts)`). If the user didn't give one, use the cwd if it qualifies; otherwise ask. +2. `AUDIT_DIR` defaults to `/.android-audit/`. Tell the user it was created there and suggest adding it to `.gitignore` (don't edit `.gitignore` yourself unless asked). Use another location if the user names one. +3. If `AUDIT_DIR/ledger.tsv` already exists with progress, **resume**: skip to the phase `bash $A coverage $AUDIT_DIR` indicates. `init` refuses to overwrite progress. +4. Record the git SHA if the project is a repo (`git -C rev-parse --short HEAD`) for the report header. + +## Phase 1 — Inventory + +```bash +bash $A init # builds ledger + empty library docs; prints counts by module/kind +bash $A tree # module → source set → package tree with file counts +bash $A signals # import/plugin hits per library +``` + +- The inventory includes `.kt .kts .java .gradle .toml gradle.properties gradle-wrapper.properties .pro .aidl .proto .sq`, manifests, `res/values|layout|navigation|xml`, and CI config. It excludes build outputs, generated code, drawables/mipmaps/fonts/raw (counted only), translated `values-*`, and all documentation (listed in `docs.txt` for the optional drift step only). +- `secret-files.txt` lists `local.properties`, keystores, `google-services.json`, `.env` etc. **Never open them.** Record their existence and role from what the build scripts read (e.g. "`TMDB_API_KEY` read from `local.properties`") under `security-auth`. +- `signals` output is a **map of where to look, not evidence**. A library on the classpath may be unused; an import may be dead. Nothing goes into the library from `signals` alone. +- If the ledger has obvious noise (e.g. a vendored SDK, sample app, or a huge generated dir the filters missed), mark those `skipped` with a reason and tell the user what was excluded. + +## Phase 2 — Orientation pass (main model, always) + +`bash $A phase $AUDIT_DIR orientation` + +Read these yourself first, in full, recording findings and marking each file. They establish the vocabulary every later reader needs: + +1. `settings.gradle(.kts)`, `gradle/libs.versions.toml`, root `build.gradle(.kts)`, `gradle.properties`, convention plugins (`build-logic/`, `buildSrc/`). +2. Each module's `build.gradle(.kts)` — note plugins and `project(":…")` dependencies → module graph. +3. Every `AndroidManifest.xml` — components, permissions, deep links, `Application` class. +4. The `Application` class, the launcher Activity, the DI root (Hilt modules / Koin `startKoin` / Dagger component), and the top-level nav host / nav graph. + +Then write a 10–20 line **orientation summary** (modules and what each is for, core libraries + versions, architectural style as seen so far, slug names already used). Keep it in your context; it is passed to every subagent. + +## Phase 3 — Per-file audit + +`bash $A phase $AUDIT_DIR per-file` + +Every remaining `pending` file is read **one by one, in full**, and filed into the right library doc. The exact procedure — read, pick category, new pattern vs. refinement vs. repetition, features, mark status — is in **`references/file-auditor-prompt.md`**. Read it before starting this phase; it applies to you as much as to subagents. + +Reading: use one file-read call per file (several independent reads in one message is fine). Don't `cat` whole packages through Bash — it blurs the per-file judgement and large UI packages overflow tool output. + +Key rule on redundancy: a file does not need to contribute. When a file is "more of the same" (the 12th Room DAO, the 30th screen ViewModel with the identical shape) log it with `also` and mark it `redundant`. Only write prose when the file shows something not already in the library. Before writing, check `bash $A patterns $AUDIT_DIR `. + +**Choose an execution mode** from the pending count (`bash $A coverage $AUDIT_DIR`): + +- **≤ 150 pending files → main model alone.** Loop: `bash $A next $AUDIT_DIR 10`, read and file each, repeat until `coverage` exits 0. +- **> 150, or the user asked to offload to a local model → batched workers.** `bash $A batch $AUDIT_DIR 40` (batches stay within one module where possible). Fill the prompt in `references/file-auditor-prompt.md` per batch (`{PROJECT_ROOT}`, `{AUDIT_DIR}`, `{SKILL_DIR}`, `{BATCH_FILE}`, `{ORIENTATION_SUMMARY}`). Then pick the worker backend: + 1. **Local worker (Claude Code only, preferred when available).** If you are in Claude Code on an Anthropic model and the `local-worker-handoff` skill is installed, load it and run its `check`. On success, write each filled prompt to a file and dispatch it through that skill's `run`, with `--cwd ` and `--allow "Read Grep Glob Bash(bash $A:*)"`, respecting the backend's `max_parallel`. Use batches of ~20 files for local workers. This skill never names a server, model or key; those belong to the handoff skill's config. + 2. **Native subagents.** This is the default in OpenCode and the fallback in Claude Code when the handoff skill is absent or `check` fails (say so in one line). Spawn one subagent per batch (see Harness notes for the tool), several in a single message: **up to 6 at a time** on hosted models, **2–3 at a time** on a local model so they don't queue on one GPU. Local-model subagents get batches of ~20 files and the heavier spot-check in Phase 4. + + When a wave finishes, run `patterns` and pass any notable new slugs into the next wave's orientation summary so later workers reuse them instead of inventing synonyms. Tell the user the batch count and backend before launching, and give a one-line update per wave. +- If the user asked for a quick/cheaper run, say what you'll reduce (e.g. read all Kotlin/Java but only sample res files) and mark the unsampled files `skipped` with note `sampled-out` — never silently drop coverage. + +## Phase 4 — Coverage gate + +`bash $A phase $AUDIT_DIR gate` + +1. `bash $A gate $AUDIT_DIR` must print `GATE: PASS`: no `pending` files, every `contributed` file is cited by a finding, every `redundant` file has a logged occurrence. Fix or re-audit whatever it lists. (`coverage` is the non-failing progress view.) +2. **Spot-check delegated work** (skip in main-model mode). Per batch, pick ~3 files marked `redundant`/`trivial` and ~2 `contributed` exemplars, open them, and confirm the status and the finding are right. Check local-worker batches more heavily (~5 + 3). If a batch looks skimmed (everything `trivial`, findings that don't match the file, invented line numbers), redo it with a built-in subagent or yourself and tell the user which batches were redone. +3. Check for slug synonyms across workers (`patterns` output: e.g. `retrofit-api-service` vs `retrofit-service-interface`). Treat them as one pattern in the report. + +## Phase 4.5 — Cross-cutting entries (main model) + +`bash $A phase $AUDIT_DIR cross-cutting` + +The per-file loop doesn't naturally produce these, so write them now: +- `file-organization`: the packaging scheme, naming conventions and outliers, from `audit.sh tree` plus what you read. Use source `(project)`. +- Empty categories: `bash $A none $AUDIT_DIR ""`, so the report can say "None found in code" with evidence of looking. +- `observations`: inconsistencies across files, such as two mechanisms for one job or migrations in progress, that no single file reveals. +- Superseded claims: the library is append-only. If an early finding was wrong or an "Inferred:" note was later confirmed, add a refinement to that slug saying so. The report uses the latest refinement. + +## Phase 5 — Consolidate and report + +`bash $A phase $AUDIT_DIR report` + +1. Read **every** `library/*.md` in full and `occurrences.tsv` (prevalence per slug: `awk -F'\t' 'NR>1{print $1"/"$2}' occurrences.tsv | sort | uniq -c | sort -rn`). +2. Resolve conflicts: where two mechanisms coexist (Gson + kotlinx.serialization, LiveData + StateFlow), report both with counts — that is a finding, not noise. Note which is newer/dominant only if the code shows it. +3. Pick **code pointers** per category: the 1–3 files that most clearly show the pattern (usually the exemplar, but prefer a clean canonical file over a first-seen edge case). Verify each path exists. +4. Run `bash $A finish $AUDIT_DIR` immediately before writing the report. It stops the clock and writes `usage.md`, whose tables go verbatim into the report's "Usage & duration" section. Tokens spent writing the report itself fall after the clock stops; the report's section says so. +5. Write `AUDIT_DIR/REPORT.md` following **`references/report-template.md`**: at-a-glance, build & toolchain, **file tree organization scheme**, **implementation summary table (Category | Implementation details | Code pointers)**, **features table (Feature | What it lets the user do | Entry point)**, architecture & data flow with one end-to-end trace, observations (inconsistencies, risks, strengths), coverage & method. +6. Print the summary to the terminal as the template's last paragraph describes, and give the full path to `REPORT.md` and the library dir. + +If this skill is itself running inside a subagent and the harness refuses the `REPORT.md` write, don't work around it. Return the full report text as your final reply, with the intended path, so the parent session saves it. + +Optional, only after the report is complete and only if documentation exists: add a **"Documentation drift"** section listing doc claims the code contradicts (e.g. README says Dagger, code uses Hilt). This is the only point where docs are opened, and they are compared against the report — never used to write it. + +## Guardrails + +- Read files; don't infer content from names, grep hits, or `signals`. +- Cite paths (and `:line` for key facts). Mark inferences as "Inferred:". +- Versions from version catalog/build files only. +- Never open files in `secret-files.txt`, and never copy secret values into the library or report; note location and type only. +- Don't modify the audited project. The only writes are inside `AUDIT_DIR`. diff --git a/skills/android-project-full-audit/references/file-auditor-prompt.md b/skills/android-project-full-audit/references/file-auditor-prompt.md new file mode 100644 index 0000000..c2fe50b --- /dev/null +++ b/skills/android-project-full-audit/references/file-auditor-prompt.md @@ -0,0 +1,58 @@ +# File-auditor prompt + +Use this verbatim (fill the `{…}` placeholders) when spawning a subagent for one batch. The main model follows the same rules when it audits files itself. + +--- + +You are auditing part of an Android codebase. Your job is to read source files **one at a time, in full**, and record what they reveal about how the app is implemented into a shared library of audit docs. Documentation (README, docs/, KDoc claims, comments describing intent) is NOT evidence — only code and build config is. If a comment says one thing and the code does another, record what the code does (and note the mismatch under `observations`). + +- Project root: `{PROJECT_ROOT}` +- Audit workspace: `{AUDIT_DIR}` +- Helper: `A="{SKILL_DIR}/scripts/audit.sh"` +- Your batch: `{AUDIT_DIR}/batches/{BATCH_FILE}` (one project-relative path per line) +- Orientation context (from the main pass): {ORIENTATION_SUMMARY} + +## Before starting + +1. `bash $A patterns {AUDIT_DIR}` — see what is already documented, so you don't re-describe known patterns. +2. Skim `{AUDIT_DIR}/library/.md` headers for the categories your batch likely touches. + +## For each file in the batch, in order + +1. **Read the whole file** with the file-read tool (`Read` / `read`), one file per call (never judge from the filename or a grep, and never `cat` groups of files through Bash). For very large files (>800 lines) read it in chunks, but read all of it. +2. Decide what it shows. 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`. One file can feed several categories. +3. For each thing it shows, choose ONE of: + - **New pattern** → record it: + ```bash + bash $A finding {AUDIT_DIR} "" <<'EOF' + - **What:** concrete mechanism (library + version if visible, class/function names) + - **How:** 2–5 bullets on how it actually works here, citing `path:line` for key lines + - **Why it matters / where it connects:** related files/classes (optional) + EOF + ``` + Slug names the *pattern*, not the file: `okhttp-auth-interceptor`, `room-flow-dao`, `hilt-viewmodel-injection`, `feature-checkout-flow`. + - **Refinement of an existing pattern** (adds something genuinely new — a variant, an exception, a second mechanism, or a correction of an earlier claim) → same `finding` command with the existing slug and **no title**; it is inserted under that entry. + - **Pure repetition** (same pattern, nothing new) → `bash $A also {AUDIT_DIR} ` only. Do not write prose. This keeps prevalence counts honest without bloating the docs. +4. **Features:** if the file is a screen, route, entry point, worker, receiver, or widget the user experiences, record a `features` entry (slug `feature-`) describing in user language what it lets the user do, the entry-point file, and the route/deep link if any. Read string resources referenced for labels if needed. +5. Mark the file — exactly one status: + - `contributed` — you recorded at least one `finding` (new or refinement) + - `redundant` — only `also` occurrences; note = the slug(s) it repeats + - `trivial` — nothing worth recording (empty, constants, generated-like, tiny glue); note = why + - `skipped` — could not read / binary / out of scope; note = why + ```bash + bash $A mark {AUDIT_DIR} "" + ``` + +## Rules + +- Evidence over inference. Every claim cites a path (and line where useful). If you infer something not directly visible, prefix it with "Inferred:". +- Library versions come from `libs.versions.toml` / build files, never from docs. +- Never open `local.properties`, keystores, `google-services.json` or `.env` files, and never copy secrets (API keys, tokens) into the library — note their presence and location only. +- Line numbers you cite must come from what the file-read tool showed you. If you didn't see the line, cite the file without a line number. +- Prefer one sharp entry over many vague ones. Don't restate what a pattern already says. +- Stay inside your batch. If a file references something important outside it, mention the referenced path in your finding; another pass covers it. +- Use only the helper to write to the library and ledger (it handles locking — other auditors are writing concurrently). Do not edit library files directly. + +## When done + +Run `bash $A coverage {AUDIT_DIR}` and reply with ≤15 lines: counts by status for your batch, the new slugs you created, and anything surprising (conflicting patterns, migrations in progress, suspected dead code). diff --git a/skills/android-project-full-audit/references/report-template.md b/skills/android-project-full-audit/references/report-template.md new file mode 100644 index 0000000..906149a --- /dev/null +++ b/skills/android-project-full-audit/references/report-template.md @@ -0,0 +1,69 @@ +# Report template + +Write `{AUDIT_DIR}/REPORT.md` with this structure. Every table cell that names a file must be a real, project-relative path that exists. Pull content from `library/*.md`, `occurrences.tsv`, `ledger.tsv` and `audit.sh tree` output — not from memory, not from docs. + +```markdown +# — Architecture Audit +_Audited from source at (). Files in scope: N; read: N; contributed: N; redundant: N; trivial: N; skipped: N._ +_Source of truth: implementation only. Documentation was not used as evidence._ + +## 1. At a glance +3–6 bullets: what the app is, the architectural style in one line, UI toolkit, async model, DI, data layer, module count. + +## 2. Build & toolchain +| Item | Value | Source | +|---|---|---| +| AGP / Gradle / Kotlin / JDK | … | `gradle/libs.versions.toml` | +| compileSdk / minSdk / targetSdk | … | … | +| Modules | N (list or link to §3) | `settings.gradle.kts` | +| Build types / flavors | … | … | +| Annotation processing | KSP / KAPT | … | + +## 3. File tree organization +- **Scheme:** e.g. "multi-module, package-by-feature: `:feature:*` (UI+VM), `:core:*` (data, network, db, designsystem), `:app` (wiring)". State whether packaging is by feature, by layer, or mixed, with evidence. +- A trimmed tree (modules → key packages, file counts), ≤40 lines, from `audit.sh tree`. +- Module dependency direction (Mermaid `graph` or arrow list) if multi-module. +- Naming conventions observed, and notable outliers. + +## 4. Implementation summary +| Category | Implementation details | Code pointers | +|---|---|---| +| UI | Jetpack Compose (Material 3), custom theme in `:core:designsystem`; Coil for images | `feature/home/.../HomeScreen.kt`, `core/designsystem/.../Theme.kt` | +| Navigation | Navigation Compose 2.8 type-safe routes; one NavHost | `app/.../AppNavHost.kt` | +| Networking | Retrofit + OkHttp, auth interceptor, kotlinx.serialization converter | `core/network/.../NetworkModule.kt`, `.../AuthInterceptor.kt` | +| Concurrency | Coroutines + Flow; injected dispatchers; `stateIn(WhileSubscribed)` in VMs | … | +| … one row per category that has findings: architecture, serialization, persistence, DI, background work, platform integration, security/auth, observability, testing, build | | | + +Rules: "Implementation details" names concrete libraries/mechanisms (+version when known) and, when a category has competing approaches, lists both with rough prevalence ("StateFlow in 14 VMs, LiveData in 3 legacy VMs"). "Code pointers" = 1–3 exemplar files that best show the category (the exemplars from the library, preferring the clearest over the first-seen). + +## 5. Features (user perspective) +| Feature | What it lets the user do | Entry point | +|---|---|---| +| Sign in | Log in with email/password or Google; stays signed in across launches | `feature/auth/.../LoginScreen.kt` | +| … | | | + +Include user-perceivable background features (sync, notifications, widgets, share targets, deep links). Group by area if > 15 rows. + +## 6. Architecture & data flow +- Layering as implemented (UI → VM → UseCase? → Repository → DataSource), with one traced example end-to-end citing each file in the chain. +- State management shape (UiState / events / effects). +- Offline/caching strategy, source of truth. +- Optional Mermaid diagram. + +## 7. Observations +- **Inconsistencies / migrations in progress** (two ways of doing the same thing, with counts). +- **Risks & tech debt** (with paths). +- **Strengths** worth preserving. + +## 8. Coverage & method +How many files were in scope, read, and contributed; what was excluded and why (generated code, resources counted not read: `resource-counts.tsv`); how many subagents/batches. Location of the library: `{AUDIT_DIR}/library/`. + +## 9. Usage & duration +Paste `usage.md` verbatim: wall-clock duration, per-phase durations, and the token table per harness / session kind / model, with the total row. Below it, add one line per caveat that applies: +- Tokens for writing this report fall after `finish` and are not included. +- The run was resumed across sessions, so wall clock includes idle time. +- A local model (vLLM/Ollama) reports no cache hits, so its input shows as uncached. +- Another audit or unrelated work ran in the same session during the window, so the session row includes that. +``` + +After writing the file, print to the terminal: section 1, the Implementation summary table, the Features table, the top 3–5 observations, the duration and token total row from §9, and the path to `REPORT.md`. diff --git a/skills/android-project-full-audit/scripts/audit.sh b/skills/android-project-full-audit/scripts/audit.sh new file mode 100644 index 0000000..80026a4 --- /dev/null +++ b/skills/android-project-full-audit/scripts/audit.sh @@ -0,0 +1,363 @@ +#!/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 diff --git a/skills/android-project-full-audit/scripts/usage.py b/skills/android-project-full-audit/scripts/usage.py new file mode 100644 index 0000000..12c72dc --- /dev/null +++ b/skills/android-project-full-audit/scripts/usage.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Token usage + duration for one audit run. + +usage.py <audit-dir> [--json] + +Window: <audit-dir>/.started_at .. .finished_at (or now), epoch ms. +Attribution: any session (main, subagent, headless worker) whose transcript mentions +the audit dir path; only model calls made inside the window are counted. + +Sources (read-only): + Claude Code ~/.claude/projects/*/**/*.jsonl (assistant message.usage, deduped by message id) + OpenCode ~/.local/share/opencode/opencode.db (message.data.tokens; subagents = child sessions) +""" +import glob, json, os, sqlite3, sys, time +from collections import defaultdict +from datetime import datetime + +def iso_ms(s): + try: return int(datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp() * 1000) + except Exception: return None + +def read_ms(path, default=None): + try: return int(open(path).read().strip()) + except Exception: return default + +def empty(): return {"calls": 0, "input": 0, "cache_write": 0, "cache_read": 0, "output": 0, "sessions": set()} + +def claude_code(audit_dir, start, end, rows): + needle = audit_dir.encode() + root = os.path.expanduser("~/.claude/projects") + for f in glob.glob(os.path.join(root, "**", "*.jsonl"), recursive=True): + try: + if os.path.getmtime(f) * 1000 < start: continue + with open(f, "rb") as fh: data = fh.read() + except OSError: continue + if needle not in data: continue + kind = "subagent" if "/subagents/" in f else "session" + seen = {} + for line in data.splitlines(): + try: o = json.loads(line) + except Exception: continue + m = o.get("message") or {} + if o.get("type") != "assistant" or not m.get("usage"): continue + ts = iso_ms(o.get("timestamp", "")) + if ts is None or ts < start or ts > end: continue + seen[m.get("id") or id(o)] = (m.get("model") or "?", m["usage"]) # last write wins + for model, u in seen.values(): + r = rows[("claude-code", kind, model)] + r["calls"] += 1; r["sessions"].add(f) + r["input"] += u.get("input_tokens") or 0 + r["cache_write"] += u.get("cache_creation_input_tokens") or 0 + r["cache_read"] += u.get("cache_read_input_tokens") or 0 + r["output"] += u.get("output_tokens") or 0 + +def opencode(audit_dir, start, end, rows): + db = os.path.expanduser("~/.local/share/opencode/opencode.db") + if not os.path.exists(db): return + try: c = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + except Exception: return + try: + roots = {r[0] for r in c.execute( + "select distinct p.session_id from part p join session s on s.id=p.session_id " + "where s.time_updated >= ? and p.data like ?", (start, f"%{audit_dir}%"))} + # include all descendants (subagent sessions) of matching sessions + allids, frontier = set(roots), set(roots) + while frontier: + q = ",".join("?" * len(frontier)) + kids = {r[0] for r in c.execute(f"select id from session where parent_id in ({q})", tuple(frontier))} + frontier = kids - allids; allids |= kids + parent = dict(c.execute("select id, parent_id from session")) + for sid in allids: + kind = "subagent" if parent.get(sid) else "session" + for (d,) in c.execute("select data from message where session_id=?", (sid,)): + o = json.loads(d); t = o.get("tokens") + ts = (o.get("time") or {}).get("created") + if o.get("role") != "assistant" or not t or ts is None or ts < start or ts > end: continue + r = rows[("opencode", kind, f'{o.get("providerID")}/{o.get("modelID")}')] + r["calls"] += 1; r["sessions"].add(sid) + r["input"] += t.get("input") or 0 + r["cache_write"] += (t.get("cache") or {}).get("write") or 0 + r["cache_read"] += (t.get("cache") or {}).get("read") or 0 + r["output"] += (t.get("output") or 0) + (t.get("reasoning") or 0) + finally: c.close() + +def fmt_dur(ms): + s = max(0, ms // 1000); return f"{s//3600}h {s%3600//60:02d}m {s%60:02d}s" if s >= 3600 else f"{s//60}m {s%60:02d}s" + +def main(): + audit_dir = os.path.abspath(sys.argv[1]); as_json = "--json" in sys.argv + start = read_ms(os.path.join(audit_dir, ".started_at")) + if start is None: sys.exit("usage.py: no .started_at in audit dir (run audit.sh init)") + fin = read_ms(os.path.join(audit_dir, ".finished_at")); end = fin or int(time.time() * 1000) + rows = defaultdict(empty) + claude_code(audit_dir, start, end, rows); opencode(audit_dir, start, end, rows) + + phases = [] + tl = os.path.join(audit_dir, "timeline.tsv") + if os.path.exists(tl): + marks = [l.rstrip("\n").split("\t") for l in open(tl) if l.strip()] + marks = [(int(t), n) for t, n in marks] + for i, (t, n) in enumerate(marks): + nxt = marks[i + 1][0] if i + 1 < len(marks) else end + phases.append((n, nxt - t)) + + tot = empty() + for r in rows.values(): + for k in ("calls", "input", "cache_write", "cache_read", "output"): tot[k] += r[k] + if as_json: + print(json.dumps({"start_ms": start, "end_ms": end, "finished": bool(fin), "duration_ms": end - start, + "phases": [{"phase": n, "ms": ms} for n, ms in phases], + "rows": [dict(harness=h, kind=k, model=m, **{x: v for x, v in r.items() if x != "sessions"}, session_count=len(r["sessions"])) + for (h, k, m), r in sorted(rows.items())], + "total": {k: v for k, v in tot.items() if k != "sessions"}}, indent=2)); return + + n = lambda v: f"{v:,}" + out = [f"**Duration:** {fmt_dur(end - start)} wall clock " + f"({datetime.fromtimestamp(start/1000):%Y-%m-%d %H:%M} → {datetime.fromtimestamp(end/1000):%H:%M}" + f"{'' if fin else ', still running'})", ""] + if phases: + out += ["| Phase | Duration |", "|---|---|"] + [f"| {p} | {fmt_dur(ms)} |" for p, ms in phases] + [""] + out += ["| Harness | Kind | Model | Sessions | Calls | Input (uncached) | Cache write | Cache read | Output | Total input |", + "|---|---|---|---|---|---|---|---|---|---|"] + for (h, k, m), r in sorted(rows.items()): + ti = r["input"] + r["cache_write"] + r["cache_read"] + out.append(f"| {h} | {k} | {m} | {len(r['sessions'])} | {n(r['calls'])} | {n(r['input'])} | {n(r['cache_write'])} | {n(r['cache_read'])} | {n(r['output'])} | {n(ti)} |") + ti = tot["input"] + tot["cache_write"] + tot["cache_read"] + out.append(f"| **Total** | | | | **{n(tot['calls'])}** | **{n(tot['input'])}** | **{n(tot['cache_write'])}** | **{n(tot['cache_read'])}** | **{n(tot['output'])}** | **{n(ti)}** |") + out += ["", "_Total input = uncached + cache write + cache read; output includes reasoning/thinking tokens. " + "Counted: model calls inside the audit window from sessions whose transcript mentions this audit dir._"] + if not rows: out.append("_No matching sessions found — usage unavailable for this harness._") + print("\n".join(out)) + +if __name__ == "__main__": main() diff --git a/skills/android-project-full-audit/templates/library/architecture.md b/skills/android-project-full-audit/templates/library/architecture.md new file mode 100644 index 0000000..56bc001 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/architecture.md @@ -0,0 +1,11 @@ +# Architecture & State + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Overall pattern and layering: MVVM/MVI/MVP/Clean, state holders, data flow, boundaries. + +**Look for:** ViewModel shape (StateFlow/LiveData/Compose state, UiState sealed classes, events/effects/intents); repository + use-case layers; domain models vs DTO vs entity mapping; single source of truth / offline-first; unidirectional data flow; layer violations. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/background-work.md b/skills/android-project-full-audit/templates/library/background-work.md new file mode 100644 index 0000000..1633dd1 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/background-work.md @@ -0,0 +1,11 @@ +# Background Work + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Work that outlives a screen. + +**Look for:** WorkManager workers (periodic/one-time, constraints), foreground services (+ type), JobScheduler/AlarmManager, sync adapters, BroadcastReceivers, boot receivers, push message handling (FirebaseMessagingService). + +## Findings diff --git a/skills/android-project-full-audit/templates/library/build-and-modules.md b/skills/android-project-full-audit/templates/library/build-and-modules.md new file mode 100644 index 0000000..d97a036 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/build-and-modules.md @@ -0,0 +1,11 @@ +# Build & Modules + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Gradle setup, module graph, versions, build variants, plugins, toolchain. + +**Look for:** settings.gradle includes; version catalog (libs.versions.toml) with actual versions; AGP/Kotlin/JDK/compileSdk/minSdk/targetSdk; convention plugins (build-logic/buildSrc); module-to-module dependencies (`project(":x")`); flavors/buildTypes; R8/proguard rules; KSP/KAPT; CI workflows. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/concurrency.md b/skills/android-project-full-audit/templates/library/concurrency.md new file mode 100644 index 0000000..e645179 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/concurrency.md @@ -0,0 +1,11 @@ +# Concurrency & Async + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Threading and async model. + +**Look for:** Coroutines (scopes: viewModelScope/lifecycleScope/custom app scope; dispatchers and whether they are injected), Flow/StateFlow/SharedFlow operators (stateIn, combine, flatMapLatest), RxJava, Executors/Handlers, LiveData, synchronization (Mutex, atomic), cancellation & error handling, structured concurrency violations (GlobalScope). + +## Findings diff --git a/skills/android-project-full-audit/templates/library/dependency-injection.md b/skills/android-project-full-audit/templates/library/dependency-injection.md new file mode 100644 index 0000000..78cbd64 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/dependency-injection.md @@ -0,0 +1,11 @@ +# Dependency Injection + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** How objects get constructed and wired. + +**Look for:** Hilt (@HiltAndroidApp, @AndroidEntryPoint, @Module/@InstallIn, scopes, qualifiers, assisted inject), Dagger components, Koin modules, kotlin-inject/Anvil, manual service locators, test replacements. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/features.md b/skills/android-project-full-audit/templates/library/features.md new file mode 100644 index 0000000..90b0aaa --- /dev/null +++ b/skills/android-project-full-audit/templates/library/features.md @@ -0,0 +1,11 @@ +# User-Facing Features + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** What the app lets a USER do, inferred from screens, routes, strings, manifest entries and workers. + +**Look for:** Each screen/flow (entry point file + route), user actions it supports (buttons, forms, gestures — read the composable/fragment and strings.xml labels), background capabilities the user perceives (sync, notifications, widgets, share targets, deep links). Write feature entries in user language: '<Feature> — lets the user …'. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/file-organization.md b/skills/android-project-full-audit/templates/library/file-organization.md new file mode 100644 index 0000000..e6a2ef8 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/file-organization.md @@ -0,0 +1,11 @@ +# File Tree Organization + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** How code is physically arranged: modules, packages, source sets, naming. + +**Look for:** package-by-feature vs package-by-layer; core/feature/data/domain module split; naming conventions (*Screen, *ViewModel, *Repository, *UseCase, *Dao); where tests live; api/impl module pairs; outliers that break the scheme. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/navigation.md b/skills/android-project-full-audit/templates/library/navigation.md new file mode 100644 index 0000000..4e4ad3a --- /dev/null +++ b/skills/android-project-full-audit/templates/library/navigation.md @@ -0,0 +1,11 @@ +# Navigation + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** How screens are wired together and how users move between them. + +**Look for:** Navigation Compose (string routes vs type-safe @Serializable routes), NavHost/NavController, nav graphs XML, Fragment transactions, multiple activities, deep links (manifest intent-filters + nav deepLink), bottom bars/drawers, back handling, result passing, third-party (Voyager/Decompose). + +## Findings diff --git a/skills/android-project-full-audit/templates/library/networking.md b/skills/android-project-full-audit/templates/library/networking.md new file mode 100644 index 0000000..b616037 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/networking.md @@ -0,0 +1,11 @@ +# Networking + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Remote I/O: HTTP clients, API definitions, interceptors, auth, caching, real-time. + +**Look for:** OkHttp (interceptors, auth, logging, cache, cert pinning), Retrofit service interfaces, Ktor, GraphQL/Apollo, gRPC, WebSockets/SSE, base URL/env config, error handling + result wrappers, retry/backoff, network monitoring (ConnectivityManager). + +## Findings diff --git a/skills/android-project-full-audit/templates/library/observability.md b/skills/android-project-full-audit/templates/library/observability.md new file mode 100644 index 0000000..51eac8d --- /dev/null +++ b/skills/android-project-full-audit/templates/library/observability.md @@ -0,0 +1,11 @@ +# Observability + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Logging, analytics, crash and performance reporting, feature flags. + +**Look for:** Timber/Log usage, Crashlytics/Sentry, analytics event wrappers, Remote Config/feature flags, StrictMode, performance tracing/baseline profiles, debug-only tooling (LeakCanary, Chucker, Flipper). + +## Findings diff --git a/skills/android-project-full-audit/templates/library/observations.md b/skills/android-project-full-audit/templates/library/observations.md new file mode 100644 index 0000000..07d8b77 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/observations.md @@ -0,0 +1,11 @@ +# Observations + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Cross-cutting notes: inconsistencies, migrations in progress, tech debt, risks, dead code, notable strengths. + +**Look for:** Two patterns for the same job (e.g. Gson AND Moshi, LiveData AND StateFlow), half-finished migrations, deprecated APIs, TODO/FIXME clusters, unused modules, layer violations, risky code (GlobalScope, main-thread I/O, !! chains), good practices worth preserving. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/persistence.md b/skills/android-project-full-audit/templates/library/persistence.md new file mode 100644 index 0000000..e8ce45f --- /dev/null +++ b/skills/android-project-full-audit/templates/library/persistence.md @@ -0,0 +1,11 @@ +# Persistence + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Local storage: databases, key-value, files, caching. + +**Look for:** Room (entities, DAOs, migrations, TypeConverters, Flow queries), SQLDelight, Realm, DataStore (Preferences/Proto), SharedPreferences, file storage, encrypted storage, cache invalidation. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/platform-integration.md b/skills/android-project-full-audit/templates/library/platform-integration.md new file mode 100644 index 0000000..cba5521 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/platform-integration.md @@ -0,0 +1,11 @@ +# Platform Integration + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Android OS surface area the app touches. + +**Look for:** Manifest components, permissions (declared + runtime request flow), notifications/channels, widgets (Glance/AppWidget), share/intent handling, content providers, camera/media/location/bluetooth, app shortcuts, tiles, Wear/TV/Auto targets, edge-to-edge, splash screen, in-app updates/review. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/security-auth.md b/skills/android-project-full-audit/templates/library/security-auth.md new file mode 100644 index 0000000..2d41354 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/security-auth.md @@ -0,0 +1,11 @@ +# Security & Auth + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Authentication, authorization, secrets, data protection. + +**Look for:** Login/session flow, token storage & refresh (OkHttp Authenticator), OAuth/Credential Manager, biometric, Keystore/EncryptedSharedPreferences, certificate pinning, network security config, exported components, hardcoded keys/secrets (flag, do not copy secret values), obfuscation. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/serialization.md b/skills/android-project-full-audit/templates/library/serialization.md new file mode 100644 index 0000000..a665851 --- /dev/null +++ b/skills/android-project-full-audit/templates/library/serialization.md @@ -0,0 +1,11 @@ +# Serialization + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** How data is encoded/decoded: JSON, protobuf, parcelables. + +**Look for:** kotlinx.serialization/Moshi/Gson (adapters, codegen vs reflection), protobuf/proto DataStore, Parcelize, custom type adapters, naming strategies. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/testing.md b/skills/android-project-full-audit/templates/library/testing.md new file mode 100644 index 0000000..43ddcce --- /dev/null +++ b/skills/android-project-full-audit/templates/library/testing.md @@ -0,0 +1,11 @@ +# Testing + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** Test strategy as implemented. + +**Look for:** Unit test frameworks (JUnit4/5, MockK/Mockito, Turbine, Truth/AssertJ), fakes vs mocks, coroutine test dispatchers, Robolectric, instrumented/Espresso/Compose UI tests, screenshot tests, test modules/fixtures, rough ratio of tested to untested areas. + +## Findings diff --git a/skills/android-project-full-audit/templates/library/ui.md b/skills/android-project-full-audit/templates/library/ui.md new file mode 100644 index 0000000..ce5153e --- /dev/null +++ b/skills/android-project-full-audit/templates/library/ui.md @@ -0,0 +1,11 @@ +# UI + +> Audit library doc. Findings come from reading source files — never from README/docs. +> Each pattern is one `### [slug] Title` entry (written via `audit.sh finding`), with an exemplar file. +> Further files that repeat a known pattern are logged with `audit.sh also`, not re-described. + +**Scope:** UI toolkit and presentation: Compose vs Views, theming, design system, image loading, lists, previews. + +**Look for:** Compose (Material2/3, custom theme, design-system module), XML layouts/ViewBinding/DataBinding, Fragments/Activities, adaptive layouts/window size classes, image loading (Coil/Glide), lists (LazyColumn/RecyclerView/Paging), animations, accessibility, previews. + +## Findings diff --git a/skills/local-worker-handoff/SKILL.md b/skills/local-worker-handoff/SKILL.md new file mode 100644 index 0000000..7e858f1 --- /dev/null +++ b/skills/local-worker-handoff/SKILL.md @@ -0,0 +1,47 @@ +--- +name: local-worker-handoff +description: Claude Code only — never use from OpenCode or any session already running on a local model. Hand off a self-contained, token-heavy task (e.g. reading and filing a batch of files) to a headless Claude Code worker running on a locally hosted model instead of an Anthropic model. Use when another skill or the user wants to offload bulk work to the local LLM to save tokens. Backends are configured per machine in ~/.claude/local-workers.json; always check availability first and fall back to built-in subagents when no backend is reachable. +--- + +# Local Worker Handoff + +> **Claude Code only.** This skill starts `claude -p` processes to move work *off* Anthropic models. If you are running in OpenCode, or on a locally hosted model, stop: use your native subagents instead. + +Runs a prompt as a separate `claude -p` process whose API traffic goes to a local, Anthropic-compatible server (e.g. vLLM ≥ 0.10 with `/v1/messages`). The calling session stays on its normal model and acts as orchestrator + reviewer. + +Server details live **only** in `~/.claude/local-workers.json` (or `$LOCAL_WORKERS_CONFIG`). Do not copy URLs, model names or keys into prompts, other skills, or files in a project. + +```json +{ "default": "name", + "backends": { "name": { "base_url": "http://host:8000", "model": "served-model-id", + "api_key_file": "~/path/to/key", "max_parallel": 2 } } } +``` + +`W="$SKILL_DIR/scripts/worker.sh"` + +## 1. Check before every handoff session + +```bash +bash $W check # or: bash $W check <backend> +``` + +Exit 0 → proceed. Non-zero, or no config file → **do not retry or debug the server**; tell the user in one line that the local backend is unavailable and fall back to the caller's default (normally built-in `Agent` subagents). Re-check before each wave if the session is long. + +## 2. Write a self-contained prompt file + +The worker starts cold: no conversation context, no skills loaded on its behalf. Put everything in the prompt file (in the scratchpad): absolute paths, the exact procedure, the exact commands it may run, and the expected final reply (keep it short — you read it). Local models are weaker at long, loose instructions: number the steps and give command templates verbatim. + +## 3. Run + +```bash +bash $W run --prompt-file <file> --out <result.json> --cwd <dir> \ + --allow "Read Grep Glob Bash(bash /abs/path/helper.sh:*)" +``` + +- `--allow` is the worker's whole tool allowlist. Grant the narrowest set: read tools plus specific helper scripts. Agent/Write/Edit/web tools are always disallowed — workers report through helper scripts or their final reply. +- For parallel workers, start up to the backend's `max_parallel` runs as separate background Bash commands (`run_in_background: true`), one per prompt file. More than that just queues on the GPU. +- The final reply prints to stdout; full JSON (turns, errors) is in `--out`, stderr in `<out>.stderr`. The reported `costUSD` is a placeholder price for an unrecognised model — local runs cost nothing. + +## 4. Verify — always + +Local-model output is untrusted until checked. Before using a worker's results, spot-check a sample against the source (the caller skill says how). If a worker's output is wrong or thin, redo that unit with a built-in subagent or yourself, and tell the user which units were redone. diff --git a/skills/local-worker-handoff/scripts/worker.sh b/skills/local-worker-handoff/scripts/worker.sh new file mode 100644 index 0000000..2a4eaab --- /dev/null +++ b/skills/local-worker-handoff/scripts/worker.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Run a prompt as a headless Claude Code worker on a locally hosted model. +# Backend details live in ~/.claude/local-workers.json (override: LOCAL_WORKERS_CONFIG), +# never in this skill or in callers. +# +# worker.sh list # configured backends +# worker.sh check [backend] # exit 0 if reachable + model served +# worker.sh run [--backend B] --prompt-file F --out O [--cwd DIR] +# [--allow "Read Grep Glob Bash(bash /x/y.sh:*)"] [--max-turns N] +# Runs `claude -p` against the backend. Writes the final JSON result to O, +# prints the worker's final text, exits non-zero if the worker errored. +set -euo pipefail +CFG="${LOCAL_WORKERS_CONFIG:-$HOME/.claude/local-workers.json}" +die() { echo "worker.sh: $*" >&2; exit 2; } +[ -f "$CFG" ] || die "no config at $CFG — no local backend configured (callers should fall back to built-in subagents)" + +# Prints: base_url \t model \t key_file \t max_parallel +backend() { + python3 -I - "$CFG" "${1:-}" <<'EOF' +import json, os, sys +c = json.load(open(sys.argv[1])); name = sys.argv[2] or c.get("default") +b = c.get("backends", {}).get(name) +if not b: sys.exit(f"unknown backend {name!r}; have {list(c.get('backends', {}))}") +print("\t".join([b["base_url"].rstrip("/"), b["model"], os.path.expanduser(b.get("api_key_file", "")), str(b.get("max_parallel", 1))])) +EOF +} + +cmd_list() { python3 -I -c 'import json,sys; c=json.load(open(sys.argv[1])); [print(("* " if k==c.get("default") else " ")+k, "-", v["model"], "@", v["base_url"], "max_parallel="+str(v.get("max_parallel",1))) for k,v in c["backends"].items()]' "$CFG"; } + +cmd_check() { + IFS=$'\t' read -r url model keyf par < <(backend "${1:-}") || die "bad backend" + local key=""; [ -n "$keyf" ] && [ -f "$keyf" ] && key="$(cat "$keyf")" + local models; models=$(curl -sf -m 4 -H "Authorization: Bearer $key" "$url/v1/models" 2>/dev/null) \ + || { echo "UNREACHABLE: $url"; exit 1; } + printf '%s' "$models" | grep -q "\"$model\"" || { echo "REACHABLE but model '$model' not served at $url"; exit 1; } + echo "OK: $model @ $url (max_parallel=$par)" +} + +cmd_run() { + local be="" pf="" out="" cwd="$PWD" allow="Read Grep Glob" turns=200 + while [ $# -gt 0 ]; do case "$1" in + --backend) be="$2"; shift 2;; --prompt-file) pf="$2"; shift 2;; --out) out="$2"; shift 2;; + --cwd) cwd="$2"; shift 2;; --allow) allow="$2"; shift 2;; --max-turns) turns="$2"; shift 2;; + *) die "unknown arg $1";; esac; done + [ -f "$pf" ] || die "--prompt-file required"; [ -n "$out" ] || die "--out required" + IFS=$'\t' read -r url model keyf par < <(backend "$be") || die "bad backend" + local key=""; [ -n "$keyf" ] && [ -f "$keyf" ] && key="$(cat "$keyf")" + # shellcheck disable=SC2086 + ( cd "$cwd" && env \ + ANTHROPIC_BASE_URL="$url" ANTHROPIC_AUTH_TOKEN="${key:-none}" ANTHROPIC_API_KEY= \ + ANTHROPIC_MODEL="$model" ANTHROPIC_DEFAULT_HAIKU_MODEL="$model" ANTHROPIC_DEFAULT_SONNET_MODEL="$model" \ + ANTHROPIC_DEFAULT_OPUS_MODEL="$model" CLAUDE_CODE_SUBAGENT_MODEL="$model" \ + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \ + claude -p "$(cat "$pf")" --output-format json --strict-mcp-config --max-turns "$turns" \ + --allowedTools $allow --disallowedTools "Agent Write Edit WebFetch WebSearch" \ + 2>"$out.stderr" ) | grep '^{' > "$out" || true + [ -s "$out" ] || { echo "worker produced no result; see $out.stderr" >&2; exit 1; } + python3 -I -c ' +import json,sys; d=json.load(open(sys.argv[1])) +print(d.get("result") or "") +print("[worker] turns=%s is_error=%s model=%s" % (d.get("num_turns"), d.get("is_error"), list((d.get("modelUsage") or {}).keys())), file=sys.stderr) +sys.exit(1 if d.get("is_error") else 0)' "$out" +} + +sub="${1:-}"; shift || true +case "$sub" in list) cmd_list;; check) cmd_check "$@";; run) cmd_run "$@";; *) sed -n '2,12p' "$0"; exit 2;; esac diff --git a/skills/scaffold-new-android-project/SKILL.md b/skills/scaffold-new-android-project/SKILL.md index b30bf4e..200a0c7 100644 --- a/skills/scaffold-new-android-project/SKILL.md +++ b/skills/scaffold-new-android-project/SKILL.md @@ -22,11 +22,11 @@ It checks JDK (needs 17+), the Android SDK (ANDROID_HOME / ANDROID_SDK_ROOT / co ## Step 2 — Pick compatible versions -The single most common failure is an incompatible **AGP ↔ Gradle ↔ Kotlin** triple, or using APIs from the wrong AGP major. Before scaffolding: +The single most common failure is an incompatible **AGP ↔ Gradle ↔ Kotlin** triple. Before scaffolding: 1. Note what's actually available: the doctor lists installed `platforms` (→ `compileSdk`) and any cached Gradle distributions. 2. If the user specified versions, use them. Otherwise pick a known-good triple and confirm against the AGP release notes (AGP's "Compatible Gradle/Kotlin" table) — **check, don't guess from memory.** -3. **Know the AGP major.** AGP 8.x: apply `org.jetbrains.kotlin.android`, use `kotlinOptions`, `packagingOptions`. AGP 9.x: Kotlin is **built in** (do NOT apply `kotlin.android`), use `kotlin { compilerOptions { … } }` and `packaging {}`. The default `scaffold.sh` template targets AGP 8.x — if the user wants AGP 9, adjust the generated `app/build.gradle.kts` accordingly and drop the `kotlin-android` plugin. +3. The default `scaffold.sh` template targets **AGP 9** with Kotlin built in (no `kotlin-android` plugin needed). If the user explicitly asks for AGP 8.x instead, adjust accordingly: apply `org.jetbrains.kotlin.android`, use `kotlinOptions`, and downgrade Gradle to ≥8.10. 4. Compose needs the Compose compiler plugin (`org.jetbrains.kotlin.plugin.compose`) for Kotlin 2.0+; the template already wires it. ## Step 3 — Generate the skeleton diff --git a/skills/scaffold-new-android-project/scripts/scaffold.sh b/skills/scaffold-new-android-project/scripts/scaffold.sh index 7c8625e..a1d45c4 100755 --- a/skills/scaffold-new-android-project/scripts/scaffold.sh +++ b/skills/scaffold-new-android-project/scripts/scaffold.sh @@ -5,7 +5,7 @@ # Usage: # scaffold.sh --dir <path> --package <com.foo.bar> [--name "App"] \ # [--compile-sdk 34] [--min-sdk 24] [--target-sdk 34] \ -# [--gradle-version 9.4.1] [--agp 8.5.2] [--kotlin 2.0.20] +# [--gradle-version 9.5] [--agp 9.0.0] [--kotlin 2.1.0] set -euo pipefail DIR="" ; PKG="" ; NAME="My App" @@ -30,10 +30,10 @@ esac; done [ -n "$TARGET_SDK" ] || TARGET_SDK="$COMPILE_SDK" # --- version defaults: KEEP THIS TABLE CURRENT. AGP<->Gradle<->Kotlin must be compatible. --- -# The caller (the model running the skill) should override these after checking release notes. -[ -n "$GRADLE_VER" ] || GRADLE_VER="8.9" -[ -n "$AGP" ] || AGP="8.5.2" -[ -n "$KOTLIN" ] || KOTLIN="2.0.20" +# AGP 9 has Kotlin built in — no kotlin-android plugin needed. +[ -n "$GRADLE_VER" ] || GRADLE_VER="9.4.1" +[ -n "$AGP" ] || AGP="9.2.1" +[ -n "$KOTLIN" ] || KOTLIN="2.2.10" echo ">> Scaffolding $PKG at $DIR (compileSdk=$COMPILE_SDK, AGP=$AGP, Gradle=$GRADLE_VER, Kotlin=$KOTLIN)" @@ -75,7 +75,6 @@ junit = { group = "junit", name = "junit", version.ref = "junit" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } -kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } EOF @@ -83,7 +82,6 @@ EOF cat > "$DIR/build.gradle.kts" <<EOF plugins { alias(libs.plugins.android.application) apply false - alias(libs.plugins.kotlin.android) apply false alias(libs.plugins.kotlin.compose) apply false } EOF @@ -92,7 +90,6 @@ EOF cat > "$DIR/app/build.gradle.kts" <<EOF plugins { alias(libs.plugins.android.application) - alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.compose) } @@ -119,7 +116,11 @@ android { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } - kotlinOptions { jvmTarget = "17" } + kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) + } + } buildFeatures { compose = true } }