Compare commits
No commits in common. "204cb13d601ef8644a6a33979f9fbbdda0422195" and "216cf3478dabeb9dd898041e6cc3b3cfab8ccbe2" have entirely different histories.
204cb13d60
...
216cf3478d
89 changed files with 12 additions and 4162 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
|
|
@ -1,128 +0,0 @@
|
||||||
---
|
|
||||||
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, how modules interact and pass data to each other (grouped into user-facing and background interactions), 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, a module interaction map 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:
|
|
||||||
|
|
||||||
```
|
|
||||||
<AUDIT_DIR>/
|
|
||||||
ledger.tsv every in-scope file + status (pending/contributed/redundant/trivial/skipped)
|
|
||||||
library/<cat>.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 <name>` 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 `<project>/.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 <project> rev-parse --short HEAD`) for the report header.
|
|
||||||
|
|
||||||
## Phase 1 — Inventory
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash $A init <project> <AUDIT_DIR> # builds ledger + empty library docs; prints counts by module/kind
|
|
||||||
bash $A tree <AUDIT_DIR> # module → source set → package tree with file counts
|
|
||||||
bash $A signals <AUDIT_DIR> # 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 <category>`.
|
|
||||||
|
|
||||||
**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 <project>` 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 <category> "<what you looked for>"`, so the report can say "None found in code" with evidence of looking.
|
|
||||||
- `module-interactions`: close the gaps the per-file pass leaves. For every `project(":…")` edge in the module graph (Phase 2), check that at least one interaction entry explains what that dependency is used for; read the files needed to fill any missing edge. Confirm or correct "Inferred:" callee sides with a refinement. In a single-module app, do the same across top-level feature/layer packages. If the app really is one undivided unit, record `none` saying so.
|
|
||||||
- `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, **module interactions** (user-facing and background tables of From → To | Mechanism | Data passed | Trigger, plus a diagram), 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`.
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
# 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/<category>.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 module-interactions 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} <category> <kebab-slug> <path> "<Short title>" <<'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} <category> <slug> <path>` 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-<name>`) 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. **Module interactions:** if the file calls into, exposes an API to, or exchanges data with **another module** (see the orientation summary's module list; in a single-module app, another top-level feature/layer package), record it under `module-interactions`. Slug names the edge and purpose: `<from>-to-<to>-<purpose>`, e.g. `feature-home-to-core-data-load-feed`, `sync-worker-to-core-network-refresh`. Body:
|
|
||||||
```
|
|
||||||
- **Kind:** user-facing | background
|
|
||||||
- **From → To:** `:feature:home` `HomeViewModel.load()` (`path:line`) → `:core:data` `FeedRepository.feed()`
|
|
||||||
- **Mechanism:** e.g. injected interface returning `Flow<List<FeedItem>>`
|
|
||||||
- **Data passed:** request types → result/stream types; where mapping happens
|
|
||||||
- **Trigger:** e.g. screen open, pull-to-refresh, periodic WorkManager job
|
|
||||||
```
|
|
||||||
`user-facing` = started by a user action or feeding what's on screen; `background` = no user waiting (workers, services, receivers, push, alarms, startup init). If the same edge is used by both, record two entries. Record the side you can see; if the other side is outside your batch, name the expected callee path and mark it "Inferred:" until confirmed. A file that merely repeats a known edge gets `also`.
|
|
||||||
6. 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} <path> <status> "<short note>"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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).
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
# 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
|
|
||||||
# <App name> — Architecture Audit
|
|
||||||
_Audited <date> from source at <project path> (<git short SHA if available>). 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. Module interactions
|
|
||||||
How modules call each other and what data crosses each boundary, from `library/module-interactions.md` (prevalence from `occurrences.tsv`). In a single-module app, use top-level feature/layer packages as the units and say so.
|
|
||||||
|
|
||||||
### 7.1 User-facing interactions
|
|
||||||
Started by a user action or feeding what's on screen. Group rows by feature (matching §5) when there are more than ~10.
|
|
||||||
|
|
||||||
| From → To | Purpose | Mechanism | Data passed (in → out) | Trigger | Code pointers |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `:feature:home` → `:core:data` | Load the feed | Injected `FeedRepository`, collected as `Flow` | `—` → `Flow<List<FeedItem>>` (entity → domain mapped in `:core:data`) | Screen open, pull-to-refresh | `feature/home/.../HomeViewModel.kt:42`, `core/data/.../FeedRepositoryImpl.kt` |
|
|
||||||
| `:feature:home` → `:feature:detail` | Open an item | Nav route with args | `itemId: String` | Tap on item | `feature/home/.../HomeNavigation.kt` |
|
|
||||||
|
|
||||||
### 7.2 Background interactions
|
|
||||||
No user waiting: workers, services, receivers, push, alarms, startup init, observers of shared storage.
|
|
||||||
|
|
||||||
| From → To | Purpose | Mechanism | Data passed (in → out) | Trigger | Code pointers |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `:sync` → `:core:network` → `:core:database` | Refresh cache | `CoroutineWorker` calls API, writes Room | `SyncRequest` → `List<FeedDto>` → `FeedEntity` rows | Periodic WorkManager, 6h, unmetered | `sync/.../SyncWorker.kt` |
|
|
||||||
|
|
||||||
### 7.3 Interaction map
|
|
||||||
A Mermaid `graph LR` of modules, with edges labelled by purpose and data type. Draw user-facing edges solid (`-->`) and background edges dashed (`-.->`). Keep it to the edges in the tables. If there are more than ~25, draw one diagram per group.
|
|
||||||
|
|
||||||
### 7.4 Notes
|
|
||||||
- Shared state reached through more than one path (e.g. a Room table written by a worker and observed by a screen): say which module owns it.
|
|
||||||
- Module dependencies that no interaction uses (possibly dead), and layer violations, with paths.
|
|
||||||
|
|
||||||
## 8. Observations
|
|
||||||
- **Inconsistencies / migrations in progress** (two ways of doing the same thing, with counts).
|
|
||||||
- **Risks & tech debt** (with paths).
|
|
||||||
- **Strengths** worth preserving.
|
|
||||||
|
|
||||||
## 9. 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/`.
|
|
||||||
|
|
||||||
## 10. 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 two Module interactions tables (or their first ~10 rows each, if long), the top 3–5 observations, the duration and token total row from §10, and the path to `REPORT.md`.
|
|
||||||
|
|
@ -1,365 +0,0 @@
|
||||||
#!/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 <project-dir> <audit-dir> # inventory + library skeleton
|
|
||||||
# audit.sh tree <audit-dir> # package/file-tree organization view
|
|
||||||
# audit.sh signals <audit-dir> # import-based library hints (NOT evidence)
|
|
||||||
# audit.sh batch <audit-dir> [size] # split pending files into batches
|
|
||||||
# audit.sh next <audit-dir> [n] # next n pending files (single-agent mode)
|
|
||||||
# audit.sh patterns <audit-dir> [category] # pattern slugs already documented (+ counts)
|
|
||||||
# audit.sh finding <audit-dir> <category> <slug> <source-path|(project)> ["<title>"] # 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 module-interactions 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
|
|
||||||
# A workspace from an older skill version may lack a newer category's doc: seed it from the template.
|
|
||||||
[ -f "$f" ] || cp "$TEMPLATES/library/$cat.md" "$f"
|
|
||||||
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
|
|
||||||
|
|
@ -1,133 +0,0 @@
|
||||||
#!/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()
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,18 +0,0 @@
|
||||||
# Module Interactions
|
|
||||||
|
|
||||||
> 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 modules call into each other and what data crosses each boundary. One entry per interaction (a caller module → callee module edge for one purpose), not per mechanism. "Module" means a Gradle module; in a single-module app, use the top-level feature/layer packages as the units instead.
|
|
||||||
|
|
||||||
**Each entry states:**
|
|
||||||
- **Kind:** `user-facing` (triggered by a user action or feeding something on screen: a tap, a screen load, navigation, a deep link) or `background` (runs with no user on the other end: WorkManager/JobScheduler, services, receivers, sync, push, alarms, app startup init, DB/cache observers).
|
|
||||||
- **From → To:** caller module and callee module, with the class/function on each side (`path:line`).
|
|
||||||
- **Mechanism:** direct call through an interface, suspend function, Flow/StateFlow/LiveData stream, callback, navigation route/args, Intent/PendingIntent extras, WorkManager `Data`, broadcast, shared DB table/DataStore key observed by both sides, event bus, DI-provided binding.
|
|
||||||
- **Data passed:** the concrete types in each direction (request args → result/stream type), and where it is mapped (DTO → entity → domain → UiState).
|
|
||||||
- **Trigger:** what starts it (user action, lifecycle event, schedule, push, connectivity, other interaction).
|
|
||||||
|
|
||||||
**Look for:** imports of another module's package; constructor-injected interfaces implemented in another module; `@Binds`/`@Provides` that bind an interface in one module to an implementation in another; nav routes and arguments crossing feature modules; Workers/Services calling repositories; repositories exposing Flows that UI modules collect; shared Room tables or DataStore keys written in one module and read in another; Intents/PendingIntents built in one module and handled in another; layer violations (UI module importing data-layer internals).
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
---
|
|
||||||
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.
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
#!/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
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
---
|
---
|
||||||
name: android-project-scaffold-new
|
name: scaffold-new-android-project
|
||||||
description: Scaffold a new Android project from scratch. Use when the user wants to start/create/bootstrap a new Android app, set up an Android project skeleton, or verify their Android dev environment (SDK, JDK, Gradle) before building. Verifies tooling, picks compatible AGP/Gradle/Kotlin versions, and produces a minimal Kotlin+Compose skeleton that `./gradlew build` passes before any feature work begins.
|
description: Scaffold a new Android project from scratch. Use when the user wants to start/create/bootstrap a new Android app, set up an Android project skeleton, or verify their Android dev environment (SDK, JDK, Gradle) before building. Verifies tooling, picks compatible AGP/Gradle/Kotlin versions, and produces a minimal Kotlin+Compose skeleton that `./gradlew build` passes before any feature work begins.
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -22,11 +22,11 @@ It checks JDK (needs 17+), the Android SDK (ANDROID_HOME / ANDROID_SDK_ROOT / co
|
||||||
|
|
||||||
## Step 2 — Pick compatible versions
|
## Step 2 — Pick compatible versions
|
||||||
|
|
||||||
The single most common failure is an incompatible **AGP ↔ Gradle ↔ Kotlin** triple. Before scaffolding:
|
The single most common failure is an incompatible **AGP ↔ Gradle ↔ Kotlin** triple, or using APIs from the wrong AGP major. Before scaffolding:
|
||||||
|
|
||||||
1. Note what's actually available: the doctor lists installed `platforms` (→ `compileSdk`) and any cached Gradle distributions.
|
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.**
|
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. 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.
|
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.
|
||||||
4. Compose needs the Compose compiler plugin (`org.jetbrains.kotlin.plugin.compose`) for Kotlin 2.0+; the template already wires it.
|
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
|
## Step 3 — Generate the skeleton
|
||||||
|
|
@ -5,7 +5,7 @@
|
||||||
# Usage:
|
# Usage:
|
||||||
# scaffold.sh --dir <path> --package <com.foo.bar> [--name "App"] \
|
# scaffold.sh --dir <path> --package <com.foo.bar> [--name "App"] \
|
||||||
# [--compile-sdk 34] [--min-sdk 24] [--target-sdk 34] \
|
# [--compile-sdk 34] [--min-sdk 24] [--target-sdk 34] \
|
||||||
# [--gradle-version 9.5] [--agp 9.0.0] [--kotlin 2.1.0]
|
# [--gradle-version 9.4.1] [--agp 8.5.2] [--kotlin 2.0.20]
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
DIR="" ; PKG="" ; NAME="My App"
|
DIR="" ; PKG="" ; NAME="My App"
|
||||||
|
|
@ -30,10 +30,10 @@ esac; done
|
||||||
[ -n "$TARGET_SDK" ] || TARGET_SDK="$COMPILE_SDK"
|
[ -n "$TARGET_SDK" ] || TARGET_SDK="$COMPILE_SDK"
|
||||||
|
|
||||||
# --- version defaults: KEEP THIS TABLE CURRENT. AGP<->Gradle<->Kotlin must be compatible. ---
|
# --- version defaults: KEEP THIS TABLE CURRENT. AGP<->Gradle<->Kotlin must be compatible. ---
|
||||||
# AGP 9 has Kotlin built in — no kotlin-android plugin needed.
|
# The caller (the model running the skill) should override these after checking release notes.
|
||||||
[ -n "$GRADLE_VER" ] || GRADLE_VER="9.4.1"
|
[ -n "$GRADLE_VER" ] || GRADLE_VER="8.9"
|
||||||
[ -n "$AGP" ] || AGP="9.2.1"
|
[ -n "$AGP" ] || AGP="8.5.2"
|
||||||
[ -n "$KOTLIN" ] || KOTLIN="2.2.10"
|
[ -n "$KOTLIN" ] || KOTLIN="2.0.20"
|
||||||
|
|
||||||
echo ">> Scaffolding $PKG at $DIR (compileSdk=$COMPILE_SDK, AGP=$AGP, Gradle=$GRADLE_VER, Kotlin=$KOTLIN)"
|
echo ">> Scaffolding $PKG at $DIR (compileSdk=$COMPILE_SDK, AGP=$AGP, Gradle=$GRADLE_VER, Kotlin=$KOTLIN)"
|
||||||
|
|
||||||
|
|
@ -75,6 +75,7 @@ junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
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" }
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
|
|
@ -82,6 +83,7 @@ EOF
|
||||||
cat > "$DIR/build.gradle.kts" <<EOF
|
cat > "$DIR/build.gradle.kts" <<EOF
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application) apply false
|
alias(libs.plugins.android.application) apply false
|
||||||
|
alias(libs.plugins.kotlin.android) apply false
|
||||||
alias(libs.plugins.kotlin.compose) apply false
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
|
|
@ -90,6 +92,7 @@ EOF
|
||||||
cat > "$DIR/app/build.gradle.kts" <<EOF
|
cat > "$DIR/app/build.gradle.kts" <<EOF
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.android)
|
||||||
alias(libs.plugins.kotlin.compose)
|
alias(libs.plugins.kotlin.compose)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -116,11 +119,7 @@ android {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
}
|
}
|
||||||
kotlin {
|
kotlinOptions { jvmTarget = "17" }
|
||||||
compilerOptions {
|
|
||||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
buildFeatures { compose = true }
|
buildFeatures { compose = true }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1,128 +0,0 @@
|
||||||
---
|
|
||||||
name: web-frontend
|
|
||||||
description: House style and build guidance for any web frontend work, so pages and apps come out with a deliberate, polished look and feel instead of generic AI-generated design. Use whenever writing or restyling frontend code — a landing page, marketing site, web app, dashboard, admin tool, component library, or a single component or page in an existing React/Vue/Svelte/plain-HTML project. Provides a token-based design system (color in OKLCH with light/dark themes, type scale, spacing, radius, motion), font pairings, a default library stack, layout patterns, component recipes, copywriting rules and a pre-ship checklist.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Web Frontend
|
|
||||||
|
|
||||||
The aim: frontends that look like a design lead at a small studio made them. That means a specific visual identity grounded in the subject, precise spacing and type, both themes designed, and none of the stock AI-generated looks. The look comes from **process plus a small system**, not a fixed template: the tokens in `assets/tokens.css` are the structure, and each project gets its own hue, fonts and one bold move.
|
|
||||||
|
|
||||||
`SKILL_DIR` is the directory holding this file. Reference files, read when the step needs them:
|
|
||||||
|
|
||||||
| File | Read when |
|
|
||||||
|---|---|
|
|
||||||
| `assets/tokens.css` | Always, before writing styles. Copy it into the project and tune it. |
|
|
||||||
| `references/libraries.md` | Choosing a stack or adding a dependency. |
|
|
||||||
| `references/layout.md` | Building page shells, grids, app layouts, dashboards. |
|
|
||||||
| `references/components.md` | Writing buttons, inputs, cards, tables, nav, toasts, empty states. |
|
|
||||||
| `references/tailwind.md` | The project uses Tailwind (or you are choosing it). |
|
|
||||||
|
|
||||||
## Precedence
|
|
||||||
|
|
||||||
1. The user's own words. If they name a look, follow it exactly, even one listed under "Avoid" below.
|
|
||||||
2. The project's existing design system: a tokens/theme file, Tailwind config, component library, CLAUDE.md. Apply it and fill gaps only. Never re-skin an existing product unasked.
|
|
||||||
3. This skill.
|
|
||||||
|
|
||||||
When the output is a claude.ai Artifact, the `artifact-design` skill's page contract (CSP, skeleton, safe areas) wins over anything here; this skill's taste still applies.
|
|
||||||
|
|
||||||
## Process
|
|
||||||
|
|
||||||
1. **Read the request and pick a treatment.**
|
|
||||||
- *Utilitarian* (internal tool, dashboard, admin, docs, settings, a feature inside an app): polished, quiet, dense where useful. No hero. Flourishes kept to near zero.
|
|
||||||
- *Editorial* (landing page, portfolio, launch page, game, something meant to be shared): an opinionated identity with one real aesthetic risk.
|
|
||||||
- If unsure, choose utilitarian done well. A well-composed page is always acceptable; an over-designed one sometimes isn't.
|
|
||||||
2. **Define the subject.** One concrete subject, its audience, and the page's single job. Pull at least one detail only this subject would have (its units, terms of art, document conventions) into the content itself. Use real copy, never lorem ipsum.
|
|
||||||
3. **Set the tokens.** Copy `assets/tokens.css` and change, at minimum:
|
|
||||||
- `--hue` (and maybe `--chroma`): the accent's hue, chosen from the subject's world. The neutrals pick up a faint tint of it automatically.
|
|
||||||
- `--font-display`, `--font-body`, `--font-mono` from the pairing table below.
|
|
||||||
- A one-line layout-concept comment above `:root` (e.g. `/* Layout: two-pane ledger, filters left, results right */`).
|
|
||||||
Every color, size and space in the code then comes from a token. No hex literals in components.
|
|
||||||
4. **Lay out with the patterns** in `references/layout.md`. Get structure right at phone width (~400px) and desktop before adding detail.
|
|
||||||
5. **Build components** from `references/components.md`, styled only through tokens.
|
|
||||||
6. **Write the copy** by the rules below.
|
|
||||||
7. **Run the checklist** at the end of this file. Render it once if you can (dev server plus a screenshot, or Playwright), fix what you see in one pass, and stop.
|
|
||||||
|
|
||||||
## The system in brief
|
|
||||||
|
|
||||||
Everything below is defined in `assets/tokens.css`.
|
|
||||||
|
|
||||||
- **Color:** OKLCH. One accent hue drives `--accent`, `--accent-fg`, `--accent-soft` and a faintly tinted neutral ramp (`--bg`, `--surface`, `--surface-2`, `--border`, `--fg`, `--fg-muted`, `--fg-subtle`). Semantic colors (`--ok`, `--warn`, `--danger`, `--info`) are separate from the accent and never stand in for it.
|
|
||||||
- **Themes:** light on bare `:root`. Dark redefines the same tokens under `@media (prefers-color-scheme: dark)`, guarded by `:root:not([data-theme="light"])`, and again under `:root[data-theme="dark"]`, so an explicit toggle wins both ways. Dark is designed, not inverted: surfaces get lighter as they rise, the accent gets lighter and a little less saturated, and borders carry more of the separation than shadows do.
|
|
||||||
- **Type:** a modular scale (ratio 1.2 for UI, 1.25 to 1.333 for editorial) from `--text-xs` to `--text-4xl`. Body copy 16px minimum on the web (15px is fine in dense tools). Measure ~65ch. Headings `text-wrap: balance`, paragraphs `text-wrap: pretty`. Uppercase labels get `letter-spacing: 0.06em`. Digits that line up use `tabular-nums`.
|
|
||||||
- **Space:** a 4px base, `--space-1` … `--space-16`. Siblings get spacing from `gap` in flex/grid, not margins.
|
|
||||||
- **Radius:** small and consistent. `--radius-sm` 4px for inputs and chips, `--radius-md` 8px for cards and popovers, `--radius-full` for pills and avatars. Not everything is rounded.
|
|
||||||
- **Elevation:** three shadows only, used by role: a raised card (rarely), a popover/menu, and a modal.
|
|
||||||
- **Motion:** 120 to 200ms with `--ease-out` for UI, one orchestrated moment at most on editorial pages, everything wrapped in `prefers-reduced-motion`.
|
|
||||||
|
|
||||||
## Font pairings
|
|
||||||
|
|
||||||
All on Google Fonts (or self-host with `@fontsource/*`). Always declare a full fallback stack. Pick by the subject's character, not by habit. Avoid the defaults listed under "Avoid".
|
|
||||||
|
|
||||||
| Character | Display | Body | Mono / data |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Precise, technical, product UI | Geist | Geist | Geist Mono |
|
|
||||||
| Warm, humane, consumer | Bricolage Grotesque | Figtree | JetBrains Mono |
|
|
||||||
| Editorial, long-form, cultural | Newsreader | Source Sans 3 | IBM Plex Mono |
|
|
||||||
| Engineered, industrial, data-heavy | IBM Plex Sans Condensed | IBM Plex Sans | IBM Plex Mono |
|
|
||||||
| Playful, crafted, games | Fredoka or Gluten (headings only) | Nunito Sans | Martian Mono |
|
|
||||||
| Luxury, fashion, quiet confidence | Cormorant Garamond | Hanken Grotesk | DM Mono |
|
|
||||||
| Civic, institutional, trustworthy | Public Sans | Public Sans | Roboto Mono |
|
|
||||||
|
|
||||||
Use the display face with restraint: headings and one or two hero moments. For utilitarian work it is fine for display and body to be the same family at different weights.
|
|
||||||
|
|
||||||
## Avoid (the stock AI-generated looks)
|
|
||||||
|
|
||||||
Unless the user asks for them:
|
|
||||||
- Warm cream background (#F4F1EA-ish) with serif display and terracotta accent.
|
|
||||||
- Near-black page with a single acid-green or vermilion pop.
|
|
||||||
- Purple-to-blue gradient hero on white; gradient text on headlines.
|
|
||||||
- Inter or Space Grotesk as the unexamined "safe" face.
|
|
||||||
- Emoji as section icons or bullet markers.
|
|
||||||
- Everything centered; every block a rounded card with the same shadow; an accent bar down the left of rounded cards.
|
|
||||||
- `rounded-2xl` + `shadow-lg` on everything; glassmorphism blur panels.
|
|
||||||
- Numbered `01 / 02 / 03` markers on content that isn't a sequence.
|
|
||||||
- A `100vh` hero that pushes all real content below the fold.
|
|
||||||
- Big-number stat tiles as the opener when the numbers aren't the point.
|
|
||||||
- Fake logos ("Trusted by…") and invented testimonials.
|
|
||||||
|
|
||||||
## Principles that make it look deliberate
|
|
||||||
|
|
||||||
- **One bold move.** Put the boldness in one place (a type treatment, a color field, an interactive hero, a striking grid) and keep everything around it quiet. If the accent fights the background, desaturate it or shift it to an analogous hue.
|
|
||||||
- **Hierarchy through type and space first,** then color, and only then borders and shadows. Card styling marks something as a separate object, so use it by role.
|
|
||||||
- **Consistent repeated elements.** Same padding, baselines and placement across sibling cards, rows and badges. Let content set heights. Pick a column count the items fill evenly.
|
|
||||||
- **Structure encodes information.** Eyebrows, numbering, dividers and labels must say something true about the content.
|
|
||||||
- **Complete at rest.** Everything readable is visible on load. Animations start from a visible state, never `opacity: 0` waiting on a scroll observer. Tools open in a realistic working state with sample data clearly marked as examples, not an empty shell.
|
|
||||||
- **UIs are scanned.** Summary before detail. State shown in form as well as numbers (pill, chip, severity stripe). Interactive things look interactive.
|
|
||||||
- **Charts to scale,** colored from tokens, labels clear of marks, both themes legible. For anything more than a sparkline, load the `dataviz` skill if available.
|
|
||||||
|
|
||||||
## Copy
|
|
||||||
|
|
||||||
- Write from the user's side: name things by what people recognize ("Notifications", not "Webhook config").
|
|
||||||
- Buttons say exactly what happens ("Save changes", "Delete project"), and the confirmation echoes it ("Changes saved").
|
|
||||||
- Errors say what went wrong and how to fix it. No apologies, no vagueness.
|
|
||||||
- Short, direct, plain sentences. No em-dash asides, no "not X but Y", no colon-then-reveal, no scare quotes, no stock phrases ("seamless", "unlock", "elevate", "worth noting").
|
|
||||||
- Sentence case for headings and buttons.
|
|
||||||
- Page `<title>`: a real name for the page, 2 to 4 words, no "– explainer" tail.
|
|
||||||
|
|
||||||
## Accessibility and build hygiene (non-negotiable)
|
|
||||||
|
|
||||||
- Semantic HTML first: `button` for actions, `a` for navigation, real `label`s, landmarks (`header`, `nav`, `main`), one `h1`.
|
|
||||||
- Text contrast at least 4.5:1 (3:1 for large text and UI boundaries) in **both** themes.
|
|
||||||
- Visible `:focus-visible` ring (`--ring` token) on everything focusable. Never `outline: none` without a replacement.
|
|
||||||
- Touch targets at least 40px tall on touch layouts.
|
|
||||||
- `prefers-reduced-motion` respected. No information conveyed by color alone.
|
|
||||||
- `body` always has an explicit background from a token.
|
|
||||||
- No horizontal page scroll at 360px. Wide tables, code and diagrams scroll inside their own `overflow-x: auto` container. Flex/grid children holding text or tables get `min-width: 0`.
|
|
||||||
- Images get `max-width: 100%`, width/height or `aspect-ratio` to avoid layout shift, and real `alt`.
|
|
||||||
|
|
||||||
## Pre-ship checklist
|
|
||||||
|
|
||||||
- [ ] Every color, size, radius and shadow comes from a token; no stray hex or px literals in components.
|
|
||||||
- [ ] Light, dark, and explicit `data-theme` toggling all look right; no text is unreadable in either theme.
|
|
||||||
- [ ] Works at 360px, 768px and 1280px+ with no horizontal scroll.
|
|
||||||
- [ ] One display face used with restraint, a body face, a mono/data face if needed, all with fallbacks.
|
|
||||||
- [ ] Nothing from the "Avoid" list crept in by default.
|
|
||||||
- [ ] Focus states visible, keyboard path works, reduced motion respected.
|
|
||||||
- [ ] Copy follows the rules above; no placeholder text.
|
|
||||||
- [ ] Repeated elements share edges, padding and baselines.
|
|
||||||
- [ ] Empty, loading and error states exist for anything that fetches data.
|
|
||||||
|
|
@ -1,210 +0,0 @@
|
||||||
/* =====================================================================
|
|
||||||
web-frontend design tokens
|
|
||||||
Copy into the project (e.g. src/styles/tokens.css) and tune.
|
|
||||||
Minimum per project: --hue, --chroma, the three font tokens, and the
|
|
||||||
layout-concept comment below. Components use ONLY these tokens.
|
|
||||||
Change --hue/--chroma/--tint on :root itself. Derived tokens are computed
|
|
||||||
where they are declared, so setting --hue on a nested element does NOT
|
|
||||||
re-tint it; for a differently colored section, redeclare the tokens it uses.
|
|
||||||
|
|
||||||
Layout: <one line describing this project's layout concept>
|
|
||||||
===================================================================== */
|
|
||||||
|
|
||||||
:root {
|
|
||||||
/* ---- Identity knobs ------------------------------------------------ */
|
|
||||||
--hue: 250; /* accent hue, 0-360. Pick from the subject's world. */
|
|
||||||
--chroma: 0.15; /* accent saturation. 0.08 muted ... 0.2 vivid. */
|
|
||||||
--tint: 0.012; /* how much the neutrals lean toward --hue. */
|
|
||||||
|
|
||||||
/* ---- Neutrals (light) ---------------------------------------------- */
|
|
||||||
--bg: oklch(0.985 var(--tint) var(--hue));
|
|
||||||
--surface: oklch(1 0 0);
|
|
||||||
--surface-2: oklch(0.965 var(--tint) var(--hue)); /* wells, table headers, code */
|
|
||||||
--border: oklch(0.90 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--border-strong: oklch(0.80 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--fg: oklch(0.22 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--fg-muted: oklch(0.45 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--fg-subtle: oklch(0.60 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
|
|
||||||
/* ---- Accent ---------------------------------------------------------- */
|
|
||||||
--accent: oklch(0.52 var(--chroma) var(--hue));
|
|
||||||
--accent-hover:oklch(0.46 var(--chroma) var(--hue));
|
|
||||||
--accent-fg: oklch(0.99 0.01 var(--hue)); /* text on --accent */
|
|
||||||
--accent-soft: oklch(0.95 calc(var(--chroma) * 0.3) var(--hue)); /* selected rows, chips */
|
|
||||||
--accent-text: oklch(0.45 var(--chroma) var(--hue)); /* links, accent text on --bg */
|
|
||||||
--ring: oklch(0.60 var(--chroma) var(--hue) / 0.55);
|
|
||||||
|
|
||||||
/* ---- Semantic (independent of the accent) ---------------------------- */
|
|
||||||
--ok: oklch(0.55 0.13 150); --ok-soft: oklch(0.95 0.04 150);
|
|
||||||
--warn: oklch(0.68 0.15 75); --warn-soft: oklch(0.96 0.05 85);
|
|
||||||
--danger: oklch(0.55 0.19 25); --danger-soft: oklch(0.95 0.04 25);
|
|
||||||
--info: oklch(0.55 0.12 230); --info-soft: oklch(0.95 0.03 230);
|
|
||||||
|
|
||||||
/* ---- Type ------------------------------------------------------------ */
|
|
||||||
--font-display: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
|
||||||
--font-body: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
|
||||||
--font-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
|
||||||
|
|
||||||
/* Scale: ratio 1.2 (UI). For editorial pages raise the top steps (see comment). */
|
|
||||||
--text-xs: 0.75rem; /* 12 captions, table meta */
|
|
||||||
--text-sm: 0.875rem; /* 14 secondary text, dense UI */
|
|
||||||
--text-base: 1rem; /* 16 body */
|
|
||||||
--text-lg: 1.125rem; /* 18 lead paragraph, card titles */
|
|
||||||
--text-xl: 1.375rem; /* 22 section headings (h3) */
|
|
||||||
--text-2xl: 1.75rem; /* 28 page sections (h2) */
|
|
||||||
--text-3xl: 2.25rem; /* 36 page title (h1) in apps */
|
|
||||||
--text-4xl: clamp(2.5rem, 1.6rem + 3.6vw, 4.5rem); /* editorial hero only */
|
|
||||||
|
|
||||||
--leading-tight: 1.15; /* display, h1-h2 */
|
|
||||||
--leading-snug: 1.3; /* h3-h4, UI labels */
|
|
||||||
--leading-body: 1.6; /* paragraphs */
|
|
||||||
--tracking-tight: -0.02em; /* large display */
|
|
||||||
--tracking-label: 0.06em; /* UPPERCASE labels */
|
|
||||||
--measure: 65ch;
|
|
||||||
|
|
||||||
--weight-regular: 400;
|
|
||||||
--weight-medium: 500;
|
|
||||||
--weight-semibold: 600;
|
|
||||||
--weight-bold: 700;
|
|
||||||
|
|
||||||
/* ---- Space (4px base) ---------------------------------------------- */
|
|
||||||
--space-1: 0.25rem; --space-2: 0.5rem; --space-3: 0.75rem;
|
|
||||||
--space-4: 1rem; --space-5: 1.25rem; --space-6: 1.5rem;
|
|
||||||
--space-8: 2rem; --space-10: 2.5rem; --space-12: 3rem;
|
|
||||||
--space-16: 4rem; --space-24: 6rem;
|
|
||||||
|
|
||||||
--gutter: max(16px, 4vw); /* page side padding, capped by layout */
|
|
||||||
--content-max: 72rem; /* app/site content width */
|
|
||||||
--prose-max: var(--measure);
|
|
||||||
|
|
||||||
/* ---- Shape & elevation -------------------------------------------- */
|
|
||||||
--radius-sm: 4px; /* inputs, chips, small buttons */
|
|
||||||
--radius-md: 8px; /* cards, popovers, buttons */
|
|
||||||
--radius-lg: 14px; /* modals, large media */
|
|
||||||
--radius-full: 999px; /* pills, avatars, toggles */
|
|
||||||
|
|
||||||
--shadow-raised: 0 1px 2px oklch(0.2 0.02 var(--hue) / 0.06), 0 1px 1px oklch(0.2 0.02 var(--hue) / 0.04);
|
|
||||||
--shadow-popover: 0 4px 12px oklch(0.2 0.02 var(--hue) / 0.10), 0 1px 3px oklch(0.2 0.02 var(--hue) / 0.08);
|
|
||||||
--shadow-modal: 0 24px 48px oklch(0.2 0.02 var(--hue) / 0.18), 0 4px 12px oklch(0.2 0.02 var(--hue) / 0.10);
|
|
||||||
|
|
||||||
/* ---- Motion ---------------------------------------------------------- */
|
|
||||||
--ease-out: cubic-bezier(0.2, 0.7, 0.2, 1);
|
|
||||||
--ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);
|
|
||||||
--dur-fast: 120ms; /* hover, press */
|
|
||||||
--dur-base: 180ms; /* menus, toggles */
|
|
||||||
--dur-slow: 320ms; /* modals, page moments */
|
|
||||||
|
|
||||||
/* ---- Layers -------------------------------------------------------- */
|
|
||||||
--z-sticky: 10; --z-dropdown: 20; --z-modal: 40; --z-toast: 50;
|
|
||||||
|
|
||||||
color-scheme: light;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---- Dark: same tokens, redesigned values. Two blocks so an explicit
|
|
||||||
data-theme toggle wins over the OS setting in both directions. ---- */
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
:root:not([data-theme="light"]) {
|
|
||||||
--bg: oklch(0.17 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--surface: oklch(0.21 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--surface-2: oklch(0.245 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--border: oklch(0.30 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--border-strong: oklch(0.40 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--fg: oklch(0.95 calc(var(--tint) * 1) var(--hue));
|
|
||||||
--fg-muted: oklch(0.74 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--fg-subtle: oklch(0.60 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--accent: oklch(0.70 calc(var(--chroma) * 0.85) var(--hue));
|
|
||||||
--accent-hover:oklch(0.76 calc(var(--chroma) * 0.85) var(--hue));
|
|
||||||
--accent-fg: oklch(0.18 0.02 var(--hue));
|
|
||||||
--accent-soft: oklch(0.30 calc(var(--chroma) * 0.4) var(--hue));
|
|
||||||
--accent-text: oklch(0.78 calc(var(--chroma) * 0.8) var(--hue));
|
|
||||||
--ring: oklch(0.72 var(--chroma) var(--hue) / 0.6);
|
|
||||||
--ok: oklch(0.72 0.14 150); --ok-soft: oklch(0.30 0.05 150);
|
|
||||||
--warn: oklch(0.80 0.14 80); --warn-soft: oklch(0.32 0.05 80);
|
|
||||||
--danger: oklch(0.70 0.17 25); --danger-soft: oklch(0.30 0.06 25);
|
|
||||||
--info: oklch(0.72 0.11 230); --info-soft: oklch(0.30 0.05 230);
|
|
||||||
--shadow-raised: 0 1px 2px oklch(0 0 0 / 0.4);
|
|
||||||
--shadow-popover: 0 6px 16px oklch(0 0 0 / 0.45), 0 0 0 1px var(--border);
|
|
||||||
--shadow-modal: 0 24px 56px oklch(0 0 0 / 0.55), 0 0 0 1px var(--border);
|
|
||||||
color-scheme: dark;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
:root[data-theme="dark"] {
|
|
||||||
--bg: oklch(0.17 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--surface: oklch(0.21 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--surface-2: oklch(0.245 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--border: oklch(0.30 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--border-strong: oklch(0.40 calc(var(--tint) * 2) var(--hue));
|
|
||||||
--fg: oklch(0.95 calc(var(--tint) * 1) var(--hue));
|
|
||||||
--fg-muted: oklch(0.74 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--fg-subtle: oklch(0.60 calc(var(--tint) * 1.5) var(--hue));
|
|
||||||
--accent: oklch(0.70 calc(var(--chroma) * 0.85) var(--hue));
|
|
||||||
--accent-hover:oklch(0.76 calc(var(--chroma) * 0.85) var(--hue));
|
|
||||||
--accent-fg: oklch(0.18 0.02 var(--hue));
|
|
||||||
--accent-soft: oklch(0.30 calc(var(--chroma) * 0.4) var(--hue));
|
|
||||||
--accent-text: oklch(0.78 calc(var(--chroma) * 0.8) var(--hue));
|
|
||||||
--ring: oklch(0.72 var(--chroma) var(--hue) / 0.6);
|
|
||||||
--ok: oklch(0.72 0.14 150); --ok-soft: oklch(0.30 0.05 150);
|
|
||||||
--warn: oklch(0.80 0.14 80); --warn-soft: oklch(0.32 0.05 80);
|
|
||||||
--danger: oklch(0.70 0.17 25); --danger-soft: oklch(0.30 0.06 25);
|
|
||||||
--info: oklch(0.72 0.11 230); --info-soft: oklch(0.30 0.05 230);
|
|
||||||
--shadow-raised: 0 1px 2px oklch(0 0 0 / 0.4);
|
|
||||||
--shadow-popover: 0 6px 16px oklch(0 0 0 / 0.45), 0 0 0 1px var(--border);
|
|
||||||
--shadow-modal: 0 24px 56px oklch(0 0 0 / 0.55), 0 0 0 1px var(--border);
|
|
||||||
color-scheme: dark;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =====================================================================
|
|
||||||
Base layer — sensible defaults built on the tokens.
|
|
||||||
===================================================================== */
|
|
||||||
*, *::before, *::after { box-sizing: border-box; }
|
|
||||||
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
background: var(--bg);
|
|
||||||
color: var(--fg);
|
|
||||||
font-family: var(--font-body);
|
|
||||||
font-size: var(--text-base);
|
|
||||||
line-height: var(--leading-body);
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
text-rendering: optimizeLegibility;
|
|
||||||
}
|
|
||||||
h1, h2, h3, h4 {
|
|
||||||
font-family: var(--font-display);
|
|
||||||
line-height: var(--leading-tight);
|
|
||||||
font-weight: var(--weight-semibold);
|
|
||||||
text-wrap: balance;
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
h1 { font-size: var(--text-3xl); letter-spacing: var(--tracking-tight); }
|
|
||||||
h2 { font-size: var(--text-2xl); letter-spacing: -0.01em; }
|
|
||||||
h3 { font-size: var(--text-xl); line-height: var(--leading-snug); }
|
|
||||||
h4 { font-size: var(--text-lg); line-height: var(--leading-snug); }
|
|
||||||
p { margin: 0; text-wrap: pretty; max-width: var(--prose-max); }
|
|
||||||
small, .text-muted { color: var(--fg-muted); }
|
|
||||||
code, kbd, samp, pre { font-family: var(--font-mono); font-size: 0.92em; }
|
|
||||||
a { color: var(--accent-text); text-underline-offset: 0.18em; text-decoration-thickness: 1px; }
|
|
||||||
a:hover { text-decoration-thickness: 2px; }
|
|
||||||
img, svg, video, canvas { display: block; max-width: 100%; height: auto; }
|
|
||||||
input, button, select, textarea { font: inherit; color: inherit; }
|
|
||||||
::selection { background: var(--accent-soft); color: var(--fg); }
|
|
||||||
:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; border-radius: var(--radius-sm); }
|
|
||||||
.label { /* uppercase eyebrow / column label */
|
|
||||||
font-size: var(--text-xs); font-weight: var(--weight-semibold);
|
|
||||||
letter-spacing: var(--tracking-label); text-transform: uppercase; color: var(--fg-muted);
|
|
||||||
}
|
|
||||||
.num { font-variant-numeric: tabular-nums; }
|
|
||||||
[hidden] { display: none !important; }
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
*, *::before, *::after {
|
|
||||||
animation-duration: 0.01ms !important; animation-iteration-count: 1 !important;
|
|
||||||
transition-duration: 0.01ms !important; scroll-behavior: auto !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Editorial pages: widen the top of the scale.
|
|
||||||
:root {
|
|
||||||
--text-xl: 1.5rem; --text-2xl: 2.25rem; --text-3xl: 3rem;
|
|
||||||
--text-4xl: clamp(3rem, 1.5rem + 6vw, 6.5rem);
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
@ -1,113 +0,0 @@
|
||||||
# Components
|
|
||||||
|
|
||||||
Recipes in plain CSS on the tokens. Port them to CSS Modules, Tailwind (`tailwind.md`) or a component library's styling API as the project requires. Every interactive element has hover, active, `:focus-visible` and disabled states.
|
|
||||||
|
|
||||||
## Buttons
|
|
||||||
|
|
||||||
Three variants and two sizes cover almost everything. One primary button per view.
|
|
||||||
|
|
||||||
```css
|
|
||||||
.btn {
|
|
||||||
display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2);
|
|
||||||
height: 2.5rem; padding-inline: var(--space-4);
|
|
||||||
font-size: var(--text-sm); font-weight: var(--weight-medium); line-height: 1;
|
|
||||||
border: 1px solid transparent; border-radius: var(--radius-md); cursor: pointer;
|
|
||||||
transition: background-color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out);
|
|
||||||
}
|
|
||||||
.btn:active { transform: translateY(1px); }
|
|
||||||
.btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
|
|
||||||
.btn-primary { background: var(--accent); color: var(--accent-fg); }
|
|
||||||
.btn-primary:hover { background: var(--accent-hover); }
|
|
||||||
.btn-secondary { background: var(--surface); color: var(--fg); border-color: var(--border-strong); }
|
|
||||||
.btn-secondary:hover { background: var(--surface-2); }
|
|
||||||
.btn-ghost { background: transparent; color: var(--fg-muted); }
|
|
||||||
.btn-ghost:hover { background: var(--surface-2); color: var(--fg); }
|
|
||||||
.btn-danger { background: var(--danger); color: var(--accent-fg); }
|
|
||||||
.btn-sm { height: 2rem; padding-inline: var(--space-3); font-size: var(--text-xs); border-radius: var(--radius-sm); }
|
|
||||||
```
|
|
||||||
Icon-only buttons are square (`width` = `height`) and need `aria-label`.
|
|
||||||
|
|
||||||
## Inputs
|
|
||||||
|
|
||||||
```css
|
|
||||||
.field { display: grid; gap: var(--space-2); }
|
|
||||||
.field > label { font-size: var(--text-sm); font-weight: var(--weight-medium); }
|
|
||||||
.field > .hint { font-size: var(--text-xs); color: var(--fg-muted); }
|
|
||||||
.field > .error { font-size: var(--text-xs); color: var(--danger); display: flex; gap: var(--space-1); }
|
|
||||||
.input {
|
|
||||||
height: 2.5rem; padding-inline: var(--space-3); width: 100%;
|
|
||||||
background: var(--surface); color: var(--fg);
|
|
||||||
border: 1px solid var(--border-strong); border-radius: var(--radius-sm);
|
|
||||||
transition: border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out);
|
|
||||||
}
|
|
||||||
.input::placeholder { color: var(--fg-subtle); }
|
|
||||||
.input:hover { border-color: var(--fg-subtle); }
|
|
||||||
.input:focus-visible { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--ring); }
|
|
||||||
.input[aria-invalid="true"] { border-color: var(--danger); }
|
|
||||||
textarea.input { height: auto; min-height: 6rem; padding-block: var(--space-2); resize: vertical; }
|
|
||||||
```
|
|
||||||
Placeholders show an example value, never the label.
|
|
||||||
|
|
||||||
## Cards and surfaces
|
|
||||||
|
|
||||||
Use a card only when the thing is a separate object (an item in a collection, a self-contained panel). A section of a page is not a card.
|
|
||||||
|
|
||||||
```css
|
|
||||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md); padding: var(--space-5); }
|
|
||||||
.card-interactive { transition: border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out); }
|
|
||||||
.card-interactive:hover { border-color: var(--border-strong); box-shadow: var(--shadow-raised); }
|
|
||||||
.well { background: var(--surface-2); border-radius: var(--radius-md); padding: var(--space-4); }
|
|
||||||
```
|
|
||||||
In a row of cards: same padding, title in the same place, actions pinned to the same edge (`display: flex; flex-direction: column` with `margin-top: auto` on the footer).
|
|
||||||
|
|
||||||
## Badges, pills, status
|
|
||||||
|
|
||||||
```css
|
|
||||||
.badge { display: inline-flex; align-items: center; gap: var(--space-1); height: 1.375rem; padding-inline: var(--space-2);
|
|
||||||
font-size: var(--text-xs); font-weight: var(--weight-medium); border-radius: var(--radius-full);
|
|
||||||
background: var(--surface-2); color: var(--fg-muted); }
|
|
||||||
.badge-ok { background: var(--ok-soft); color: var(--ok); }
|
|
||||||
.badge-warn { background: var(--warn-soft); color: oklch(from var(--warn) calc(l - 0.15) c h); }
|
|
||||||
.badge-danger { background: var(--danger-soft); color: var(--danger); }
|
|
||||||
.badge-accent { background: var(--accent-soft); color: var(--accent-text); }
|
|
||||||
.dot { width: 0.5rem; height: 0.5rem; border-radius: 50%; background: currentColor; }
|
|
||||||
```
|
|
||||||
Status always pairs color with a word or icon.
|
|
||||||
|
|
||||||
## Tables
|
|
||||||
|
|
||||||
```css
|
|
||||||
.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: var(--radius-md); }
|
|
||||||
table { width: 100%; border-collapse: collapse; font-size: var(--text-sm); }
|
|
||||||
th { position: sticky; top: 0; background: var(--surface-2); text-align: left; font-weight: var(--weight-medium);
|
|
||||||
color: var(--fg-muted); padding: var(--space-2) var(--space-3); border-bottom: 1px solid var(--border); white-space: nowrap; }
|
|
||||||
td { padding: var(--space-3); border-bottom: 1px solid var(--border); vertical-align: top; }
|
|
||||||
tr:last-child td { border-bottom: 0; }
|
|
||||||
tbody tr:hover { background: var(--surface-2); }
|
|
||||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
|
||||||
```
|
|
||||||
No zebra stripes and borders together; pick one. Truncate long cells with a tooltip rather than letting a row explode.
|
|
||||||
|
|
||||||
## Navigation
|
|
||||||
|
|
||||||
- Top nav: logo/name left, 3 to 6 links, one action right. Active link marked by weight or color plus `aria-current="page"`, not just an underline that is hard to see.
|
|
||||||
- Side nav: items 2.25rem tall, icon + label, active item `background: var(--accent-soft); color: var(--accent-text)`. Group headings use `.label`.
|
|
||||||
- Tabs: underline style (2px `--accent` bar under the active tab) for page sections; segmented control (pill group on `--surface-2`) for view switches.
|
|
||||||
|
|
||||||
## Overlays
|
|
||||||
|
|
||||||
- Popovers/menus: `--surface`, `--shadow-popover`, `--radius-md`, 4px inner padding, items 2rem tall. Animate opacity + 4px translate in `--dur-base`.
|
|
||||||
- Modals: max-width 32rem (forms) or 48rem (content), `--shadow-modal`, `--radius-lg`, backdrop `oklch(0 0 0 / 0.4)`. Focus trapped, Escape closes, title in an `h2`. Use the native `<dialog>` or Radix Dialog.
|
|
||||||
- Toasts: bottom-right on desktop, bottom-center on phones; short past-tense message ("Invoice sent"); an Undo action for destructive operations instead of a confirm dialog where possible.
|
|
||||||
|
|
||||||
## States
|
|
||||||
|
|
||||||
- **Loading:** skeletons shaped like the real content (`--surface-2` blocks with a subtle shimmer that stops under reduced motion) for page loads; inline spinners only inside buttons.
|
|
||||||
- **Empty:** say what will appear here and how to add the first one, with the primary action. A small icon at most, no large illustration unless the product has an illustration style.
|
|
||||||
- **Error:** what failed, why if known, and a retry. Keep the rest of the page usable.
|
|
||||||
|
|
||||||
## Data display details
|
|
||||||
|
|
||||||
- Numbers: `tabular-nums`, right-aligned in columns, units in `--fg-muted`, thousands separators via `Intl.NumberFormat`.
|
|
||||||
- Dates: relative for recent ("3 min ago") with the absolute date in a `title`/tooltip; absolute in tables.
|
|
||||||
- Code and IDs: `--font-mono`, `--surface-2` background, copy button on hover.
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
# Layout
|
|
||||||
|
|
||||||
Rules first, then patterns to copy. All values come from `assets/tokens.css`.
|
|
||||||
|
|
||||||
## Rules
|
|
||||||
|
|
||||||
- Spacing between siblings comes from `gap` on a flex/grid parent. Margins only for one-off offsets.
|
|
||||||
- One side gutter, set once on the outer wrapper: `padding-inline: var(--gutter)`. Use `padding-block` for vertical padding so the sides never get zeroed by a shorthand.
|
|
||||||
- Design at ~400px and ~1280px, then check 768px. Rows wrap or stack to one column on phones.
|
|
||||||
- Flex/grid children that hold text, code or tables get `min-width: 0`.
|
|
||||||
- Only tables, code blocks and diagrams may be wider than the screen, each inside an `overflow-x: auto` wrapper.
|
|
||||||
- Size heroes to their content, never `100vh`. For full-screen apps, use `height: 100dvh` on the shell (or `100%` from `html`/`body`), not `100vh`.
|
|
||||||
- Let content set heights. Don't stretch cards over empty space. Choose column counts the items fill.
|
|
||||||
- Left-align by default. Center only short, self-contained things (an empty state, a one-line hero on a launch page).
|
|
||||||
- Vertical rhythm: inside a component `--space-2` to `--space-4`; between components `--space-6` to `--space-8`; between page sections `--space-12` to `--space-24`.
|
|
||||||
|
|
||||||
## Page container
|
|
||||||
|
|
||||||
```css
|
|
||||||
.page { padding-inline: var(--gutter); padding-block: var(--space-8) var(--space-16); }
|
|
||||||
.container { max-width: var(--content-max); margin-inline: auto; }
|
|
||||||
.prose { max-width: var(--prose-max); }
|
|
||||||
.stack { display: flex; flex-direction: column; gap: var(--stack-gap, var(--space-4)); }
|
|
||||||
.cluster { display: flex; flex-wrap: wrap; align-items: center; gap: var(--cluster-gap, var(--space-3)); }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Auto-fitting grid (cards, galleries)
|
|
||||||
|
|
||||||
```css
|
|
||||||
.grid-auto {
|
|
||||||
display: grid; gap: var(--space-6);
|
|
||||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 18rem), 1fr));
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Sidebar + content (docs, settings)
|
|
||||||
|
|
||||||
```css
|
|
||||||
.with-sidebar { display: grid; gap: var(--space-8); grid-template-columns: 1fr; }
|
|
||||||
@media (min-width: 900px) { .with-sidebar { grid-template-columns: 15rem minmax(0, 1fr); } }
|
|
||||||
.with-sidebar > aside { position: sticky; top: var(--space-6); align-self: start; }
|
|
||||||
```
|
|
||||||
|
|
||||||
## App shell (tools, dashboards)
|
|
||||||
|
|
||||||
```css
|
|
||||||
.app { display: grid; height: 100dvh; grid-template-rows: auto 1fr; grid-template-columns: 1fr; }
|
|
||||||
@media (min-width: 900px) {
|
|
||||||
.app { grid-template-columns: 15rem minmax(0, 1fr); grid-template-areas: "nav top" "nav main"; }
|
|
||||||
.app > nav { grid-area: nav; border-right: 1px solid var(--border); }
|
|
||||||
.app > header { grid-area: top; }
|
|
||||||
.app > main { grid-area: main; }
|
|
||||||
}
|
|
||||||
.app > header { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-3) var(--gutter);
|
|
||||||
border-bottom: 1px solid var(--border); background: var(--bg); position: sticky; top: 0; z-index: var(--z-sticky); }
|
|
||||||
.app > main { overflow: auto; padding: var(--space-6) var(--gutter); }
|
|
||||||
```
|
|
||||||
On phones the nav becomes a top bar with a menu button or a bottom tab bar (max 5 items).
|
|
||||||
|
|
||||||
## Dashboard
|
|
||||||
|
|
||||||
- Order: page title and time range → the 3 to 5 numbers that matter → the main chart → supporting tables.
|
|
||||||
- KPI row: `grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr))`. Each tile shows label, value (`tabular-nums`), change vs. previous period with a semantic color, and optionally a sparkline.
|
|
||||||
- Status shown in form: a colored dot or pill plus a word, never color alone.
|
|
||||||
- Tables: sticky header, right-aligned numbers, muted secondary columns, row hover in `--surface-2`.
|
|
||||||
|
|
||||||
## Editorial / landing page
|
|
||||||
|
|
||||||
- The hero states the thesis: the subject's most characteristic thing (a headline set big, a live demo, a striking image), sized to content.
|
|
||||||
- Break the grid on purpose once: an oversized type moment, a full-bleed band, an asymmetric 7/5 split. Keep the rest on a calm 12-column grid:
|
|
||||||
```css
|
|
||||||
.grid-12 { display: grid; gap: var(--space-6); grid-template-columns: repeat(12, minmax(0, 1fr)); }
|
|
||||||
.span-7 { grid-column: span 7; } .span-5 { grid-column: span 5; }
|
|
||||||
@media (max-width: 800px) { .grid-12 > * { grid-column: 1 / -1; } }
|
|
||||||
```
|
|
||||||
- Full-bleed bands keep the gutter on their inner wrapper, not the band itself.
|
|
||||||
- Section headings are left-aligned with a short lead paragraph. No eyebrow on every section; use one only when it encodes something (a category, a step).
|
|
||||||
- End with one clear call to action, not three.
|
|
||||||
|
|
||||||
## Forms
|
|
||||||
|
|
||||||
- One column. Labels above inputs. Group related fields with a heading, not a box around each.
|
|
||||||
- Inputs width by expected content (a ZIP code field is short), max ~32rem for text fields.
|
|
||||||
- Primary action at the end, left-aligned with the fields; secondary actions as quieter buttons next to it.
|
|
||||||
- Validate on blur and on submit; inline errors under the field in `--danger` with an icon and text.
|
|
||||||
|
|
@ -1,44 +0,0 @@
|
||||||
# Libraries
|
|
||||||
|
|
||||||
Reach for few dependencies, each doing real work. If the project already has a choice for a role, keep it. Install current stable versions (`npm view <pkg> version`). Don't add a library for something CSS or the platform already does well.
|
|
||||||
|
|
||||||
## Pick a base by project type
|
|
||||||
|
|
||||||
| Project | Stack |
|
|
||||||
|---|---|
|
|
||||||
| Static page, single landing page, prototype | Plain HTML + `tokens.css` + a little vanilla JS. No framework. |
|
|
||||||
| Content site, blog, docs, marketing site | **Astro** (static by default, islands where needed). MDX for content. |
|
|
||||||
| Interactive SPA, internal tool, dashboard (no SEO needs) | **Vite + React + TypeScript**. |
|
|
||||||
| Product with SEO, auth, server data, many routes | **Next.js (App Router) + TypeScript**. |
|
|
||||||
| Team already on Vue / Svelte | **Nuxt** or **SvelteKit**; map the roles below to their equivalents. |
|
|
||||||
|
|
||||||
## Roles (React defaults)
|
|
||||||
|
|
||||||
| Role | Default | Notes |
|
|
||||||
|---|---|---|
|
|
||||||
| Styling | `tokens.css` + **CSS Modules** or **Tailwind v4** | Tailwind only with tokens mapped into `@theme` (`tailwind.md`). Never a second color system alongside the tokens. |
|
|
||||||
| Accessible primitives | **Radix UI** primitives (or **shadcn/ui** for copy-in components) | shadcn's stock look is a known AI tell: always restyle it to the tokens (radius, colors, fonts, shadows). |
|
|
||||||
| Icons | **Lucide** (`lucide-react`) | One icon set per project. 16px in dense UI, 20px default, `stroke-width` 1.75. Never emoji as icons. |
|
|
||||||
| Fonts | `@fontsource/<family>` or `next/font/google` | Self-host to avoid layout shift; set `font-display: swap`. |
|
|
||||||
| Routing | Framework router; **TanStack Router** or **React Router** for Vite SPAs | Type-safe routes when available. |
|
|
||||||
| Server state | **TanStack Query** | Caching, retries, loading/error states. Don't hand-roll fetch-in-`useEffect`. |
|
|
||||||
| Client state | React state/context first; **Zustand** when shared state grows | No Redux unless the project has it. |
|
|
||||||
| Forms + validation | **React Hook Form** + **Zod** | Zod schemas double as API types. |
|
|
||||||
| Tables | **TanStack Table** | Headless; style with tokens. |
|
|
||||||
| Charts | **Recharts** for standard charts; **visx** or **D3** for custom | Color from tokens; load the `dataviz` skill if present. |
|
|
||||||
| Motion | CSS transitions first; **Motion** (`motion/react`) for orchestrated sequences, layout and gestures | Always honor reduced motion. |
|
|
||||||
| Toasts | **Sonner** | Restyle to tokens. |
|
|
||||||
| Command palette | **cmdk** | |
|
|
||||||
| Dates | **date-fns** (or `Intl` alone for formatting) | Format with `Intl.DateTimeFormat`/`NumberFormat` for locale-aware output. |
|
|
||||||
| Markdown | **react-markdown** + **remark-gfm** | |
|
|
||||||
| Syntax highlighting | **Shiki** | Pick a theme pair that matches both color themes. |
|
|
||||||
| Testing | **Vitest** + **Testing Library**; **Playwright** for e2e and screenshots | Playwright also gives the one rendered check before shipping. |
|
|
||||||
| Lint/format | ESLint (flat config) + Prettier, or **Biome** | Match the project. |
|
|
||||||
|
|
||||||
## Don't reach for
|
|
||||||
|
|
||||||
- Full UI kits with a strong look of their own (Material UI, Ant Design, Chakra default theme, Bootstrap) unless the project already uses one. They fight the tokens.
|
|
||||||
- Animation libraries for hover states.
|
|
||||||
- jQuery, Moment.js, Lodash as a whole (import single functions or use the platform).
|
|
||||||
- CSS-in-JS runtimes (styled-components, Emotion) in new projects. They cost runtime and clash with server components.
|
|
||||||
- Icon fonts.
|
|
||||||
|
|
@ -1,68 +0,0 @@
|
||||||
# Tailwind with the tokens
|
|
||||||
|
|
||||||
Tailwind is fine as long as the tokens stay the single source of truth. Never use Tailwind's stock palette (`bg-blue-600`, `text-gray-500`) in components. Map the tokens into the theme and use only those names.
|
|
||||||
|
|
||||||
## Tailwind v4 (CSS-first config)
|
|
||||||
|
|
||||||
```css
|
|
||||||
/* src/styles/app.css */
|
|
||||||
@import "tailwindcss";
|
|
||||||
@import "./tokens.css"; /* the file from assets/tokens.css */
|
|
||||||
|
|
||||||
/* Explicit toggle. System dark mode needs no variant: the tokens already switch. */
|
|
||||||
@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));
|
|
||||||
|
|
||||||
@theme inline {
|
|
||||||
--color-*: initial; /* drop the stock palette */
|
|
||||||
--color-bg: var(--bg);
|
|
||||||
--color-surface: var(--surface);
|
|
||||||
--color-surface-2: var(--surface-2);
|
|
||||||
--color-border: var(--border);
|
|
||||||
--color-border-strong: var(--border-strong);
|
|
||||||
--color-fg: var(--fg);
|
|
||||||
--color-fg-muted: var(--fg-muted);
|
|
||||||
--color-fg-subtle: var(--fg-subtle);
|
|
||||||
--color-accent: var(--accent);
|
|
||||||
--color-accent-hover: var(--accent-hover);
|
|
||||||
--color-accent-fg: var(--accent-fg);
|
|
||||||
--color-accent-soft: var(--accent-soft);
|
|
||||||
--color-accent-text: var(--accent-text);
|
|
||||||
--color-ring: var(--ring);
|
|
||||||
--color-ok: var(--ok); --color-ok-soft: var(--ok-soft);
|
|
||||||
--color-warn: var(--warn); --color-warn-soft: var(--warn-soft);
|
|
||||||
--color-danger: var(--danger); --color-danger-soft: var(--danger-soft);
|
|
||||||
--color-info: var(--info); --color-info-soft: var(--info-soft);
|
|
||||||
--color-transparent: transparent;
|
|
||||||
--color-current: currentColor;
|
|
||||||
|
|
||||||
/* Names must differ from the token they read, or the variable refers to itself and becomes invalid. */
|
|
||||||
--font-heading: var(--font-display); /* class: font-heading */
|
|
||||||
--font-sans: var(--font-body);
|
|
||||||
--shadow-card: var(--shadow-raised); /* class: shadow-card */
|
|
||||||
--shadow-menu: var(--shadow-popover);
|
|
||||||
--shadow-dialog: var(--shadow-modal);
|
|
||||||
/* --radius-sm/md/lg, --font-mono and --ease-out need no mapping: tokens.css declares them
|
|
||||||
with Tailwind's own names, unlayered, so they override Tailwind's defaults. */
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Because the colors resolve through CSS variables that already switch with the theme, components rarely need `dark:` variants at all: `bg-surface text-fg border-border` is correct in both themes.
|
|
||||||
|
|
||||||
Usage examples:
|
|
||||||
```html
|
|
||||||
<button class="inline-flex h-10 items-center gap-2 rounded-md bg-accent px-4 text-sm font-medium text-accent-fg hover:bg-accent-hover focus-visible:outline-2 focus-visible:outline-ring">Save changes</button>
|
|
||||||
<div class="rounded-md border border-border bg-surface p-5">…</div>
|
|
||||||
<span class="text-xs font-semibold uppercase tracking-[0.06em] text-fg-muted">Revenue</span>
|
|
||||||
```
|
|
||||||
|
|
||||||
## Tailwind v3 projects
|
|
||||||
|
|
||||||
Put the same mapping in `tailwind.config` under `theme.extend.colors` (`bg: 'var(--bg)'`, `fg: 'var(--fg)'`, …), plus `fontFamily`, `borderRadius` and `boxShadow`. Set `darkMode: ['selector', '[data-theme="dark"]']` for the toggle. As in v4, the variables already follow the system theme, so `dark:` classes are rarely needed.
|
|
||||||
|
|
||||||
## Habits to avoid in Tailwind output
|
|
||||||
|
|
||||||
- `rounded-xl shadow-lg` as the default on every container.
|
|
||||||
- `bg-gradient-to-r from-purple-500 to-blue-500` anywhere.
|
|
||||||
- `text-center` on whole sections.
|
|
||||||
- Arbitrary values (`p-[13px]`, `text-[#333]`) instead of tokens.
|
|
||||||
- Very long class strings repeated across files: extract a component instead.
|
|
||||||
|
|
@ -1,129 +0,0 @@
|
||||||
---
|
|
||||||
name: web-project-audit
|
|
||||||
description: Audit-level architecture report for an existing web project (frontend, full-stack or monorepo — React/Next.js, Vue/Nuxt, Svelte/SvelteKit, Astro, Angular, Node backends), 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 a web app is architected — its file/package organization, the libraries and mechanisms behind each implementation category (rendering, routing, styling, state, data fetching, API/backend, persistence, auth, background jobs, etc.) with code pointers, how modules interact and pass data to each other (grouped into user-facing and background interactions), 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, a module interaction map and a features table.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Web Project 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:
|
|
||||||
|
|
||||||
```
|
|
||||||
<AUDIT_DIR>/
|
|
||||||
ledger.tsv every in-scope file + status (pending/contributed/redundant/trivial/skipped)
|
|
||||||
library/<cat>.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 <name>` 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/web-project-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 the top-level `package.json` or backend manifest, or the workspace root of a monorepo). If the user didn't give one, use the cwd if it qualifies; otherwise ask.
|
|
||||||
2. `AUDIT_DIR` defaults to `<project>/.web-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 <project> rev-parse --short HEAD`) for the report header.
|
|
||||||
|
|
||||||
## Phase 1 — Inventory
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash $A init <project> <AUDIT_DIR> # builds ledger + empty library docs; prints counts by module/kind
|
|
||||||
bash $A tree <AUDIT_DIR> # package → top-level area → directory tree with file counts
|
|
||||||
bash $A signals <AUDIT_DIR> # import/dependency hits per library
|
|
||||||
```
|
|
||||||
|
|
||||||
- Modules are directories holding a `package.json` or a backend manifest (`requirements.txt`, `pyproject.toml`, `go.mod`, `Gemfile`, `Cargo.toml`, `composer.json`). Projects with a non-Node backend and no-build frontends (plain ES modules served from `static/`) are in scope.
|
|
||||||
- The inventory includes source (`.ts .tsx .js .jsx .mjs .cjs`), backend code (`.py .go .rb .php .rs .ex .cs`), server templates (Jinja, EJS, Handlebars, ERB), shell scripts and Makefiles, framework components (`.vue .svelte .astro`), styles (`.css .scss .sass .less`), markup (`.html .mdx`), schemas (`.prisma .graphql .sql .proto`, migrations), `package.json` and workspace files, tooling config (`tsconfig`, `*.config.*`, lint/format rc files), infra (Dockerfiles, compose, `vercel.json`, `netlify.toml`, `wrangler.toml`), CI config, and JSON/TOML/YAML data. Each file gets a kind: `build config source component server style markup template schema data test story infra script ci other`. It excludes `node_modules`, build outputs (`dist`, `.next`, `.nuxt`, `.svelte-kit`, `.astro`, `.turbo`, `coverage`…), generated dirs, lockfiles, minified bundles and source maps, `vendor/` directories, Python venvs and caches, images/fonts/media under `public/`/`static/`/`assets/` (counted only; hand-written code there is kept), translated locale files (English kept), and all documentation (listed in `docs.txt` for the optional drift step only).
|
|
||||||
- `secret-files.txt` lists `.env*`, `*.env`, `.npmrc`, `.dev.vars`, keys/certificates and credentials JSON. They are kept out of the ledger. **Never open them.** Record their existence and role from the code that reads them (e.g. "`STRIPE_SECRET_KEY` read via `process.env` in `lib/stripe.ts`") under `auth-security`, and note which variables are exposed to the client bundle (`NEXT_PUBLIC_*`, `VITE_*`, `PUBLIC_*`).
|
|
||||||
- `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 library, an example app, large JSON fixtures or data dumps, a generated API client 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. Root `package.json` and workspace config (`pnpm-workspace.yaml`, `turbo.json`, `nx.json`), root `tsconfig*.json`, and the framework/bundler config (`next.config.*`, `vite.config.*`, `nuxt.config.*`, `svelte.config.*`, `astro.config.*`, `angular.json`).
|
|
||||||
2. Each package's `package.json`: dependencies with versions, scripts, and `workspace:` dependencies on other packages → package graph.
|
|
||||||
3. Entry points: the root layout/`_app`/`App.tsx`/`main.ts`, the router definition or the top of the file-based route tree, middleware (`middleware.ts`, server hooks), and the server entry if there is a backend (`server.ts`, `app.ts`, `src/index.ts`).
|
|
||||||
4. Env handling (`env.ts`, `import.meta.env` usage) and the global stylesheet / theme / Tailwind config.
|
|
||||||
|
|
||||||
Then write a 10–20 line **orientation summary** (packages and what each is for, framework + rendering model, core libraries + versions, architectural style as seen so far, slug names already used; for a single-package app, the top-level feature/layer directories that will be treated as modules). 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 shadcn primitive, the 30th page component with the identical data-loading 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 <category>`.
|
|
||||||
|
|
||||||
**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 package 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 <project>` 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 source and components but only sample styles, stories and JSON data) 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. `tanstack-query-hook` vs `react-query-custom-hook`). 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 <category> "<what you looked for>"`, so the report can say "None found in code" with evidence of looking.
|
|
||||||
- `module-interactions`: close the gaps the per-file pass leaves. For every `workspace:` dependency in the package graph (Phase 2), check that at least one interaction entry explains what it is used for; read the files needed to fill any missing edge. Also check the client → server boundary, external services (payment, email, auth providers, webhooks) and every background entry point (cron, queue worker, webhook, service worker) for an entry. Confirm or correct "Inferred:" callee sides with a refinement. In a single-package app, do the same across the top-level feature/layer directories. If the app really is one undivided unit, record `none` saying so.
|
|
||||||
- `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 (styled-components + Tailwind, SWR + TanStack Query), 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, **module interactions** (user-facing and background tables of From → To | Mechanism | Data passed | Trigger, plus a diagram), 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 Redux, code uses Zustand). 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 `package.json` / the backend manifest (lockfile only to resolve a range). For vendored libraries with no manifest, read only the version banner at the top of each file and say that's where the version came from.
|
|
||||||
- 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`.
|
|
||||||
|
|
@ -1,67 +0,0 @@
|
||||||
# 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 a web 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/<category>.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-tooling file-organization architecture module-interactions routing rendering ui-components styling state-management data-fetching forms-validation api-backend persistence auth-security background-jobs i18n-a11y performance observability testing deployment 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} <category> <kebab-slug> <path> "<Short title>" <<'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: `tanstack-query-hooks`, `prisma-repository`, `nextauth-middleware-guard`, `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} <category> <slug> <path>` only. Do not write prose. This keeps prevalence counts honest without bloating the docs.
|
|
||||||
4. **Features:** if the file is a page, route, layout, API endpoint the UI depends on, email template, background job, or service worker the user experiences, record a `features` entry (slug `feature-<name>`) describing in user language what it lets the user do, the entry-point file, and the URL/route if any. Read the referenced message/i18n strings for labels if needed.
|
|
||||||
5. **Module interactions:** if the file calls into, exposes an API to, or exchanges data with **another module** (see the orientation summary's module list: workspace packages, or in a single-package app the top-level feature/layer directories), record it under `module-interactions`. Slug names the edge and purpose: `<from>-to-<to>-<purpose>`, e.g. `web-to-ui-render-button`, `checkout-page-to-api-create-order`, `cron-to-db-expire-carts`. Body:
|
|
||||||
```
|
|
||||||
- **Kind:** user-facing | background
|
|
||||||
- **From → To:** `apps/web` `CheckoutPage` → `submitOrder()` (`path:line`) → `apps/api` `POST /orders` handler
|
|
||||||
- **Mechanism:** e.g. server action, `fetch` via API client, tRPC procedure, prop/callback, shared store, queue message
|
|
||||||
- **Data passed:** request types → result/stream types; where mapping happens
|
|
||||||
- **Trigger:** e.g. page load, button click, form submit, cron schedule, incoming webhook
|
|
||||||
```
|
|
||||||
`user-facing` = started by a user action or feeding what's on screen (including server work done for a page request); `background` = no user waiting (cron, queue workers, webhooks, service-worker sync/push, revalidation, build-time generation, startup init). If the same edge is used by both, record two entries. Record the side you can see; if the other side is outside your batch, name the expected callee path and mark it "Inferred:" until confirmed. A file that merely repeats a known edge gets `also`.
|
|
||||||
6. 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} <path> <status> "<short note>"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 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 `package.json` (and the lockfile only if needed to resolve a range), never from docs.
|
|
||||||
- Never open `.env*`, `.npmrc`, key/certificate or credentials files (see `secret-files.txt`), and never copy secrets (API keys, tokens, connection strings) 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).
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
# 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
|
|
||||||
# <Project name> — Architecture Audit
|
|
||||||
_Audited <date> from source at <project path> (<git short SHA if available>). 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 product is, the rendering model and framework in one line, styling approach, data layer (client fetching + backend + DB), auth, hosting, package count.
|
|
||||||
|
|
||||||
## 2. Build & toolchain
|
|
||||||
| Item | Value | Source |
|
|
||||||
|---|---|---|
|
|
||||||
| Package manager / workspaces | pnpm 9, Turborepo | `package.json`, `turbo.json` |
|
|
||||||
| Framework / bundler | Next.js 15 (Turbopack dev), React 19 | `apps/web/package.json` |
|
|
||||||
| Language | TypeScript 5.x, `strict: true`, path aliases `@/*` | `tsconfig.json` |
|
|
||||||
| Node / runtime targets | Node 20, edge runtime for middleware | `.nvmrc`, `middleware.ts` |
|
|
||||||
| Lint / format | ESLint flat config + Prettier | … |
|
|
||||||
| Env vars | validated with Zod in `env.ts`; client-exposed: `NEXT_PUBLIC_*` (names only) | … |
|
|
||||||
|
|
||||||
## 3. File tree organization
|
|
||||||
- **Scheme:** e.g. "monorepo: `apps/web` (Next.js app router), `apps/api` (Hono), `packages/ui` (design system), `packages/db` (Drizzle schema); inside `apps/web`, feature folders under `src/features/*`". State whether organization is by feature, by type, or framework-convention, with evidence.
|
|
||||||
- A trimmed tree (packages → key directories, file counts), ≤40 lines, from `audit.sh tree`.
|
|
||||||
- Package dependency direction (Mermaid `graph` or arrow list) if a monorepo.
|
|
||||||
- Naming conventions observed, and notable outliers.
|
|
||||||
|
|
||||||
## 4. Implementation summary
|
|
||||||
| Category | Implementation details | Code pointers |
|
|
||||||
|---|---|---|
|
|
||||||
| Rendering | App Router; RSC by default, 14 client components; ISR on `/blog/*` (`revalidate = 3600`) | `apps/web/src/app/layout.tsx`, `.../blog/[slug]/page.tsx` |
|
|
||||||
| Styling | Tailwind v4 with CSS-variable tokens; dark mode via `data-theme` | `apps/web/src/styles/app.css` |
|
|
||||||
| Data fetching | TanStack Query in client components; server components call `lib/api.ts` directly | … |
|
|
||||||
| … one row per category that has findings: build, architecture, routing, UI components, state, forms, API/backend, persistence, auth/security, background jobs, i18n/a11y, performance, observability, testing, deployment | | |
|
|
||||||
|
|
||||||
Rules: "Implementation details" names concrete libraries/mechanisms (+version when known) and, when a category has competing approaches, lists both with rough prevalence ("TanStack Query in 22 hooks, raw `useEffect` fetch in 5 legacy components"). "Code pointers" = 1–3 exemplar files that best show the category.
|
|
||||||
|
|
||||||
## 5. Features (user perspective)
|
|
||||||
| Feature | What it lets the user do | Entry point |
|
|
||||||
|---|---|---|
|
|
||||||
| Sign in | Sign in with email magic link or GitHub; stays signed in for 30 days | `apps/web/src/app/(auth)/login/page.tsx` |
|
|
||||||
| … | | |
|
|
||||||
|
|
||||||
Include user-perceivable background features (emails, notifications, scheduled reports, offline support, webhooks that change what the user sees). Group by area if > 15 rows.
|
|
||||||
|
|
||||||
## 6. Architecture & data flow
|
|
||||||
- Layering as implemented (page/component → hook/store → API client or server action → handler → service → DB), with one traced example end-to-end citing each file in the chain.
|
|
||||||
- Client/server boundary: what runs where.
|
|
||||||
- State management shape and caching/source of truth (server cache, client cache, URL).
|
|
||||||
- Optional Mermaid diagram.
|
|
||||||
|
|
||||||
## 7. Module interactions
|
|
||||||
How modules call each other and what data crosses each boundary, from `library/module-interactions.md` (prevalence from `occurrences.tsv`). Modules are workspace packages; in a single-package app, use top-level feature/layer directories and say so.
|
|
||||||
|
|
||||||
### 7.1 User-facing interactions
|
|
||||||
Started by a user action or feeding what's on screen, including server work done for a page request. Group rows by feature (matching §5) when there are more than ~10.
|
|
||||||
|
|
||||||
| From → To | Purpose | Mechanism | Data passed (in → out) | Trigger | Code pointers |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `apps/web` checkout page → `apps/api` | Place an order | `fetch` via `lib/api.ts`, Zod-validated both sides | `CreateOrderInput` → `Order` | Submit on checkout form | `apps/web/.../CheckoutForm.tsx:58`, `apps/api/src/routes/orders.ts` |
|
|
||||||
| `apps/web` → `packages/ui` | Render controls | React components + props | `ButtonProps` → JSX | Every render | `packages/ui/src/button.tsx` |
|
|
||||||
|
|
||||||
### 7.2 Background interactions
|
|
||||||
No user waiting: cron, queue workers, webhooks, service-worker sync/push, revalidation, build-time generation, startup init.
|
|
||||||
|
|
||||||
| From → To | Purpose | Mechanism | Data passed (in → out) | Trigger | Code pointers |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| Stripe → `apps/api` → `packages/db` | Mark order paid | Webhook handler, signature verified, Drizzle update | `Stripe.Event` → `orders.status` row | `checkout.session.completed` webhook | `apps/api/src/webhooks/stripe.ts` |
|
|
||||||
|
|
||||||
### 7.3 Interaction map
|
|
||||||
A Mermaid `graph LR` of modules (and external services as distinct nodes), with edges labelled by purpose and data type. Draw user-facing edges solid (`-->`) and background edges dashed (`-.->`). Keep it to the edges in the tables. If there are more than ~25, draw one diagram per group.
|
|
||||||
|
|
||||||
### 7.4 Notes
|
|
||||||
- Shared state reached through more than one path (e.g. a table written by a webhook and read by a page; a store written by two features): say which module owns it.
|
|
||||||
- Package dependencies that no interaction uses (possibly dead), and layer violations (UI importing DB code, server-only code reachable from the client), with paths.
|
|
||||||
|
|
||||||
## 8. Observations
|
|
||||||
- **Inconsistencies / migrations in progress** (two ways of doing the same thing, with counts).
|
|
||||||
- **Risks & tech debt** (with paths): e.g. secrets exposed to the client bundle, unvalidated inputs, missing auth checks, heavy client dependencies.
|
|
||||||
- **Strengths** worth preserving.
|
|
||||||
|
|
||||||
## 9. Coverage & method
|
|
||||||
How many files were in scope, read, and contributed; what was excluded and why (dependencies, build output, generated code, lockfiles, translated locale files, static assets counted not read: `resource-counts.tsv`); how many subagents/batches. Location of the library: `{AUDIT_DIR}/library/`.
|
|
||||||
|
|
||||||
## 10. 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 two Module interactions tables (or their first ~10 rows each, if long), the top 3–5 observations, the duration and token total row from §10, and the path to `REPORT.md`.
|
|
||||||
|
|
@ -1,439 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# web-project-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 <project-dir> <audit-dir> # inventory + library skeleton
|
|
||||||
# audit.sh tree <audit-dir> # package/directory organization view
|
|
||||||
# audit.sh signals <audit-dir> # import/dependency-based library hints (NOT evidence)
|
|
||||||
# audit.sh batch <audit-dir> [size] # split pending files into batches
|
|
||||||
# audit.sh next <audit-dir> [n] # next n pending files (single-agent mode)
|
|
||||||
# audit.sh patterns <audit-dir> [category] # pattern slugs already documented (+ counts)
|
|
||||||
# audit.sh finding <audit-dir> <category> <slug> <source-path|(project)> ["<title>"] # 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-tooling file-organization architecture module-interactions routing rendering ui-components styling state-management data-fetching forms-validation api-backend persistence auth-security background-jobs i18n-a11y performance observability testing deployment 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 package.json or a backend manifest (requirements.txt, pyproject.toml, go.mod, Gemfile, Cargo.toml, composer.json).
|
|
||||||
( cd "$proj" && find . \( -name node_modules -o -name .git -o -name dist -o -name build -o -name out -o -name .next -o -name .nuxt -o -name .output \
|
|
||||||
-o -name .svelte-kit -o -name .astro -o -name .turbo -o -name .vercel -o -name .netlify -o -name coverage -o -name .cache \
|
|
||||||
-o -name .parcel-cache -o -name storybook-static -o -name generated -o -name __generated__ -o -name .idea -o -name .vscode \
|
|
||||||
-o -name vendor -o -name .web-audit -o -name .yarn -o -name .pnpm-store \
|
|
||||||
-o -name .venv -o -name venv -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name target \) -prune -o \
|
|
||||||
\( -name package.json -o -name requirements.txt -o -name pyproject.toml -o -name go.mod -o -name Gemfile -o -name Cargo.toml \
|
|
||||||
-o -name composer.json -o -name deno.json -o -name deno.jsonc \) -print ) \
|
|
||||||
| sed 's#^\./##; s#/\{0,1\}[^/]*$##' | sort -u > "$AUDIT_DIR/modules.txt"
|
|
||||||
[ -s "$AUDIT_DIR/modules.txt" ] || echo "" > "$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 node_modules -o -name .git -o -name dist -o -name build -o -name out -o -name .next -o -name .nuxt -o -name .output \
|
|
||||||
-o -name .svelte-kit -o -name .astro -o -name .turbo -o -name .vercel -o -name .netlify -o -name coverage -o -name .cache \
|
|
||||||
-o -name .parcel-cache -o -name storybook-static -o -name generated -o -name __generated__ -o -name .idea -o -name .vscode \
|
|
||||||
-o -name vendor -o -name .web-audit -o -name .yarn -o -name .pnpm-store \
|
|
||||||
-o -name .venv -o -name venv -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name target -o -name docs -o -name doc \) -prune -o \
|
|
||||||
-type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' -o -name '*.mjs' -o -name '*.cjs' \
|
|
||||||
-o -name '*.vue' -o -name '*.svelte' -o -name '*.astro' -o -name '*.css' -o -name '*.scss' -o -name '*.sass' -o -name '*.less' \
|
|
||||||
-o -name '*.pcss' -o -name '*.html' -o -name '*.mdx' -o -name '*.json' -o -name '*.jsonc' -o -name '*.prisma' -o -name '*.graphql' \
|
|
||||||
-o -name '*.gql' -o -name '*.sql' -o -name '*.proto' -o -name '*.toml' -o -name '*.yml' -o -name '*.yaml' -o -name 'Dockerfile*' \
|
|
||||||
-o -name '.babelrc' -o -name '.eslintrc*' -o -name '.prettierrc*' -o -name '.browserslistrc' -o -name '.nvmrc' -o -name '.node-version' \
|
|
||||||
-o -name 'Procfile' -o -name 'Caddyfile' -o -name 'nginx*.conf' \
|
|
||||||
-o -name '*.py' -o -name '*.go' -o -name '*.rb' -o -name '*.php' -o -name '*.rs' -o -name '*.ex' -o -name '*.exs' -o -name '*.cs' \
|
|
||||||
-o -name '*.sh' -o -name 'Makefile' -o -name 'justfile' -o -name 'requirements*.txt' -o -name 'go.mod' -o -name 'Gemfile' \
|
|
||||||
-o -name '*.jinja' -o -name '*.jinja2' -o -name '*.j2' -o -name '*.hbs' -o -name '*.ejs' -o -name '*.njk' -o -name '*.erb' \) -print ) \
|
|
||||||
| sed 's#^\./##' \
|
|
||||||
| awk '
|
|
||||||
# drop noise: lockfiles, minified/bundled output, source maps, translated locale files.
|
|
||||||
# Hand-written code under public/ or static/ stays: no-build apps serve their whole frontend from there.
|
|
||||||
/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|composer\.lock)$/ { next }
|
|
||||||
/\.min\.(js|css)$/ || /\.map$/ || /\.bundle\.js$/ { next }
|
|
||||||
/(^|\/)(locales?|i18n|lang|translations|messages)\/.*/ { n=split($0,a,"/"); f=a[n]; d=a[n-1]
|
|
||||||
if (f !~ /^en([-_][A-Za-z]+)?\.json$/ && d !~ /^en([-_][A-Za-z]+)?$/ && (f ~ /^[a-z][a-z]([-_][A-Za-z]+)?\.json$/ || d ~ /^[a-z][a-z]([-_][A-Za-z]+)?$/)) next }
|
|
||||||
/\.ya?ml$/ && !/^\.github\// && !/^\.gitlab-ci/ && !/circleci|bitbucket-pipelines|azure-pipelines|docker-compose|compose\.ya?ml|pnpm-workspace|netlify|render\.ya?ml|fly|app\.ya?ml|openapi|swagger/ { 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)"
|
|
||||||
rel=path; if (best!="(root)") rel=substr(path, length(best)+2)
|
|
||||||
ss="-"; if (index(rel, "/")) ss=substr(rel, 1, index(rel, "/")-1)
|
|
||||||
f=path; sub(/.*\//, "", f)
|
|
||||||
k="other"
|
|
||||||
if (f=="package.json" || f ~ /^(pnpm-workspace\.yaml|turbo\.json|nx\.json|lerna\.json|rush\.json|deno\.jsonc?|requirements.*\.txt|pyproject\.toml|go\.mod|Gemfile|Cargo\.toml|composer\.json|Makefile|justfile)$/) k="build"
|
|
||||||
else if (path ~ /^\.github\/|^\.gitlab-ci|circleci|bitbucket-pipelines|azure-pipelines/) k="ci"
|
|
||||||
else if (f ~ /^(Dockerfile.*|docker-compose.*|compose\.ya?ml|Procfile|Caddyfile|nginx.*\.conf|vercel\.json|netlify\.toml|wrangler\.toml|fly\.toml|render\.ya?ml|firebase\.json|app\.ya?ml|serverless\.ya?ml)$/) k="infra"
|
|
||||||
else if (f ~ /^(tsconfig.*|jsconfig.*)\.json$/ || f ~ /\.config\.(js|cjs|mjs|ts|mts|cts|json)$/ || f ~ /^\.(babelrc|eslintrc.*|prettierrc.*|browserslistrc|nvmrc|node-version)$/ || f ~ /^(biome|components|\.?swcrc)\.json$/) k="config"
|
|
||||||
else if (f ~ /\.(test|spec)\.[cm]?[jt]sx?$/ || f ~ /^test_.*\.py$|_test\.(py|go)$|_spec\.rb$/ || path ~ /(^|\/)(__tests__|tests?|e2e|cypress|playwright)\//) k="test"
|
|
||||||
else if (f ~ /\.stories\.[cm]?[jt]sx?$|\.stories\.(mdx|svelte|vue)$/) k="story"
|
|
||||||
else if (f ~ /\.(prisma|graphql|gql|sql|proto)$/ || path ~ /(^|\/)(migrations?|schema)\//) k="schema"
|
|
||||||
else if (f ~ /\.(css|scss|sass|less|pcss)$/) k="style"
|
|
||||||
else if (f ~ /\.(html|mdx)$/) k="markup"
|
|
||||||
else if (f ~ /\.(json|jsonc|toml|ya?ml)$/) k="data"
|
|
||||||
else if (f ~ /\.(vue|svelte|astro)$/) k="component"
|
|
||||||
else if (f ~ /\.(py|go|rb|php|rs|ex|exs|cs)$/) k="server"
|
|
||||||
else if (f ~ /\.sh$/) k="script"
|
|
||||||
else if (f ~ /\.(jinja2?|j2|hbs|ejs|njk|erb)$/) k="template"
|
|
||||||
else if (f ~ /\.[cm]?[jt]sx?$/) k="source"
|
|
||||||
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
|
|
||||||
|
|
||||||
# Static assets: counted, not read.
|
|
||||||
( cd "$proj" && find . \( -name node_modules -o -name .git -o -name dist -o -name build -o -name out -o -name .next -o -name .nuxt -o -name .output \
|
|
||||||
-o -name .svelte-kit -o -name .astro -o -name .turbo -o -name .vercel -o -name .netlify -o -name coverage -o -name .cache \
|
|
||||||
-o -name .parcel-cache -o -name storybook-static -o -name generated -o -name __generated__ -o -name .idea -o -name .vscode \
|
|
||||||
-o -name vendor -o -name .web-audit -o -name .yarn -o -name .pnpm-store \
|
|
||||||
-o -name .venv -o -name venv -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name target \) -prune -o -type f \( -path '*/public/*' -o -path '*/static/*' -o -path '*/assets/*' \) \
|
|
||||||
\( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.gif' -o -iname '*.webp' -o -iname '*.avif' -o -iname '*.svg' -o -iname '*.ico' \
|
|
||||||
-o -iname '*.woff' -o -iname '*.woff2' -o -iname '*.ttf' -o -iname '*.otf' -o -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mp3' -o -iname '*.pdf' \) -print ) \
|
|
||||||
| awk '{ e=$0; sub(/.*\./, "", e); c[tolower(e)]++ } END { for (k in c) printf "%s\t%d\n", k, c[k] }' \
|
|
||||||
| sort > "$AUDIT_DIR/resource-counts.tsv"
|
|
||||||
|
|
||||||
( cd "$proj" && find . \( -name node_modules -o -name .git -o -name dist -o -name build -o -name out -o -name .next -o -name .nuxt -o -name .output \
|
|
||||||
-o -name .svelte-kit -o -name .astro -o -name .turbo -o -name .vercel -o -name .netlify -o -name coverage -o -name .cache \
|
|
||||||
-o -name .parcel-cache -o -name storybook-static -o -name generated -o -name __generated__ -o -name .idea -o -name .vscode \
|
|
||||||
-o -name vendor -o -name .web-audit -o -name .yarn -o -name .pnpm-store \
|
|
||||||
-o -name .venv -o -name venv -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name target \) -prune -o \
|
|
||||||
-type f \( -iname '*.md' -o -iname '*.adoc' -o -iname '*.rst' \) -print ) | sed 's#^\./##' | sort > "$AUDIT_DIR/docs.txt"
|
|
||||||
( cd "$proj" && find . \( -name node_modules -o -name .git -o -name dist -o -name build -o -name out -o -name .next -o -name .nuxt -o -name .output \
|
|
||||||
-o -name .svelte-kit -o -name .astro -o -name .turbo -o -name .vercel -o -name .netlify -o -name coverage -o -name .cache \
|
|
||||||
-o -name .parcel-cache -o -name storybook-static -o -name generated -o -name __generated__ -o -name .idea -o -name .vscode \
|
|
||||||
-o -name vendor -o -name .web-audit -o -name .yarn -o -name .pnpm-store \
|
|
||||||
-o -name .venv -o -name venv -o -name __pycache__ -o -name .pytest_cache -o -name .mypy_cache -o -name target \) -prune -o -type f \( -name '.env' -o -name '.env.*' -o -name '*.env' -o -name '*.pem' -o -name '*.key' \
|
|
||||||
-o -name '*.p12' -o -name '*.pfx' -o -name '.npmrc' -o -name '.yarnrc.yml' -o -name 'credentials*.json' -o -name 'service-account*.json' \
|
|
||||||
-o -name '*-sa.json' -o -name '.dev.vars' -o -name 'secrets.*' \) -print ) | sed 's#^\./##' | sort > "$AUDIT_DIR/secret-files.txt"
|
|
||||||
# Secret-bearing files never enter the ledger.
|
|
||||||
awk -F'\t' -v s="$AUDIT_DIR/secret-files.txt" 'BEGIN{while((getline l<s)>0) S[l]=1} NR==1 || !($6 in S)' "$AUDIT_DIR/ledger.tsv" > "$AUDIT_DIR/ledger.tmp" && mv "$AUDIT_DIR/ledger.tmp" "$AUDIT_DIR/ledger.tsv"
|
|
||||||
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 (dirs with package.json or a backend manifest) =="; sed 's/^$/(root)/; s/^/ /' "$AUDIT_DIR/modules.txt"
|
|
||||||
echo
|
|
||||||
echo "== Directories per module [top-level area] (code files per directory: source/component/server/style/markup/test/story/template) =="
|
|
||||||
awk -F'\t' 'NR>1 && ($4=="source"||$4=="component"||$4=="server"||$4=="style"||$4=="test"||$4=="story"||$4=="markup"||$4=="template") {
|
|
||||||
p=$6; if ($2!="(root)") p=substr(p, length($2)+2); if (index(p, "/")) sub(/\/[^\/]+$/, "", p); else p="."
|
|
||||||
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 "== Static assets (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=="source"||$4=="component"||$4=="server"||$4=="markup"||$4=="template"||$4=="build"||$4=="config"||$4=="test"||$4=="story"||$4=="style"||$4=="infra"||$4=="script") {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'
|
|
||||||
React|from ['"]react['"]|"react":
|
|
||||||
Next.js|from ['"]next/|"next":
|
|
||||||
Remix / React Router framework|@remix-run/|@react-router/|"react-router":
|
|
||||||
Vue|from ['"]vue['"]|\.vue['"]|"vue":
|
|
||||||
Nuxt|"nuxt":|defineNuxtConfig|useFetch\(|useAsyncData\(
|
|
||||||
Svelte / SvelteKit|"svelte":|@sveltejs/kit|\$app/
|
|
||||||
Astro|"astro":|Astro\.props
|
|
||||||
Angular|@angular/core
|
|
||||||
SolidJS|from ['"]solid-js
|
|
||||||
Qwik|@builder\.io/qwik
|
|
||||||
Server components / actions|['"]use server['"]|['"]use client['"]
|
|
||||||
Tailwind CSS|tailwindcss|@tailwind |@import ['"]tailwindcss
|
|
||||||
CSS Modules|\.module\.(css|scss)
|
|
||||||
Sass/SCSS|"sass":|\.scss['"]
|
|
||||||
styled-components / Emotion|styled-components|@emotion/
|
|
||||||
vanilla-extract / Panda / StyleX|@vanilla-extract|@pandacss|@stylexjs
|
|
||||||
Radix / shadcn|@radix-ui/|components\.json|class-variance-authority
|
|
||||||
Headless UI / Ark / React Aria|@headlessui/|@ark-ui/|react-aria
|
|
||||||
MUI / Chakra / Mantine / Ant|@mui/|@chakra-ui/|@mantine/|from ['"]antd
|
|
||||||
Lucide / other icon sets|lucide-|@heroicons/|react-icons|@iconify
|
|
||||||
React Router|from ['"]react-router(-dom)?['"]
|
|
||||||
TanStack Router|@tanstack/react-router
|
|
||||||
Vue Router|vue-router
|
|
||||||
TanStack Query|@tanstack/(react|vue|svelte)-query|react-query
|
|
||||||
SWR|from ['"]swr['"]
|
|
||||||
Apollo / urql / GraphQL|@apollo/client|from ['"]urql|graphql-request|gql`
|
|
||||||
tRPC|@trpc/
|
|
||||||
axios / ky / ofetch|from ['"](axios|ky|ofetch)['"]
|
|
||||||
OpenAPI clients|openapi-fetch|openapi-typescript|@hey-api|orval
|
|
||||||
Redux / RTK|@reduxjs/toolkit|from ['"]redux|react-redux
|
|
||||||
Zustand / Jotai / Valtio|from ['"](zustand|jotai|valtio)
|
|
||||||
Pinia / Vuex|from ['"](pinia|vuex)['"]
|
|
||||||
XState|from ['"]xstate|@xstate/
|
|
||||||
React Hook Form / Formik|react-hook-form|from ['"]formik
|
|
||||||
TanStack Form / Superforms|@tanstack/(react-)?form|sveltekit-superforms
|
|
||||||
Zod / Yup / Valibot|from ['"](zod|yup|valibot)['"]
|
|
||||||
Express / Fastify / Koa|from ['"](express|fastify|koa)['"]|require\(['"](express|fastify|koa)['"]\)
|
|
||||||
Hono / Elysia|from ['"](hono|elysia)
|
|
||||||
NestJS|@nestjs/
|
|
||||||
Route handlers / API routes|export (async )?function (GET|POST|PUT|PATCH|DELETE)|export const (GET|POST)|pages/api/
|
|
||||||
Prisma|@prisma/client|PrismaClient
|
|
||||||
Drizzle|drizzle-orm
|
|
||||||
Kysely / Knex / TypeORM / Sequelize|from ['"](kysely|knex|typeorm|sequelize)
|
|
||||||
Mongoose / MongoDB|from ['"](mongoose|mongodb)['"]
|
|
||||||
Supabase|@supabase/
|
|
||||||
Firebase|from ['"]firebase/|firebase-admin
|
|
||||||
Redis|ioredis|from ['"]redis['"]|@upstash/redis
|
|
||||||
localStorage / IndexedDB|localStorage\.|sessionStorage\.|indexedDB|from ['"](idb|dexie|localforage)
|
|
||||||
Auth.js / NextAuth|next-auth|@auth/
|
|
||||||
Clerk / Auth0 / Lucia / Better Auth|@clerk/|@auth0/|from ['"]lucia|better-auth
|
|
||||||
JWT / sessions / cookies|jsonwebtoken|from ['"]jose['"]|iron-session|cookies\(\)|express-session
|
|
||||||
Background jobs / queues|bullmq|from ['"]bull['"]|inngest|trigger\.dev|@vercel/functions|qstash|graphile-worker|pg-boss
|
|
||||||
Cron / schedules|node-cron|cron-parser|"crons":|scheduled\(|schedule\(
|
|
||||||
Webhooks|webhook|stripe\.webhooks|svix
|
|
||||||
Service worker / PWA|serviceWorker\.register|workbox|vite-plugin-pwa|next-pwa|self\.addEventListener\(['"](fetch|install|push)
|
|
||||||
WebSockets / realtime|new WebSocket|socket\.io|from ['"]ws['"]|pusher|ably|EventSource
|
|
||||||
Stripe / payments|from ['"]stripe|@stripe/
|
|
||||||
i18n|i18next|react-intl|next-intl|vue-i18n|@formatjs|paraglide|lingui
|
|
||||||
Motion / animation|framer-motion|from ['"]motion|gsap|@react-spring|auto-animate
|
|
||||||
Charts / viz|recharts|from ['"]d3|chart\.js|@visx/|echarts|@nivo/|apexcharts
|
|
||||||
3D / canvas|from ['"]three|@react-three/|pixi\.js|konva
|
|
||||||
Dates|date-fns|dayjs|moment|luxon|@internationalized/date
|
|
||||||
Markdown / MDX|react-markdown|@mdx-js|remark-|rehype-|marked|shiki|prismjs
|
|
||||||
Sentry / error tracking|@sentry/|bugsnag|(^|[^A-Za-z])rollbar
|
|
||||||
Analytics|posthog|@vercel/analytics|plausible|@segment/|mixpanel|gtag\(|amplitude
|
|
||||||
Logging|from ['"](pino|winston)['"]|consola
|
|
||||||
Feature flags|launchdarkly|growthbook|@vercel/flags|unleash|flagsmith
|
|
||||||
Vitest|from ['"]vitest['"]|"vitest":
|
|
||||||
Jest|from ['"]@jest/|jest\.fn|"jest":
|
|
||||||
Testing Library|@testing-library/
|
|
||||||
Playwright|@playwright/test
|
|
||||||
Cypress|cypress
|
|
||||||
MSW|from ['"]msw
|
|
||||||
Storybook|@storybook/
|
|
||||||
Vite|from ['"]vite['"]|"vite":
|
|
||||||
Webpack / Rspack / Turbopack|webpack|@rspack|--turbo
|
|
||||||
ESLint / Prettier / Biome|eslint|prettier|@biomejs
|
|
||||||
Monorepo tooling|turbo\.json|nx\.json|pnpm-workspace|"workspaces":|lerna
|
|
||||||
Docker|^FROM |docker-compose
|
|
||||||
Vercel / Netlify / Cloudflare|vercel\.json|netlify\.toml|wrangler|@cloudflare/
|
|
||||||
No-build ES modules / import maps|<script type="module"|type="importmap"
|
|
||||||
FastAPI / Starlette|from fastapi|from starlette|import fastapi
|
|
||||||
Flask / Django|from flask|import flask|from django|django\.
|
|
||||||
Python DB (SQLAlchemy / sqlite3)|sqlalchemy|import sqlite3|from sqlmodel
|
|
||||||
Go HTTP (net/http, Gin, Echo, Chi)|"net/http"|gin-gonic|labstack/echo|go-chi
|
|
||||||
Rails / Sinatra|Rails\.application|ActiveRecord|require .sinatra
|
|
||||||
pytest|import pytest|def test_
|
|
||||||
Node test runner|from ['"]node:test['"]|node --test
|
|
||||||
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 + config 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=="config")?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=="config")?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
|
|
||||||
# A workspace from an older skill version may lack a newer category's doc: seed it from the template.
|
|
||||||
[ -f "$f" ] || cp "$TEMPLATES/library/$cat.md" "$f"
|
|
||||||
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
|
|
||||||
|
|
@ -1,133 +0,0 @@
|
||||||
#!/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()
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# API & Backend
|
|
||||||
|
|
||||||
> 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:** Server code in this repo: endpoints and business logic.
|
|
||||||
|
|
||||||
**Look for:** framework (route handlers, Express/Fastify/Hono/Nest, serverless functions); endpoint list and methods; input validation; error format; middleware chain; rate limiting; external service integrations (payments, email, storage); OpenAPI/GraphQL schema; BFF patterns.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Architecture & Layering
|
|
||||||
|
|
||||||
> 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 shape: rendering model, layers, boundaries, data flow.
|
|
||||||
|
|
||||||
**Look for:** SPA vs SSR/SSG/ISR vs islands; client/server boundary (`use client`, server components, loaders); layering (UI → hooks/stores → services/API clients → backend → DB); domain types vs DTOs; where business logic lives; shared packages; unidirectional data flow; layer violations (components calling DB, fetch scattered in UI).
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Auth & Security
|
|
||||||
|
|
||||||
> 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:** Identity, access control and security posture.
|
|
||||||
|
|
||||||
**Look for:** auth provider/library; session vs JWT; where tokens live (httpOnly cookie vs storage); route/middleware protection; role/permission checks; CSRF/CORS config; security headers/CSP; input sanitization/XSS (`dangerouslySetInnerHTML`, `v-html`); secrets handling (env vars, which are exposed to the client); dependency on `secret-files.txt` entries by name only.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Background Jobs & Async 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 runs without a user waiting.
|
|
||||||
|
|
||||||
**Look for:** cron/scheduled functions; queues and workers (BullMQ, Inngest, …); webhooks received; email sending; revalidation/ISR triggers; service-worker background sync and push; build-time data generation; long-running processes.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Build & Tooling
|
|
||||||
|
|
||||||
> 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:** Package manager, workspaces, bundler/framework config, TypeScript setup, scripts, lint/format, versions.
|
|
||||||
|
|
||||||
**Look for:** package manager + lockfile type; workspaces/monorepo tool (pnpm/npm/yarn workspaces, Turborepo, Nx); framework + bundler and versions from package.json; tsconfig strictness, path aliases, project references; package.json scripts (dev/build/test/lint); env var loading (`import.meta.env`, `process.env`, `NEXT_PUBLIC_*`) and where it is validated; ESLint/Prettier/Biome config; browserslist/targets; build plugins.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Data Fetching & API Clients
|
|
||||||
|
|
||||||
> 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 the frontend gets and mutates data.
|
|
||||||
|
|
||||||
**Look for:** TanStack Query/SWR/Apollo/tRPC/plain fetch; API client wrappers, base URLs, interceptors, auth headers; request/response typing and runtime validation (Zod); caching, invalidation, optimistic updates; pagination/infinite scroll; error and retry handling; server actions; realtime (WebSocket/SSE).
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Deployment & CI
|
|
||||||
|
|
||||||
> 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 gets to users.
|
|
||||||
|
|
||||||
**Look for:** CI workflows (steps, checks, caching); hosting target (Vercel, Netlify, Cloudflare, Docker/K8s, static host); Dockerfiles and compose; environment separation (preview/staging/prod); env var injection; release/versioning; database migration step in deploy.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Features (user perspective)
|
|
||||||
|
|
||||||
> 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 product lets users do, as implemented.
|
|
||||||
|
|
||||||
**Look for:** one entry per user-perceivable capability (`feature-<name>`): what it lets the user do, entry point (route/page/component), and any background part (emails, notifications, scheduled reports, offline support).
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# File 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 the codebase is laid out and named.
|
|
||||||
|
|
||||||
**Look for:** by-feature vs by-type vs framework-convention (file-based routes); where components, hooks, stores, services, utils live; barrel files; path aliases in use; naming conventions (PascalCase components, kebab-case files, `.client`/`.server` suffixes); co-located tests/styles/stories; outliers.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Forms & Validation
|
|
||||||
|
|
||||||
> 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 input is collected and validated.
|
|
||||||
|
|
||||||
**Look for:** form library; schema validation shared between client and server; field components; error display; submission handling and pending states; file uploads; multi-step forms.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Internationalization & Accessibility
|
|
||||||
|
|
||||||
> 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:** Language support and accessible UI as implemented.
|
|
||||||
|
|
||||||
**Look for:** i18n library, locale detection, message files (count locales from `ledger` / excluded files), formatting via `Intl`; RTL support; semantic HTML, ARIA usage, focus management, keyboard support, skip links, reduced-motion handling, alt text practices, a11y lint rules/tests.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# Module Interactions
|
|
||||||
|
|
||||||
> 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 modules call each other and what data crosses each boundary. One entry per interaction (caller → callee for one purpose). "Module" means a workspace package; in a single-package app, use top-level feature/layer directories (e.g. `src/features/*`, `src/lib/*`, `server/`) instead.
|
|
||||||
|
|
||||||
**Look for:** imports of another package/feature; props/callbacks and context passed across feature boundaries; route params and search params between pages; client → server calls (fetch, server actions, tRPC, GraphQL) and their request/response types; server → DB/external API calls; events (custom events, event bus, BroadcastChannel, postMessage); shared stores read/written by several modules; queue/job payloads; webhook payloads; service-worker messages; shared DB tables/cache keys written by one module and read by another; layer violations.
|
|
||||||
|
|
||||||
**Each entry states:** **Kind** (`user-facing`: started by a user action or feeding what is on screen, including the request/response of a page load; `background`: no user waiting, e.g. cron, queue workers, webhooks, service-worker sync/push, revalidation, build-time generation, startup init), **From → To** (module + function/component, `path:line`), **Mechanism**, **Data passed** (types in each direction, where mapping/validation happens), **Trigger**.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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:** Errors, logs, analytics, monitoring.
|
|
||||||
|
|
||||||
**Look for:** error tracking (Sentry, …) client and server; error boundaries; logging library and format; analytics/event tracking and which events; feature flags; health checks; tracing.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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 no single category owns.
|
|
||||||
|
|
||||||
**Look for:** inconsistencies (two mechanisms for one job, with counts); migrations in progress; dead code suspicions; risky patterns; comment-vs-code mismatches; strengths worth keeping.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Performance
|
|
||||||
|
|
||||||
> 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:** Mechanisms that affect load and runtime speed.
|
|
||||||
|
|
||||||
**Look for:** code splitting and lazy loading; image optimization (`next/image`, srcset); font loading; bundle analysis config; memoization patterns; virtualization of long lists; prefetching; web-vitals reporting; heavy dependencies imported on the client.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Persistence & Storage
|
|
||||||
|
|
||||||
> 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:** Where data is stored, server and client.
|
|
||||||
|
|
||||||
**Look for:** database + ORM/query builder (Prisma, Drizzle, …); schema and migrations; connection handling; caching layers (Redis, in-memory, HTTP cache); object storage; client storage (localStorage, IndexedDB, cookies); seed data.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Rendering & Delivery
|
|
||||||
|
|
||||||
> 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:** Where and when HTML is produced.
|
|
||||||
|
|
||||||
**Look for:** CSR/SSR/SSG/ISR per route; streaming and Suspense boundaries; hydration strategy/islands; caching directives (`revalidate`, `cache`, `Cache-Control`, CDN headers); edge vs node runtimes; static export; prerendered routes.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Routing & 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 URLs map to screens and how users move between them.
|
|
||||||
|
|
||||||
**Look for:** file-based vs config routes; layouts and nested routes; dynamic segments; route guards/middleware and redirects; loaders/actions; search-param state; 404/error boundaries; links vs programmatic navigation; i18n route prefixes; deep links.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# State Management
|
|
||||||
|
|
||||||
> 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:** Client state: where it lives and how it changes.
|
|
||||||
|
|
||||||
**Look for:** local component state; context; stores (Redux/Zustand/Jotai/Pinia/XState); URL as state; persisted state (localStorage); derived state; global vs feature stores; server-state caches used as client state; prop drilling hot spots.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# Styling & Theming
|
|
||||||
|
|
||||||
> 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 visual design is expressed in code.
|
|
||||||
|
|
||||||
**Look for:** Tailwind / CSS Modules / Sass / CSS-in-JS / plain CSS; design tokens (CSS variables, Tailwind theme); dark mode mechanism; fonts and how they load; responsive approach (breakpoints, container queries); global styles and resets; hard-coded colors/sizes vs tokens; animation approach.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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:** How the code is tested.
|
|
||||||
|
|
||||||
**Look for:** unit/integration runner (Vitest/Jest); component testing (Testing Library); e2e (Playwright/Cypress); API mocking (MSW); fixtures/factories; visual/snapshot tests; Storybook stories and interaction tests; coverage config; which areas are tested and which are not.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# UI Components
|
|
||||||
|
|
||||||
> 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:** Component architecture and the design system as implemented.
|
|
||||||
|
|
||||||
**Look for:** component library (own design system, shadcn/Radix, MUI, …); primitives vs composites; variants API (cva, props); icon set; layout components; composition patterns (slots, compound components, render props); modals/toasts; component size and reuse; duplicated components.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
@ -1,123 +0,0 @@
|
||||||
---
|
|
||||||
name: web-project-scaffold-containerized-python
|
|
||||||
description: Scaffold a new web project with a Python (FastAPI) backend and a no-build HTML/CSS/JS frontend, packaged in a Docker container that deploys by pulling source from a remote git repo — `docker exec <name> update` fetches the latest commit, syncs requirements, restarts the app in place and rolls back on failure, with no image rebuild. Servers are set up by one copy-paste install command (curl … | bash) that installs Docker, clones the repo, writes the .env with repo URL and credentials, and starts the container. Requires an existing remote git repo URL up front. Use when the user wants to start/create/bootstrap a new web app, site, API or internal tool that should be Python-based, containerized, or easy to deploy and update on a server.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Scaffold a containerized Python web project
|
|
||||||
|
|
||||||
Goal: hand back a project where **`scripts/verify.sh` prints `VERIFY: PASS`** before any feature work. The run proves the image builds, the container clones from the repo named in `.env`, the tests pass, and `update` deploys, refuses broken code and rolls back without a rebuild. A passing run is the contract. Don't build features on a skeleton that hasn't passed.
|
|
||||||
|
|
||||||
## Principles (why the skeleton looks the way it does)
|
|
||||||
|
|
||||||
1. **Nothing is compiled.** The backend is Python (FastAPI + uvicorn). The frontend is plain HTML, CSS and ES modules served from `app/static/`, with no bundler, TypeScript, Sass, JSX or npm. Third-party browser libraries are vendored into `app/static/vendor/` as files with the pinned version in a comment. A deploy is therefore just new files.
|
|
||||||
2. **Containerized.** The host needs only Docker and git. Python, the venv and every tool run in the container, for dev and prod alike.
|
|
||||||
3. **The image is the runtime, not the app.** The image holds Python, git, tini and three scripts in `container/`. The source is a git checkout in the `/srv` volume, cloned from `REPO_URL` on first start. A rebuild is needed only when `container/` or the Python version changes.
|
|
||||||
4. **Update is one command.** `/usr/local/bin/update` is on PATH, so `docker exec <name> update` works. It reads `.env`, fetches `REPO_REF` from `REPO_URL`, checks out, reinstalls requirements if they changed, checks that `app.main` imports, sends SIGHUP to the in-container supervisor (which restarts uvicorn), and waits for `/healthz` to report the new commit. Any failure restores the previous commit. `--check`, `--rollback` and `<ref>` cover the rest.
|
|
||||||
5. **Remote and credentials live in `.env`.** It is gitignored and mounted read-only at `/run/config/app.env`. The container parses it (it doesn't execute it) on every start and every update, so a new URL or rotated token needs no rebuild or recreate.
|
|
||||||
- **Variables:** `REPO_URL`, `REPO_REF`, `GIT_TOKEN`/`GIT_USERNAME` (https) or `GIT_SSH_KEY` (base64 deploy key), plus any app settings.
|
|
||||||
- **Token:** a git credential helper supplies it from the environment. It never goes into `.git/config` or the URL.
|
|
||||||
- **Isolation:** the uvicorn process gets the app settings but not the git credentials.
|
|
||||||
|
|
||||||
6. **Install is one pasted line.** The project ships `install.sh`. On a fresh Linux server, the user pastes `curl -fsSL <raw install.sh URL> | bash`, Homebrew-style, and the installer does the rest:
|
|
||||||
- installs git and Docker (Engine + Compose) if they're missing
|
|
||||||
- checks it can read the repo, asking for a token on the terminal if the https repo is private
|
|
||||||
- clones into `/opt/<name>`
|
|
||||||
- writes `.env` from `.env.example` with the repo URL, branch, credentials and port, owned by uid 1000 with mode 640
|
|
||||||
- builds the image, starts the container and waits for `/healthz`
|
|
||||||
|
|
||||||
Re-running it is safe, and is also how the image gets rebuilt: it keeps `.env` and replaces only the keys passed in. Everything is inside `main()`, so a partial download runs nothing. It uses sudo only for steps that need it.
|
|
||||||
|
|
||||||
## Step 0 — Get the remote repo URL first (required)
|
|
||||||
|
|
||||||
Servers install from and update from the remote. The install command is that repo's raw `install.sh` URL, and the URL is the default `REPO_URL` baked into `install.sh` and `.env.example`. So **don't scaffold until the user has given the remote git repo URL.** If they haven't, ask for it before anything else. Ask whether it is private: over https it needs a read-only token, and over SSH a deploy key.
|
|
||||||
- Have them create an empty repo first if it doesn't exist (GitHub, GitLab, Gitea, …).
|
|
||||||
- GitHub and GitLab raw URLs are derived. For any other host, ask for the raw URL of `install.sh` on the default branch and pass `--install-url`.
|
|
||||||
- The URL must not contain credentials. Those go only in the server's `.env`, through the installer.
|
|
||||||
|
|
||||||
## Step 1 — Check the environment (never install silently)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash "$SKILL_DIR/scripts/doctor.sh"
|
|
||||||
```
|
|
||||||
|
|
||||||
It checks git, docker, compose v2, buildx and daemon access. If it exits non-zero, show the user its fix lines and stop. Let them run the installs, suggesting the `! <command>` prefix. Don't scaffold blind.
|
|
||||||
|
|
||||||
## Step 2 — Decide the few inputs
|
|
||||||
|
|
||||||
- `--name`: a lowercase slug. It becomes the container name (so `docker exec <name> update`), the image name and the compose project.
|
|
||||||
- `--title`: the display name.
|
|
||||||
- `--python`: default 3.14. Use the user's version if they give one.
|
|
||||||
- `--port`: the host port on 127.0.0.1, default 8000.
|
|
||||||
- `--branch`: default `main`.
|
|
||||||
- `--repo-url` (**required**, from Step 0): the remote the servers clone from. It goes into `install.sh`, `.env.example` and the local `origin`.
|
|
||||||
- `--install-url`: only for hosts other than GitHub and GitLab.
|
|
||||||
|
|
||||||
Ask only for what you can't default. The name is usually obvious from the request.
|
|
||||||
|
|
||||||
## Step 3 — Generate
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash "$SKILL_DIR/scripts/scaffold.sh" --dir <project-dir> --name <slug> --repo-url <url> [--title "…"] [--python 3.14] [--port 8000] [--branch main] [--install-url <url>]
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Pins:** it resolves current `fastapi`, `uvicorn[standard]`, `pytest` and `httpx2` versions in a throwaway `python:<ver>-slim` container and pins them `==X.Y.*`. Use `--no-resolve` when offline.
|
|
||||||
- **Templates and tokens:** it copies `templates/project`. If the `web-frontend` skill is installed, it copies that skill's `tokens.css` into `app/static/css/`.
|
|
||||||
- **`.env` and git:** it writes a local `.env` (mode 600) for dev, runs `git init` and adds `origin`, then prints the install command. It doesn't commit, push, build or start anything.
|
|
||||||
|
|
||||||
Resulting layout (details in the generated `README.md`):
|
|
||||||
|
|
||||||
```
|
|
||||||
app/main.py, app/api.py FastAPI: /healthz {status, version}, /api/*, /static (no-cache), /
|
|
||||||
app/static/ index.html, css/tokens.css + app.css, js/main.js + api.js, vendor/
|
|
||||||
tests/test_app.py pytest + TestClient
|
|
||||||
install.sh server installer: curl … | bash (Docker, clone, .env, build, start, health)
|
|
||||||
container/ Dockerfile, lib.sh, entrypoint.sh (setup + supervisor), update.sh
|
|
||||||
compose.yml prod: volumes runtime:/srv + data:/data, ./.env mounted, loopback port, read-only rootfs
|
|
||||||
compose.dev.yml dev overlay: source bind-mounted, DEV=1 → dev deps + --reload, update disabled
|
|
||||||
.env.example / .env REPO_URL, REPO_REF, GIT_TOKEN/GIT_USERNAME, GIT_SSH_KEY, HOST_PORT, app settings
|
|
||||||
```
|
|
||||||
|
|
||||||
## Step 4 — Verify the contract
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash "$SKILL_DIR/scripts/verify.sh" <project-dir> # add --keep to leave containers for debugging
|
|
||||||
```
|
|
||||||
|
|
||||||
It works on a throwaway copy with a local bare repo as the "remote" and a dummy token in its `.env`. Your project, its `.env` and its git history are untouched. It checks:
|
|
||||||
- the build and a healthy start
|
|
||||||
- the app sees `.env` settings but not `GIT_TOKEN`, and the token is never written to disk
|
|
||||||
- pytest passes
|
|
||||||
- `update` deploys a commit that changes requirements, with the same image and the same container start time
|
|
||||||
- an import-breaking commit is refused and a startup-crashing commit is rolled back, with the old commit still serving
|
|
||||||
- `update --rollback`
|
|
||||||
- `install.sh` piped into bash, as on a fresh server, against a `git://` remote: it brings the app up healthy and reachable on the host port, writes `.env` (uid 1000, mode 640) and never calls sudo when it isn't needed; a re-run is safe and replaces only the keys passed in
|
|
||||||
|
|
||||||
It doesn't exercise the Docker-install branch, because Docker is already present. That branch was tested on a bare Debian image: git, ssh, Docker and Compose all installed.
|
|
||||||
|
|
||||||
It must end with `VERIFY: PASS`. If it fails, fix the template or the project until it passes, then report the versions used.
|
|
||||||
|
|
||||||
Then tell the user the flow:
|
|
||||||
1. **Push** the project to the remote. Offer to make the first commit and push; don't do either unless they ask. The install command only works once `install.sh` is on the remote branch.
|
|
||||||
2. **Install:** paste the printed command on the server. For a private https repo, use the `read -rsp … && curl -H …` form from the README, so the token is never echoed or saved in shell history.
|
|
||||||
3. **Deploy:** `git push`, then `docker exec <name> update` on the server.
|
|
||||||
4. **Rebuild** (only when `container/` changes): run the install command again.
|
|
||||||
|
|
||||||
## Building on the skeleton
|
|
||||||
|
|
||||||
- **UI:** follow the `web-frontend` skill for the look (tokens, layout, components), within the no-build rule: plain CSS on the tokens, ES modules, vendored libraries, no CDN. Web fonts are vendored into `static/vendor/fonts/` or left on the system stack.
|
|
||||||
- **API:** routes go in `app/api.py`, or an `app/api/` package as it grows, under `/api`. Use Pydantic models for request and response bodies.
|
|
||||||
- **Persistence:** keep it under `$DATA_DIR` (`/data`, its own volume). SQLite is the default for small apps. Create the schema and run migrations idempotently in `lifespan`, never at import time, because `update` imports `app.main` as its pre-flight check.
|
|
||||||
- **Dependencies:** add each one to `requirements.txt` with a `==X.Y.*` pin. `update` installs it on the next deploy. Test-only dependencies go in `requirements-dev.txt`.
|
|
||||||
- **Settings and secrets:** new ones go in `.env` and `.env.example`, which holds names and placeholders only. Read them with `os.environ` in the app.
|
|
||||||
- **System packages** (e.g. `ffmpeg`, `libpq`) mean a `container/Dockerfile` change, and so a rebuild. Prefer pure-Python wheels. When a system package is needed, say a rebuild is required.
|
|
||||||
|
|
||||||
## Guardrails
|
|
||||||
|
|
||||||
- **Every "it works" claim comes from a `verify.sh` run that printed `VERIFY: PASS`,** never from reading the files.
|
|
||||||
- **No build step, ever.** Don't add `package.json`, a bundler, TypeScript or a CSS preprocessor. If the user needs one, they are asking for a different project shape; say so.
|
|
||||||
- **Never bake app source into the image.** `.dockerignore` lets in only `container/`. Copying `app/` into the image would make `update` and the image disagree.
|
|
||||||
- **No remote, no scaffold.** Get the repo URL first (Step 0). Don't invent a placeholder URL to fill in later.
|
|
||||||
- **The server is set up only through `install.sh`.** Keep it idempotent and inside `main()`. When a project needs more server setup (a system package, a firewall rule, a volume path), add it to the installer rather than to manual README steps.
|
|
||||||
- **Never commit `.env`, tokens or keys.** Don't put credentials in `REPO_URL`. Don't print `.env` values. Name variables, never their values.
|
|
||||||
- **Keep the scripts in `container/` generic.** Project-specific logic belongs in the app (`lifespan`), not in `update.sh`, which can only change with a rebuild.
|
|
||||||
- **Used ⇒ declared:** every import maps to a pinned line in `requirements*.txt`, and every vendored file has its version noted.
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Check that this machine can build and run the scaffold. The host needs only Docker
|
|
||||||
# (with Compose v2 and BuildKit) and git; Python runs inside the container.
|
|
||||||
# Exits non-zero if something required is missing. Installs nothing.
|
|
||||||
ok=1
|
|
||||||
pass() { printf ' ok %s\n' "$*"; }
|
|
||||||
fail() { printf ' MISS %s\n' "$*"; ok=0; }
|
|
||||||
note() { printf ' note %s\n' "$*"; }
|
|
||||||
|
|
||||||
echo "Host tools"
|
|
||||||
if command -v git >/dev/null; then pass "git $(git --version | awk '{print $3}')"; else
|
|
||||||
fail "git: install it (e.g. sudo apt install git)"; fi
|
|
||||||
if command -v docker >/dev/null; then pass "docker $(docker --version | sed 's/Docker version //; s/,.*//')"; else
|
|
||||||
fail "docker: install Docker Engine (https://docs.docker.com/engine/install/)"; fi
|
|
||||||
|
|
||||||
if command -v docker >/dev/null; then
|
|
||||||
if docker compose version >/dev/null 2>&1; then pass "compose $(docker compose version --short)"; else
|
|
||||||
fail "docker compose v2 plugin: sudo apt install docker-compose-plugin"; fi
|
|
||||||
if docker buildx version >/dev/null 2>&1; then pass "buildx (BuildKit; needed for COPY --chmod)"; else
|
|
||||||
fail "docker buildx plugin: sudo apt install docker-buildx-plugin"; fi
|
|
||||||
if docker info >/dev/null 2>&1; then pass "daemon reachable as $(id -un)"; else
|
|
||||||
fail "cannot talk to the Docker daemon: start it, or add yourself to the docker group (sudo usermod -aG docker $USER, then log in again)"; fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "Notes"
|
|
||||||
note "host uid $(id -u): the image's app user defaults to uid 1000; dev bind mounts are easiest when they match"
|
|
||||||
command -v python3 >/dev/null && note "host python3 $(python3 -V 2>&1 | awk '{print $2}') is not used; Python runs in the container"
|
|
||||||
|
|
||||||
[ "$ok" = 1 ] && { echo "Ready."; exit 0; }
|
|
||||||
echo "Fix the MISS lines above, then re-run."
|
|
||||||
exit 1
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Write a new containerized Python web project from templates/project.
|
|
||||||
# scaffold.sh --dir <path> --name <slug> --repo-url <url> [--title "My App"] [--python 3.14]
|
|
||||||
# [--port 8000] [--branch main] [--install-url <url>] [--no-resolve]
|
|
||||||
# --repo-url is required: the remote must exist, since servers install and update from it.
|
|
||||||
# --install-url is the raw URL of install.sh on the default branch; derived for GitHub and
|
|
||||||
# GitLab, required for other hosts.
|
|
||||||
# Resolves current fastapi/uvicorn/pytest/httpx2 versions inside python:<ver>-slim and pins
|
|
||||||
# them (==X.Y.*), unless --no-resolve (then the fallback pins below are used).
|
|
||||||
# Writes .env from .env.example, runs `git init` and adds the remote as origin.
|
|
||||||
# Does not commit, build or start anything; run verify.sh for that.
|
|
||||||
set -euo pipefail
|
|
||||||
SKILL_DIR=$(cd "$(dirname "$0")/.." && pwd)
|
|
||||||
TEMPLATE="$SKILL_DIR/templates/project"
|
|
||||||
TOKENS="$SKILL_DIR/../web-frontend/assets/tokens.css"
|
|
||||||
|
|
||||||
dir= name= title= python=3.14 port=8000 branch=main repo_url= install_url= resolve=1
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case $1 in
|
|
||||||
--dir) dir=$2; shift ;;
|
|
||||||
--name) name=$2; shift ;;
|
|
||||||
--title) title=$2; shift ;;
|
|
||||||
--python) python=$2; shift ;;
|
|
||||||
--port) port=$2; shift ;;
|
|
||||||
--branch) branch=$2; shift ;;
|
|
||||||
--repo-url) repo_url=$2; shift ;;
|
|
||||||
--install-url) install_url=$2; shift ;;
|
|
||||||
--no-resolve) resolve=0 ;;
|
|
||||||
-h|--help) sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
|
|
||||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
|
||||||
esac
|
|
||||||
shift
|
|
||||||
done
|
|
||||||
[ -n "$dir" ] && [ -n "$name" ] && [ -n "$repo_url" ] || { echo "usage: scaffold.sh --dir <path> --name <slug> --repo-url <url> [...]" >&2; exit 2; }
|
|
||||||
[[ $repo_url =~ ^(https://|ssh://|git@[^:]+:) ]] || { echo "--repo-url must be https://..., ssh://... or git@host:owner/repo.git" >&2; exit 2; }
|
|
||||||
[[ $repo_url =~ ://[^/]*@ ]] && { echo "--repo-url must not contain credentials; they go in the server's .env" >&2; exit 2; }
|
|
||||||
|
|
||||||
# Raw URL of install.sh, and the header a private repo's token goes in.
|
|
||||||
token_header="Authorization: Bearer "
|
|
||||||
if [[ $repo_url =~ github\.com[:/]([^/]+)/([^/]+)$ ]]; then
|
|
||||||
derived="https://raw.githubusercontent.com/${BASH_REMATCH[1]}/${BASH_REMATCH[2]%.git}/$branch/install.sh"
|
|
||||||
token_header="Authorization: token "
|
|
||||||
elif [[ $repo_url =~ gitlab\.com[:/](.+)/([^/]+)$ ]]; then
|
|
||||||
gl_path="${BASH_REMATCH[1]}/${BASH_REMATCH[2]%.git}"
|
|
||||||
derived="https://gitlab.com/api/v4/projects/${gl_path//\//%2F}/repository/files/install.sh/raw?ref=$branch"
|
|
||||||
token_header="PRIVATE-TOKEN: "
|
|
||||||
else derived=; fi
|
|
||||||
install_url=${install_url:-$derived}
|
|
||||||
[ -n "$install_url" ] || { echo "can't derive the raw install.sh URL for $repo_url; pass --install-url" >&2; exit 2; }
|
|
||||||
[[ $name =~ ^[a-z][a-z0-9-]*$ ]] || { echo "--name must be a lowercase slug (letters, digits, -)" >&2; exit 2; }
|
|
||||||
[ -n "$title" ] || title=$(echo "$name" | tr '-' ' ' | sed -E 's/(^| )([a-z])/\1\u\2/g')
|
|
||||||
if [ -e "$dir" ] && [ -n "$(ls -A "$dir" | grep -v '^\.git$' || true)" ]; then
|
|
||||||
echo "$dir exists and is not empty; refusing to overwrite" >&2; exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Fallback pins, verified 2026-11 on Python 3.14.
|
|
||||||
fastapi=0.162 uvicorn=0.54 pytest=9.2 httpx=2.16
|
|
||||||
if [ "$resolve" = 1 ]; then
|
|
||||||
echo "resolving current versions in python:$python-slim ..."
|
|
||||||
if out=$(docker run --rm "python:$python-slim" sh -c \
|
|
||||||
'pip install -q --disable-pip-version-check --root-user-action=ignore fastapi "uvicorn[standard]" pytest httpx2 >/dev/null 2>&1 && pip freeze'); then
|
|
||||||
v() { echo "$out" | sed -n "s/^$1==\([0-9]*\.[0-9]*\).*/\1/p"; }
|
|
||||||
fastapi=$(v fastapi) uvicorn=$(v uvicorn) pytest=$(v pytest) httpx=$(v httpx2)
|
|
||||||
else
|
|
||||||
echo "could not resolve versions (offline, or no python:$python-slim image); using fallback pins" >&2
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir -p "$dir"
|
|
||||||
cp -r "$TEMPLATE/." "$dir/"
|
|
||||||
if [ -f "$TOKENS" ]; then
|
|
||||||
cp "$TOKENS" "$dir/app/static/css/tokens.css"
|
|
||||||
else
|
|
||||||
echo "web-frontend skill not found; writing minimal tokens.css" >&2
|
|
||||||
cat > "$dir/app/static/css/tokens.css" <<'CSS'
|
|
||||||
:root { color-scheme: light dark; --hue: 250; --bg: oklch(0.985 0.01 var(--hue)); --surface: oklch(1 0 0);
|
|
||||||
--surface-2: oklch(0.965 0.01 var(--hue)); --border: oklch(0.9 0.015 var(--hue)); --fg: oklch(0.22 0.02 var(--hue));
|
|
||||||
--fg-muted: oklch(0.45 0.02 var(--hue)); --ok: oklch(0.55 0.13 150); --danger: oklch(0.55 0.19 25);
|
|
||||||
--font-body: ui-sans-serif, system-ui, sans-serif; --font-mono: ui-monospace, Menlo, monospace;
|
|
||||||
--text-xs: .75rem; --text-lg: 1.125rem; --weight-medium: 500; --weight-semibold: 600; --measure: 65ch;
|
|
||||||
--space-2: .5rem; --space-4: 1rem; --space-5: 1.25rem; --space-6: 1.5rem; --space-12: 3rem;
|
|
||||||
--gutter: max(16px, 4vw); --content-max: 72rem; --radius-md: 8px; --radius-full: 999px; }
|
|
||||||
@media (prefers-color-scheme: dark) { :root { --bg: oklch(0.17 0.015 var(--hue)); --surface: oklch(0.21 0.015 var(--hue));
|
|
||||||
--surface-2: oklch(0.245 0.015 var(--hue)); --border: oklch(0.3 0.02 var(--hue)); --fg: oklch(0.95 0.01 var(--hue));
|
|
||||||
--fg-muted: oklch(0.74 0.015 var(--hue)); --ok: oklch(0.72 0.14 150); --danger: oklch(0.7 0.17 25); } }
|
|
||||||
body { margin: 0; background: var(--bg); color: var(--fg); font-family: var(--font-body); line-height: 1.6; }
|
|
||||||
.label { font-size: var(--text-xs); font-weight: var(--weight-semibold); text-transform: uppercase; letter-spacing: .06em; color: var(--fg-muted); }
|
|
||||||
CSS
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Fill placeholders in every text file.
|
|
||||||
find "$dir" -type f ! -path '*/.git/*' -print0 | xargs -0 sed -i \
|
|
||||||
-e "s|__NAME__|$name|g" -e "s|__TITLE__|$title|g" -e "s|__PYTHON__|$python|g" \
|
|
||||||
-e "s|__PORT__|$port|g" -e "s|__BRANCH__|$branch|g" \
|
|
||||||
-e "s|__REPO_URL__|$repo_url|g" -e "s|__INSTALL_URL__|$install_url|g" -e "s|__TOKEN_HEADER__|$token_header|g" \
|
|
||||||
-e "s|__FASTAPI__|$fastapi.*|g" -e "s|__UVICORN__|$uvicorn.*|g" \
|
|
||||||
-e "s|__PYTEST__|$pytest.*|g" -e "s|__HTTPX__|$httpx.*|g"
|
|
||||||
chmod +x "$dir/container/entrypoint.sh" "$dir/container/update.sh" "$dir/install.sh"
|
|
||||||
|
|
||||||
# The machine's own .env: gitignored, read by the container.
|
|
||||||
cp "$dir/.env.example" "$dir/.env"
|
|
||||||
chmod 600 "$dir/.env"
|
|
||||||
|
|
||||||
[ -d "$dir/.git" ] || git -C "$dir" init -q -b "$branch"
|
|
||||||
git -C "$dir" remote get-url origin >/dev/null 2>&1 || git -C "$dir" remote add origin "$repo_url"
|
|
||||||
left=$(grep -rl '__[A-Z]*__' "$dir" --exclude-dir=.git || true)
|
|
||||||
[ -z "$left" ] || { echo "unfilled placeholders in: $left" >&2; exit 1; }
|
|
||||||
|
|
||||||
echo "scaffolded $name in $dir (Python $python, fastapi $fastapi, uvicorn $uvicorn)"
|
|
||||||
echo "install command (after the first push): curl -fsSL $install_url | bash"
|
|
||||||
echo "next: bash $SKILL_DIR/scripts/verify.sh $dir"
|
|
||||||
|
|
@ -1,153 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Prove the scaffold's contract end to end, on a throwaway copy (the project itself, its
|
|
||||||
# .env and its git history are not touched):
|
|
||||||
# 1. the image builds and the container comes up healthy, cloning from a "remote" repo
|
|
||||||
# named in .env
|
|
||||||
# 2. the tests pass in the dev setup
|
|
||||||
# 3. `docker exec <c> update` deploys a new commit (with a requirements change) without
|
|
||||||
# rebuilding the image or restarting the container
|
|
||||||
# 4. an update to code that fails to import is refused; the old commit keeps serving
|
|
||||||
# 5. an update to code that crashes at startup is rolled back; the old commit keeps serving
|
|
||||||
# 6. `update --rollback` returns to the commit before the last successful update
|
|
||||||
# 7. install.sh, piped into bash as on a fresh server, clones from a git:// remote, writes
|
|
||||||
# .env (uid 1000, mode 640), and brings the app up healthy; a re-run is safe and only
|
|
||||||
# replaces the .env keys passed to it. Docker is not reinstalled (it is present here).
|
|
||||||
# verify.sh <project-dir> [--keep] # --keep leaves the containers and temp dir for debugging
|
|
||||||
set -uo pipefail
|
|
||||||
project=$(cd "${1:?usage: verify.sh <project-dir> [--keep]}" && pwd)
|
|
||||||
keep=0; [ "${2:-}" = --keep ] && keep=1
|
|
||||||
|
|
||||||
W=$(mktemp -d "${TMPDIR:-/tmp}/scaffold-verify.XXXXXX")
|
|
||||||
P="verify-$(basename "$project" | tr -cd 'a-z0-9-')-$$"
|
|
||||||
C="$P-app"
|
|
||||||
branch=$(sed -n 's/^REPO_REF=//p' "$project/.env.example"); branch=${branch:-main}
|
|
||||||
fails=0
|
|
||||||
step() { printf '\n== %s\n' "$*"; }
|
|
||||||
pass() { printf ' PASS %s\n' "$*"; }
|
|
||||||
fail() { printf ' FAIL %s\n' "$*"; fails=$((fails + 1)); }
|
|
||||||
dc() { docker compose -p "$P" -f "$W/work/compose.yml" -f "$W/verify.yml" "$@"; }
|
|
||||||
cleanup() {
|
|
||||||
if [ "$keep" = 1 ]; then echo "kept: $W, compose project $P (docker compose -p $P down -v)"; return; fi
|
|
||||||
dc down -v --rmi local >/dev/null 2>&1
|
|
||||||
docker compose -p "$P-dev" -f "$W/work/compose.yml" -f "$W/work/compose.dev.yml" -f "$W/verify-dev.yml" down -v >/dev/null 2>&1
|
|
||||||
docker image rm -f "$P:latest" >/dev/null 2>&1
|
|
||||||
[ -f "$W/opt/compose.yml" ] && (cd "$W/opt" && docker compose down -v --rmi local >/dev/null 2>&1)
|
|
||||||
[ -n "${daemon:-}" ] && kill "$daemon" 2>/dev/null
|
|
||||||
rm -rf "$W"
|
|
||||||
}
|
|
||||||
trap cleanup EXIT
|
|
||||||
|
|
||||||
health() { docker exec "$C" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null; }
|
|
||||||
wait_for() { # wait_for <version> <seconds>
|
|
||||||
for _ in $(seq 1 "$2"); do [ "$(health)" = "$1" ] && return 0; sleep 1; done; return 1; }
|
|
||||||
commit() { git -C "$W/work" add -A && git -C "$W/work" commit -qm "$1" && git -C "$W/work" push -q origin "$branch" && git -C "$W/work" rev-parse --short HEAD; }
|
|
||||||
|
|
||||||
step "copy project to $W and create a remote"
|
|
||||||
mkdir -p "$W/work"
|
|
||||||
tar -C "$project" --exclude=.git --exclude=.env --exclude=data -cf - . | tar -C "$W/work" -xf -
|
|
||||||
git -C "$W/work" init -q -b "$branch"
|
|
||||||
git -C "$W/work" -c user.name=verify -c user.email=verify@localhost add -A
|
|
||||||
git -C "$W/work" -c user.name=verify -c user.email=verify@localhost commit -qm "initial"
|
|
||||||
git clone -q --bare "$W/work" "$W/seed.git"
|
|
||||||
git -C "$W/work" remote add origin "$W/seed.git"
|
|
||||||
git -C "$W/work" config user.name verify; git -C "$W/work" config user.email verify@localhost
|
|
||||||
c1=$(git -C "$W/work" rev-parse --short HEAD)
|
|
||||||
sed -e "s|^REPO_URL=.*|REPO_URL=/seed.git|" -e "s|^REPO_REF=.*|REPO_REF=$branch|" \
|
|
||||||
-e "s|^GIT_TOKEN=.*|GIT_TOKEN=verify-dummy-token|" "$W/work/.env.example" > "$W/work/.env"
|
|
||||||
echo "VERIFY_SETTING=from-dotenv" >> "$W/work/.env"
|
|
||||||
chmod 600 "$W/work/.env"
|
|
||||||
cat > "$W/verify.yml" <<EOF
|
|
||||||
services:
|
|
||||||
app:
|
|
||||||
image: $P:latest
|
|
||||||
container_name: $C
|
|
||||||
environment:
|
|
||||||
CONTAINER_NAME: $C
|
|
||||||
ports: !reset []
|
|
||||||
volumes:
|
|
||||||
- $W/seed.git:/seed.git:ro
|
|
||||||
EOF
|
|
||||||
cat > "$W/verify-dev.yml" <<EOF
|
|
||||||
services:
|
|
||||||
app:
|
|
||||||
image: $P:latest
|
|
||||||
container_name: $C-dev
|
|
||||||
ports: !reset []
|
|
||||||
EOF
|
|
||||||
pass "remote at $W/seed.git, initial commit $c1"
|
|
||||||
|
|
||||||
step "1. build and start"
|
|
||||||
if dc up -d --build >"$W/build.log" 2>&1 && wait_for "$c1" 120; then pass "healthy at $c1 (cloned from REPO_URL in .env)"
|
|
||||||
else fail "did not come up healthy; build log and container log:"; tail -20 "$W/build.log"; docker logs --tail 40 "$C" 2>&1; exit 1; fi
|
|
||||||
image0=$(docker inspect -f '{{.Image}}' "$C"); started0=$(docker inspect -f '{{.State.StartedAt}}' "$C")
|
|
||||||
appenv=$(docker exec "$C" sh -c 'for d in /proc/[0-9]*; do grep -q uvicorn "$d/cmdline" 2>/dev/null && tr "\0" "\n" < "$d/environ"; done')
|
|
||||||
grep -qx 'VERIFY_SETTING=from-dotenv' <<<"$appenv" && pass "app sees settings from .env" || fail "app does not see VERIFY_SETTING from .env"
|
|
||||||
grep -q 'verify-dummy-token' <<<"$appenv" && fail "app process can see GIT_TOKEN" || pass "app process cannot see GIT_TOKEN"
|
|
||||||
docker exec "$C" grep -rqs 'verify-dummy-token' /srv/src/.git/config /srv/state && fail "token written to disk" || pass "token not written into the checkout or state"
|
|
||||||
[ "$(docker exec "$C" git -C /srv/src config --get remote.origin.url)" = /seed.git ] && pass "origin is the REPO_URL from .env" || fail "origin URL is not REPO_URL"
|
|
||||||
|
|
||||||
step "2. tests (dev setup)"
|
|
||||||
if docker compose -p "$P-dev" -f "$W/work/compose.yml" -f "$W/work/compose.dev.yml" -f "$W/verify-dev.yml" run --rm app pytest -q >"$W/test.log" 2>&1; then
|
|
||||||
pass "pytest: $(grep -E 'passed|failed' "$W/test.log" | tail -1)"
|
|
||||||
else fail "pytest failed:"; tail -30 "$W/test.log"; fi
|
|
||||||
|
|
||||||
step "3. update to a new commit"
|
|
||||||
echo "idna>=3" >> "$W/work/requirements.txt"
|
|
||||||
c2=$(commit "add a requirement")
|
|
||||||
if out=$(docker exec "$C" update 2>&1) && [ "$(health)" = "$c2" ]; then pass "update -> $c2"; else fail "update to $c2 failed:"; echo "$out"; fi
|
|
||||||
[ "$(docker inspect -f '{{.Image}}' "$C")" = "$image0" ] && pass "same image (no rebuild)" || fail "image changed"
|
|
||||||
[ "$(docker inspect -f '{{.State.StartedAt}}' "$C")" = "$started0" ] && pass "same container start time (no container restart)" || fail "container restarted"
|
|
||||||
docker exec "$C" /srv/venv/bin/python -c 'import idna' 2>/dev/null && pass "new requirement installed" || fail "new requirement missing"
|
|
||||||
out=$(docker exec "$C" update 2>&1); [[ $out == already* ]] && pass "second update is a no-op ($out)" || fail "second update: $out"
|
|
||||||
|
|
||||||
step "4. update to code that does not import"
|
|
||||||
cp "$W/work/app/main.py" "$W/main.py.good"
|
|
||||||
echo 'raise RuntimeError("broken on purpose by verify.sh")' >> "$W/work/app/main.py"
|
|
||||||
c3=$(commit "broken import")
|
|
||||||
if docker exec "$C" update >"$W/u4.log" 2>&1; then fail "update to broken $c3 reported success"; else pass "update refused (exit non-zero)"; fi
|
|
||||||
[ "$(health)" = "$c2" ] && pass "still serving $c2" || fail "serving '$(health)', expected $c2"
|
|
||||||
[ "$(docker exec "$C" git -C /srv/src rev-parse --short HEAD)" = "$c2" ] && pass "checkout back at $c2" || fail "checkout not restored"
|
|
||||||
|
|
||||||
step "5. update to code that crashes at startup"
|
|
||||||
cp "$W/main.py.good" "$W/work/app/main.py"
|
|
||||||
sed -i 's| DATA_DIR.mkdir(parents=True, exist_ok=True)| raise RuntimeError("startup failure on purpose by verify.sh")|' "$W/work/app/main.py"
|
|
||||||
grep -q 'startup failure on purpose' "$W/work/app/main.py" || fail "could not plant the startup failure"
|
|
||||||
c4=$(commit "broken startup")
|
|
||||||
if docker exec -e HEALTH_TIMEOUT=10 "$C" update >"$W/u5.log" 2>&1; then fail "update to crashing $c4 reported success"; else pass "update rolled back (exit non-zero)"; fi
|
|
||||||
wait_for "$c2" 30 && pass "still serving $c2" || { fail "serving '$(health)', expected $c2"; cat "$W/u5.log"; docker logs --tail 20 "$C"; }
|
|
||||||
[ "$(docker inspect -f '{{.State.StartedAt}}' "$C")" = "$started0" ] && pass "container stayed up" || fail "container restarted"
|
|
||||||
|
|
||||||
step "6. rollback"
|
|
||||||
cp "$W/main.py.good" "$W/work/app/main.py"; commit "fixed" >/dev/null
|
|
||||||
if docker exec "$C" update --rollback >"$W/u6.log" 2>&1 && [ "$(health)" = "$c1" ]; then pass "rolled back to $c1"; else fail "rollback failed:"; cat "$W/u6.log"; fi
|
|
||||||
|
|
||||||
step "7. install.sh on a fresh host"
|
|
||||||
iname="$P-i"
|
|
||||||
pname=$(sed -n 's/^name: //p' "$project/compose.yml")
|
|
||||||
mkdir -p "$W/isrc" "$W/bin"
|
|
||||||
tar -C "$project" --exclude=.git --exclude=.env --exclude=data -cf - . | tar -C "$W/isrc" -xf -
|
|
||||||
grep -rl -- "$pname" "$W/isrc" | xargs sed -i "s/$pname/$iname/g"
|
|
||||||
git -C "$W/isrc" init -q -b "$branch" && git -C "$W/isrc" add -A && git -C "$W/isrc" -c user.name=verify -c user.email=verify@localhost commit -qm initial
|
|
||||||
ic=$(git -C "$W/isrc" rev-parse --short HEAD)
|
|
||||||
git clone -q --bare "$W/isrc" "$W/serve/iseed.git"
|
|
||||||
gport=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1])')
|
|
||||||
hport=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1])')
|
|
||||||
hostip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')
|
|
||||||
git daemon --export-all --reuseaddr --listen=0.0.0.0 --port="$gport" --base-path="$W/serve" "$W/serve" >/dev/null 2>&1 & daemon=$!
|
|
||||||
sleep 1
|
|
||||||
printf '#!/bin/sh\necho "sudo was called: $*" >&2; exit 1\n' > "$W/bin/sudo"; chmod +x "$W/bin/sudo"
|
|
||||||
irun() { PATH="$W/bin:$PATH" INSTALL_DIR="$W/opt" REPO_URL="git://$hostip:$gport/iseed.git" "$@" bash < "$W/isrc/install.sh"; }
|
|
||||||
if irun env HOST_PORT="$hport" >"$W/i1.log" 2>&1; then pass "installer exit 0 (piped into bash, no sudo needed)"; else fail "installer failed:"; tail -30 "$W/i1.log"; fi
|
|
||||||
iv=$(docker exec "$iname" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null)
|
|
||||||
[ "$iv" = "$ic" ] && pass "container $iname healthy at $ic" || fail "container not healthy at $ic (got '$iv')"
|
|
||||||
[ "$(stat -c '%u %a' "$W/opt/.env" 2>/dev/null)" = "1000 640" ] && pass ".env owned by uid 1000, mode 640" || fail ".env ownership/mode: $(stat -c '%u %a' "$W/opt/.env" 2>&1)"
|
|
||||||
grep -qx "REPO_URL=git://$hostip:$gport/iseed.git" "$W/opt/.env" && grep -qx "HOST_PORT=$hport" "$W/opt/.env" && pass ".env has REPO_URL and HOST_PORT" || fail ".env missing REPO_URL/HOST_PORT"
|
|
||||||
curl -fsS "http://127.0.0.1:$hport/healthz" >/dev/null && pass "reachable on 127.0.0.1:$hport" || fail "not reachable on host port $hport"
|
|
||||||
if PATH="$W/bin:$PATH" INSTALL_DIR="$W/opt" GIT_USERNAME=verify-user bash < "$W/isrc/install.sh" >"$W/i2.log" 2>&1; then pass "re-run exit 0"; else fail "re-run failed:"; tail -30 "$W/i2.log"; fi
|
|
||||||
grep -qx "GIT_USERNAME=verify-user" "$W/opt/.env" && grep -qx "HOST_PORT=$hport" "$W/opt/.env" && pass "re-run replaced only the passed key, kept the rest" || fail ".env after re-run: $(grep -E '^(GIT_USERNAME|HOST_PORT|REPO_URL)=' "$W/opt/.env")"
|
|
||||||
docker exec "$iname" update --check 2>&1 | grep -q "up to date" && pass "update works in the installed container" || fail "update --check in installed container"
|
|
||||||
(cd "$W/opt" && docker compose down -v --rmi local >/dev/null 2>&1)
|
|
||||||
|
|
||||||
echo
|
|
||||||
if [ "$fails" = 0 ]; then echo "VERIFY: PASS"; exit 0; fi
|
|
||||||
echo "VERIFY: FAIL ($fails)"; keep=1; exit 1
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
# The image is built from container/ only; the source reaches the container through git.
|
|
||||||
*
|
|
||||||
!container/
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
# install.sh writes .env from this file on the server (see README).
|
|
||||||
# Gitignored. The container reads it at startup and on every `update`, so edits apply on the
|
|
||||||
# next update or restart; no rebuild. Plain KEY=value lines; quotes optional; not executed.
|
|
||||||
|
|
||||||
# The remote the container pulls the source from, and the branch/tag it follows.
|
|
||||||
REPO_URL=__REPO_URL__
|
|
||||||
REPO_REF=__BRANCH__
|
|
||||||
|
|
||||||
# Private repo over https: a read-only access token (GitHub fine-grained token with
|
|
||||||
# Contents: read, GitLab deploy token, ...). Leave empty for a public repo.
|
|
||||||
GIT_USERNAME=
|
|
||||||
GIT_TOKEN=
|
|
||||||
|
|
||||||
# Or private repo over SSH: an ssh REPO_URL (git@host:owner/repo.git) and a read-only deploy
|
|
||||||
# key, base64-encoded on one line: base64 -w0 deploy_key
|
|
||||||
GIT_SSH_KEY=
|
|
||||||
|
|
||||||
# Host port on 127.0.0.1 (used by compose, not the app).
|
|
||||||
HOST_PORT=__PORT__
|
|
||||||
|
|
||||||
# App settings go below; the app sees them as environment variables.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
.env
|
|
||||||
deploy_key*
|
|
||||||
__pycache__/
|
|
||||||
.venv/
|
|
||||||
.pytest_cache/
|
|
||||||
data/
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
# __TITLE__
|
|
||||||
|
|
||||||
A FastAPI backend serving a plain HTML/CSS/JS frontend, in one container. Nothing is compiled: no bundler, no TypeScript, no Sass. The image holds only the runtime. The source lives in a git checkout inside a volume, so a deploy is one command and needs no image rebuild.
|
|
||||||
|
|
||||||
## Layout
|
|
||||||
|
|
||||||
```
|
|
||||||
app/main.py FastAPI app: /healthz, /api, static files, index page
|
|
||||||
app/api.py JSON API routes (under /api)
|
|
||||||
app/static/ the frontend, served as is (vendor libraries into static/vendor/)
|
|
||||||
tests/ pytest
|
|
||||||
container/ Dockerfile, entrypoint (setup + supervisor), update script
|
|
||||||
compose.yml production
|
|
||||||
compose.dev.yml development overlay (bind-mounted source, auto reload)
|
|
||||||
requirements.txt runtime dependencies (pinned); requirements-dev.txt for tests
|
|
||||||
```
|
|
||||||
|
|
||||||
## Develop
|
|
||||||
|
|
||||||
The host needs only Docker and git.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose -f compose.yml -f compose.dev.yml up --build # http://127.0.0.1:__PORT__
|
|
||||||
docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
|
|
||||||
```
|
|
||||||
|
|
||||||
Python changes reload on save; frontend changes show on the next page load.
|
|
||||||
|
|
||||||
## Install on a server
|
|
||||||
|
|
||||||
On a fresh Linux server (Debian, Ubuntu, Fedora, RHEL and others), paste one line:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# public repo
|
|
||||||
curl -fsSL __INSTALL_URL__ | bash
|
|
||||||
|
|
||||||
# private repo: asks for a read-only token without echoing it
|
|
||||||
read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
|
|
||||||
```
|
|
||||||
|
|
||||||
`install.sh` does the whole setup:
|
|
||||||
- installs git and Docker (Engine and Compose) if they're missing
|
|
||||||
- checks it can read `__REPO_URL__`
|
|
||||||
- clones it into `/opt/__NAME__`
|
|
||||||
- writes `/opt/__NAME__/.env` (the repo URL, branch, credentials and port that `update` uses)
|
|
||||||
- builds the image, starts the container and waits until it is healthy
|
|
||||||
|
|
||||||
Settings such as `INSTALL_DIR`, `REPO_REF`, `HOST_PORT`, `GIT_TOKEN` and `GIT_SSH_KEY` can be passed as environment variables; the top of `install.sh` lists them. For an SSH-only private repo, copy `install.sh` to the server and run `GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh`.
|
|
||||||
|
|
||||||
Re-running the installer is safe. It keeps `.env`, replacing only the keys you pass, then updates the checkout, rebuilds and restarts. Re-run it whenever `container/` changes, or to rotate a credential.
|
|
||||||
|
|
||||||
After that, every deploy is:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git push # from your machine
|
|
||||||
docker exec __NAME__ update # on the server
|
|
||||||
```
|
|
||||||
|
|
||||||
`update` fetches, checks out the new commit, installs the requirements if they changed, checks that `app.main` imports, restarts the app process and waits until `/healthz` reports the new commit. If any step fails it goes back to the previous commit and exits non-zero. Other forms:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker exec __NAME__ update --check # what an update would bring in
|
|
||||||
docker exec __NAME__ update v1.4.0 # a tag, branch or commit
|
|
||||||
docker exec __NAME__ update --rollback # back to the commit before the last update
|
|
||||||
```
|
|
||||||
|
|
||||||
The app restarts in place, so there is a second or two of downtime while it restarts. The container itself keeps running.
|
|
||||||
|
|
||||||
A rebuild is needed only when `container/` or the Python version changes. For that, re-run the install command, or run `docker compose up -d --build` in `/opt/__NAME__`. `update` prints a reminder when an update touches `container/`.
|
|
||||||
|
|
||||||
## The `.env` file
|
|
||||||
|
|
||||||
`.env` is gitignored and stays on the machine. It is mounted read-only into the container, which reads it at startup and again on every `update`. So a changed URL, branch or rotated token takes effect on the next update, with no rebuild or recreate.
|
|
||||||
|
|
||||||
| Variable | Meaning |
|
|
||||||
|---|---|
|
|
||||||
| `REPO_URL` | The remote the container pulls from (https or SSH). Keep credentials out of the URL. |
|
|
||||||
| `REPO_REF` | The branch (or tag) that `update` follows. |
|
|
||||||
| `GIT_TOKEN`, `GIT_USERNAME` | Private repo over https: a read-only token. A git credential helper supplies it, so it is never written into the checkout. |
|
|
||||||
| `GIT_SSH_KEY` | Private repo over SSH: a read-only deploy key, base64-encoded on one line (`base64 -w0 deploy_key`). |
|
|
||||||
| anything else | App settings. The app sees them as environment variables; it never sees the git credentials. |
|
|
||||||
|
|
||||||
`install.sh` writes `.env` owned by uid 1000 (the container's user) with mode 640. If you set up by hand, do the same, and create `.env` before the first `docker compose up`: if it is missing, Docker creates an empty directory in its place, and the container stops with an error saying so.
|
|
||||||
|
|
||||||
## Data and config
|
|
||||||
|
|
||||||
- Persistent app data goes under `$DATA_DIR` (`/data`, the `data` volume). Back up that volume.
|
|
||||||
- Configuration and secrets live in `.env`, never in the repo.
|
|
||||||
- Do startup work (creating tables, migrations) in `lifespan` in `app/main.py`, and make it idempotent. Don't do it at import time: `update` imports the app as a check before it restarts it.
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
"""JSON API, mounted under /api. Split into a package (app/api/<area>.py) as it grows."""
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
from fastapi import APIRouter
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/info")
|
|
||||||
def info() -> dict:
|
|
||||||
return {"name": "__TITLE__", "version": os.environ.get("APP_VERSION", "dev")}
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
"""__TITLE__: FastAPI backend serving a no-build static frontend from app/static."""
|
|
||||||
|
|
||||||
import contextlib
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from fastapi import FastAPI
|
|
||||||
from fastapi.responses import FileResponse
|
|
||||||
from fastapi.staticfiles import StaticFiles
|
|
||||||
|
|
||||||
from app import api
|
|
||||||
|
|
||||||
VERSION = os.environ.get("APP_VERSION", "dev")
|
|
||||||
STATIC = Path(__file__).parent / "static"
|
|
||||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
|
|
||||||
|
|
||||||
|
|
||||||
@contextlib.asynccontextmanager
|
|
||||||
async def lifespan(_app: FastAPI):
|
|
||||||
# Startup work goes here, not at import time: `update` imports this module as a check
|
|
||||||
# before restarting. Create tables or run migrations idempotently here.
|
|
||||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
||||||
yield
|
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="__TITLE__", version=VERSION, lifespan=lifespan, docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
|
|
||||||
app.include_router(api.router, prefix="/api")
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/healthz", include_in_schema=False)
|
|
||||||
def healthz() -> dict:
|
|
||||||
# `update` waits for this to report the new commit before it calls the update done.
|
|
||||||
return {"status": "ok", "version": VERSION}
|
|
||||||
|
|
||||||
|
|
||||||
class Assets(StaticFiles):
|
|
||||||
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
|
|
||||||
|
|
||||||
async def get_response(self, path, scope):
|
|
||||||
response = await super().get_response(path, scope)
|
|
||||||
response.headers["Cache-Control"] = "no-cache"
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
app.mount("/static", Assets(directory=STATIC), name="static")
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/", include_in_schema=False)
|
|
||||||
def index() -> FileResponse:
|
|
||||||
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
/* App styles on top of tokens.css. Plain CSS, no preprocessor. */
|
|
||||||
.wrap { max-width: var(--content-max); margin-inline: auto; padding-inline: var(--gutter); }
|
|
||||||
|
|
||||||
.topbar { border-bottom: 1px solid var(--border); background: var(--surface); }
|
|
||||||
.topbar-inner { display: flex; align-items: center; justify-content: space-between; gap: var(--space-4); height: 3.5rem; }
|
|
||||||
.brand { font-weight: var(--weight-semibold); color: var(--fg); text-decoration: none; }
|
|
||||||
|
|
||||||
main.wrap { display: grid; gap: var(--space-6); padding-block: var(--space-12); }
|
|
||||||
.lead { font-size: var(--text-lg); color: var(--fg-muted); max-width: var(--measure); margin: 0; }
|
|
||||||
h1 { margin: 0; text-wrap: balance; }
|
|
||||||
|
|
||||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md); padding: var(--space-5); max-width: 32rem; }
|
|
||||||
.card h2 { margin: 0 0 var(--space-2); }
|
|
||||||
.card p { margin: 0; }
|
|
||||||
|
|
||||||
.badge { display: inline-flex; align-items: center; height: 1.375rem; padding-inline: var(--space-2);
|
|
||||||
font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono); border-radius: var(--radius-full);
|
|
||||||
background: var(--surface-2); color: var(--fg-muted); }
|
|
||||||
.ok { color: var(--ok); }
|
|
||||||
.error { color: var(--danger); }
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title>__TITLE__</title>
|
|
||||||
<link rel="stylesheet" href="/static/css/tokens.css">
|
|
||||||
<link rel="stylesheet" href="/static/css/app.css">
|
|
||||||
<script type="module" src="/static/js/main.js"></script>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<header class="topbar">
|
|
||||||
<div class="wrap topbar-inner">
|
|
||||||
<a class="brand" href="/">__TITLE__</a>
|
|
||||||
<span class="badge" id="version" title="Running commit">…</span>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<main class="wrap">
|
|
||||||
<h1>__TITLE__</h1>
|
|
||||||
<p class="lead">FastAPI serves this page and the JSON API under <code>/api</code>. Edit <code>app/static</code> and reload; there is no build step.</p>
|
|
||||||
<section class="card" aria-labelledby="status-heading">
|
|
||||||
<h2 id="status-heading" class="label">Server</h2>
|
|
||||||
<p id="status" aria-live="polite">Checking…</p>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
|
|
||||||
export async function getJSON(path, options = {}) {
|
|
||||||
const response = await fetch(path, { headers: { Accept: "application/json" }, ...options });
|
|
||||||
if (!response.ok) {
|
|
||||||
let detail = response.statusText;
|
|
||||||
try { detail = (await response.json()).detail ?? detail; } catch {}
|
|
||||||
throw new Error(`${response.status} ${detail}`);
|
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function postJSON(path, body) {
|
|
||||||
return getJSON(path, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body) });
|
|
||||||
}
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
// Plain ES modules, no bundler. Vendor any library into /static/vendor and import it by path.
|
|
||||||
import { getJSON } from "./api.js";
|
|
||||||
|
|
||||||
const status = document.getElementById("status");
|
|
||||||
const version = document.getElementById("version");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const info = await getJSON("/api/info");
|
|
||||||
version.textContent = info.version;
|
|
||||||
status.textContent = `Running ${info.name} at commit ${info.version}.`;
|
|
||||||
status.className = "ok";
|
|
||||||
} catch (err) {
|
|
||||||
status.textContent = `Could not reach the API: ${err.message}`;
|
|
||||||
status.className = "error";
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# Local development: the source is this folder, bind-mounted, and uvicorn reloads on save.
|
|
||||||
# docker compose -f compose.yml -f compose.dev.yml up --build
|
|
||||||
# docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
|
|
||||||
# `update` is disabled in dev; use git on the host. Separate project name = separate volumes.
|
|
||||||
name: __NAME__-dev
|
|
||||||
services:
|
|
||||||
app:
|
|
||||||
container_name: __NAME__-dev
|
|
||||||
environment:
|
|
||||||
DEV: "1"
|
|
||||||
CONTAINER_NAME: __NAME__-dev
|
|
||||||
volumes:
|
|
||||||
- .:/srv/src
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
# Production. install.sh sets this up on a server (see README); by hand it is:
|
|
||||||
# clone into /opt/__NAME__, write .env from .env.example, docker compose up -d --build
|
|
||||||
# Deploys after that: docker exec __NAME__ update
|
|
||||||
name: __NAME__
|
|
||||||
services:
|
|
||||||
app:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: container/Dockerfile
|
|
||||||
image: __NAME__:latest
|
|
||||||
container_name: __NAME__
|
|
||||||
restart: unless-stopped
|
|
||||||
environment:
|
|
||||||
CONTAINER_NAME: __NAME__
|
|
||||||
# Only a reverse proxy at these addresses may set X-Forwarded-For.
|
|
||||||
FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-127.0.0.1}
|
|
||||||
# Loopback only: put a reverse proxy or tunnel in front of it.
|
|
||||||
ports:
|
|
||||||
- "127.0.0.1:${HOST_PORT:-__PORT__}:8000"
|
|
||||||
volumes:
|
|
||||||
- runtime:/srv # source checkout, venv, update state
|
|
||||||
- data:/data # the app's persistent data
|
|
||||||
# Repo URL, credentials and app settings, read on every start and every update.
|
|
||||||
# Not env_file: a mounted file can change without recreating the container.
|
|
||||||
- ./.env:/run/config/app.env:ro
|
|
||||||
read_only: true
|
|
||||||
tmpfs:
|
|
||||||
- /tmp
|
|
||||||
cap_drop: [ALL]
|
|
||||||
security_opt:
|
|
||||||
- no-new-privileges:true
|
|
||||||
mem_limit: 256m
|
|
||||||
logging:
|
|
||||||
driver: json-file
|
|
||||||
options:
|
|
||||||
max-size: 10m
|
|
||||||
max-file: "3"
|
|
||||||
volumes:
|
|
||||||
runtime:
|
|
||||||
data:
|
|
||||||
|
|
@ -1,35 +0,0 @@
|
||||||
# The image is the runtime only: Python, git and the scripts in this folder. The app's
|
|
||||||
# source is cloned into the /srv volume on first start and updated in place by `update`,
|
|
||||||
# so a rebuild is needed only when this folder or the Python version changes.
|
|
||||||
ARG PYTHON_VERSION=__PYTHON__
|
|
||||||
FROM python:${PYTHON_VERSION}-slim
|
|
||||||
|
|
||||||
RUN apt-get update \
|
|
||||||
&& apt-get install -y --no-install-recommends git openssh-client tini \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
ARG UID=1000
|
|
||||||
ARG GID=1000
|
|
||||||
RUN groupadd --gid "$GID" app \
|
|
||||||
&& useradd --uid "$UID" --gid app --create-home --shell /usr/sbin/nologin app \
|
|
||||||
&& mkdir -p /srv/src /srv/venv /srv/state /data \
|
|
||||||
&& chown -R app:app /srv /data \
|
|
||||||
&& git config --system --add safe.directory '*'
|
|
||||||
|
|
||||||
COPY container/lib.sh /usr/local/lib/app/lib.sh
|
|
||||||
COPY --chmod=755 container/entrypoint.sh /usr/local/bin/entrypoint
|
|
||||||
COPY --chmod=755 container/update.sh /usr/local/bin/update
|
|
||||||
|
|
||||||
ENV PATH=/srv/venv/bin:$PATH \
|
|
||||||
PYTHONDONTWRITEBYTECODE=1 \
|
|
||||||
PYTHONUNBUFFERED=1 \
|
|
||||||
PIP_NO_CACHE_DIR=1 \
|
|
||||||
DATA_DIR=/data \
|
|
||||||
PORT=8000
|
|
||||||
|
|
||||||
USER app
|
|
||||||
WORKDIR /srv/src
|
|
||||||
EXPOSE 8000
|
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
|
||||||
CMD python3 -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/healthz', timeout=3)"
|
|
||||||
ENTRYPOINT ["tini", "--", "entrypoint"]
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Container entrypoint (runs under tini). Gets the source and venv ready, then supervises
|
|
||||||
# uvicorn: SIGHUP restarts the app on the current checkout (that's how `update` swaps code
|
|
||||||
# in without restarting the container); SIGTERM stops it. If the app dies on its own, the
|
|
||||||
# container exits and Docker's restart policy takes over.
|
|
||||||
#
|
|
||||||
# With arguments, it runs them in the source dir after setup instead, e.g.
|
|
||||||
# docker compose run --rm app pytest
|
|
||||||
set -uo pipefail
|
|
||||||
. /usr/local/lib/app/lib.sh
|
|
||||||
|
|
||||||
load_env
|
|
||||||
ensure_source || exit 1
|
|
||||||
sync_deps || die "installing requirements failed"
|
|
||||||
cd "$SRC"
|
|
||||||
|
|
||||||
if [ $# -gt 0 ]; then
|
|
||||||
export PATH="$VENV/bin:$PATH"
|
|
||||||
exec "$@"
|
|
||||||
fi
|
|
||||||
|
|
||||||
child=
|
|
||||||
stopping=0
|
|
||||||
restart=0
|
|
||||||
trap 'stopping=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT
|
|
||||||
trap 'restart=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' HUP
|
|
||||||
echo $$ > "$PIDFILE"
|
|
||||||
|
|
||||||
start_app() {
|
|
||||||
local args=(app.main:app --host 0.0.0.0 --port "$PORT"
|
|
||||||
--proxy-headers --forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}"
|
|
||||||
--no-server-header --timeout-graceful-shutdown 10)
|
|
||||||
[ "${DEV:-}" = 1 ] && args+=(--reload)
|
|
||||||
export APP_VERSION
|
|
||||||
APP_VERSION=$(current_version)
|
|
||||||
log "starting app at $APP_VERSION"
|
|
||||||
env "${APP_ENV_UNSET[@]}" "$VENV/bin/uvicorn" "${args[@]}" &
|
|
||||||
child=$!
|
|
||||||
}
|
|
||||||
|
|
||||||
while :; do
|
|
||||||
start_app
|
|
||||||
wait "$child"; rc=$?
|
|
||||||
# A trapped signal interrupts `wait` while the child is still shutting down.
|
|
||||||
while kill -0 "$child" 2>/dev/null; do wait "$child"; rc=$?; done
|
|
||||||
[ "$stopping" = 1 ] && exit 0
|
|
||||||
if [ "$restart" = 1 ]; then restart=0; continue; fi
|
|
||||||
log "app exited with status $rc"
|
|
||||||
# New code that crashes at startup must not take the container down mid-update, or
|
|
||||||
# `update` dies with it and can't roll back. Wait for its restart signal instead.
|
|
||||||
if ! flock -n /tmp/app-update.lock true; then
|
|
||||||
log "an update is running; waiting for it to restart the app"
|
|
||||||
while [ "$restart" = 0 ] && [ "$stopping" = 0 ]; do sleep 1 & wait $!; done
|
|
||||||
[ "$stopping" = 1 ] && exit 0
|
|
||||||
restart=0; continue
|
|
||||||
fi
|
|
||||||
exit "$rc"
|
|
||||||
done
|
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
# Shared by entrypoint and update. Installed at /usr/local/lib/app/lib.sh.
|
|
||||||
# Config: the project .env, mounted at /run/config/app.env, read by load_env.
|
|
||||||
# Layout inside the container:
|
|
||||||
# /srv/src git checkout of the app (cloned from REPO_URL on first start, or bind-mounted in dev)
|
|
||||||
# /srv/venv virtualenv built from requirements.txt (rebuilt when requirements or Python change)
|
|
||||||
# /srv/state update bookkeeping (previous commit, ssh known_hosts)
|
|
||||||
# /data the app's own persistent data
|
|
||||||
# /srv is one named volume, so source, venv and state survive container recreation.
|
|
||||||
|
|
||||||
SRC=${SRC:-/srv/src}
|
|
||||||
VENV=${VENV:-/srv/venv}
|
|
||||||
STATE=${STATE:-/srv/state}
|
|
||||||
PORT=${PORT:-8000}
|
|
||||||
PIDFILE=/tmp/app-supervisor.pid
|
|
||||||
ENV_FILE=${ENV_FILE:-/run/config/app.env}
|
|
||||||
|
|
||||||
log() { echo "[$(basename "$0")] $*" >&2; }
|
|
||||||
die() { log "error: $*"; exit 1; }
|
|
||||||
|
|
||||||
# Read the project's .env (bind-mounted read-only at $ENV_FILE). It runs on every start
|
|
||||||
# and every update, so a new URL or rotated token takes effect without a rebuild.
|
|
||||||
# Plain KEY=value lines only; it is parsed, not executed. Values never get printed.
|
|
||||||
load_env() {
|
|
||||||
[ -e "$ENV_FILE" ] || return 0
|
|
||||||
[ -f "$ENV_FILE" ] || die "$ENV_FILE is not a file (create .env before 'docker compose up'; Docker made a directory in its place)"
|
|
||||||
[ -r "$ENV_FILE" ] || die "$ENV_FILE is not readable by uid $(id -u): chown $(id -u) .env && chmod 600 .env on the host"
|
|
||||||
local line key val
|
|
||||||
while IFS= read -r line || [ -n "$line" ]; do
|
|
||||||
line=${line%$'\r'}
|
|
||||||
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
|
||||||
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
|
||||||
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
|
||||||
export "$key=$val"
|
|
||||||
done < "$ENV_FILE"
|
|
||||||
setup_git_auth
|
|
||||||
}
|
|
||||||
|
|
||||||
# Credentials for REPO_URL, from the environment only. Nothing is written into the checkout:
|
|
||||||
# https: GIT_TOKEN (+ GIT_USERNAME, default x-access-token) answered by a credential helper
|
|
||||||
# ssh: GIT_SSH_KEY, the private key base64-encoded (base64 -w0 deploy_key)
|
|
||||||
setup_git_auth() {
|
|
||||||
if [ -n "${GIT_TOKEN:-}" ]; then
|
|
||||||
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
|
||||||
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
|
||||||
fi
|
|
||||||
local ssh="ssh -o UserKnownHostsFile=$STATE/known_hosts -o StrictHostKeyChecking=accept-new"
|
|
||||||
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
|
||||||
local key=/tmp/git-deploy-key
|
|
||||||
(umask 077; printf '%s' "$GIT_SSH_KEY" | base64 -d > "$key") || die "GIT_SSH_KEY is not valid base64"
|
|
||||||
ssh="$ssh -i $key -o IdentitiesOnly=yes"
|
|
||||||
fi
|
|
||||||
export GIT_SSH_COMMAND="$ssh" GIT_TERMINAL_PROMPT=0
|
|
||||||
}
|
|
||||||
|
|
||||||
# Hide user:password@ if someone put credentials in the URL anyway.
|
|
||||||
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
|
||||||
|
|
||||||
# The app gets the .env settings but not the repo credentials.
|
|
||||||
APP_ENV_UNSET=(-u GIT_TOKEN -u GIT_USERNAME -u GIT_SSH_KEY -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0)
|
|
||||||
|
|
||||||
# Clone the source on first start. A bind-mounted checkout (dev) already has .git.
|
|
||||||
ensure_source() {
|
|
||||||
mkdir -p "$STATE"
|
|
||||||
[ -d "$SRC/.git" ] && return 0
|
|
||||||
[ -n "${REPO_URL:-}" ] || die "no source at $SRC and REPO_URL is not set in .env"
|
|
||||||
log "cloning $(redact "$REPO_URL") (${REPO_REF:-main}) into $SRC"
|
|
||||||
# $SRC may exist as an empty dir; clone into it.
|
|
||||||
git clone --quiet --branch "${REPO_REF:-main}" "$REPO_URL" "$SRC"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Follow REPO_URL if .env changed it. Credentials are never part of the stored URL.
|
|
||||||
sync_remote() {
|
|
||||||
[ -n "${REPO_URL:-}" ] || return 0
|
|
||||||
[ "$(git -C "$SRC" remote get-url origin 2>/dev/null)" = "$REPO_URL" ] || git -C "$SRC" remote set-url origin "$REPO_URL"
|
|
||||||
}
|
|
||||||
|
|
||||||
requirement_files() {
|
|
||||||
echo "$SRC/requirements.txt"
|
|
||||||
if [ "${DEV:-}" = 1 ] && [ -f "$SRC/requirements-dev.txt" ]; then echo "$SRC/requirements-dev.txt"; fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# Bring the venv in line with the checkout. A no-op when nothing changed.
|
|
||||||
sync_deps() {
|
|
||||||
local py want files
|
|
||||||
py=$(python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')
|
|
||||||
mapfile -t files < <(requirement_files)
|
|
||||||
want="$py $(cat "${files[@]}" | sha256sum | cut -d' ' -f1)"
|
|
||||||
if [ "$(cat "$VENV/.python" 2>/dev/null)" != "$py" ]; then
|
|
||||||
log "creating venv for Python $py"
|
|
||||||
rm -rf "$VENV"
|
|
||||||
python3 -m venv "$VENV"
|
|
||||||
echo "$py" > "$VENV/.python"
|
|
||||||
fi
|
|
||||||
[ "$(cat "$VENV/.synced" 2>/dev/null)" = "$want" ] && return 0
|
|
||||||
log "installing requirements"
|
|
||||||
local args=()
|
|
||||||
for f in "${files[@]}"; do args+=(-r "$f"); done
|
|
||||||
"$VENV/bin/pip" install --quiet --disable-pip-version-check --no-cache-dir "${args[@]}" || return 1
|
|
||||||
echo "$want" > "$VENV/.synced"
|
|
||||||
}
|
|
||||||
|
|
||||||
# The new code must at least import before it replaces the running app.
|
|
||||||
check_import() {
|
|
||||||
(cd "$SRC" && "$VENV/bin/python" -c 'import app.main') || return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
current_version() { git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo dev; }
|
|
||||||
|
|
||||||
# Wait until /healthz answers with the expected version (or any version if none given).
|
|
||||||
wait_healthy() {
|
|
||||||
local want=${1:-} timeout=${HEALTH_TIMEOUT:-30} got
|
|
||||||
for _ in $(seq 1 "$timeout"); do
|
|
||||||
got=$(python3 - "$PORT" <<'PY' 2>/dev/null
|
|
||||||
import json, sys, urllib.request
|
|
||||||
r = urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/healthz", timeout=2)
|
|
||||||
print(json.load(r).get("version", ""))
|
|
||||||
PY
|
|
||||||
) && { [ -z "$want" ] || [ "$got" = "$want" ]; } && return 0
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
@ -1,81 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Pull the latest source from the remote repo in .env (REPO_URL, REPO_REF and credentials)
|
|
||||||
# into the running container and restart the app on it. No rebuild.
|
|
||||||
# docker exec <container> update # to the tip of REPO_REF
|
|
||||||
# docker exec <container> update <ref> # to a tag, branch or commit
|
|
||||||
# docker exec <container> update --check # show what an update would bring in
|
|
||||||
# docker exec <container> update --rollback # back to the commit before the last update
|
|
||||||
# Steps: fetch, check out, sync requirements, import check, restart, wait for /healthz to
|
|
||||||
# report the new commit. If any step fails, it puts the previous commit back and exits 1.
|
|
||||||
set -euo pipefail
|
|
||||||
. /usr/local/lib/app/lib.sh
|
|
||||||
|
|
||||||
usage() { sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
|
|
||||||
|
|
||||||
mode=update force=0 ref=
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case $1 in
|
|
||||||
--check) mode=check ;;
|
|
||||||
--rollback) mode=rollback ;;
|
|
||||||
--force) force=1 ;;
|
|
||||||
-h|--help) usage ;;
|
|
||||||
-*) usage 1 ;;
|
|
||||||
*) ref=$1 ;;
|
|
||||||
esac
|
|
||||||
shift
|
|
||||||
done
|
|
||||||
|
|
||||||
load_env
|
|
||||||
[ "${DEV:-}" = 1 ] && die "dev mode: the source is bind-mounted from the host; update it with git there"
|
|
||||||
[ -d "$SRC/.git" ] || die "no checkout at $SRC"
|
|
||||||
exec 9>/tmp/app-update.lock
|
|
||||||
flock -n 9 || die "another update is running"
|
|
||||||
cd "$SRC"
|
|
||||||
|
|
||||||
old=$(git rev-parse HEAD)
|
|
||||||
if [ "$mode" = rollback ]; then
|
|
||||||
new=$(cat "$STATE/previous" 2>/dev/null) || die "no previous commit recorded"
|
|
||||||
else
|
|
||||||
sync_remote
|
|
||||||
git fetch --quiet --prune --tags origin
|
|
||||||
target=${ref:-${REPO_REF:-main}}
|
|
||||||
# A branch resolves on the remote; a tag or commit as given.
|
|
||||||
new=$(git rev-parse --verify --quiet "origin/$target^{commit}" || git rev-parse --verify --quiet "$target^{commit}") \
|
|
||||||
|| die "unknown ref: $target"
|
|
||||||
fi
|
|
||||||
short() { git rev-parse --short "$1"; }
|
|
||||||
|
|
||||||
if [ "$mode" = check ]; then
|
|
||||||
if [ "$old" = "$new" ]; then echo "up to date at $(short "$old")"; else
|
|
||||||
echo "$(short "$old") -> $(short "$new")"
|
|
||||||
git log --oneline "$old..$new" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
[ "$old" = "$new" ] && { echo "already at $(short "$new")"; exit 0; }
|
|
||||||
|
|
||||||
if [ "$force" = 0 ] && [ -n "$(git status --porcelain --untracked-files=no)" ]; then
|
|
||||||
die "the checkout has local changes (inspect with: docker exec ${CONTAINER_NAME:-<container>} git -C $SRC status); --force discards them"
|
|
||||||
fi
|
|
||||||
|
|
||||||
restart_app() { kill -HUP "$(cat "$PIDFILE")" || return 1; sleep 1; }
|
|
||||||
apply() { git reset --quiet --hard "$1" && sync_deps && check_import; }
|
|
||||||
|
|
||||||
restarted=0
|
|
||||||
log "updating $(short "$old") -> $(short "$new")"
|
|
||||||
if apply "$new" && restarted=1 && restart_app && wait_healthy "$(short "$new")"; then
|
|
||||||
echo "$old" > "$STATE/previous"
|
|
||||||
git log --oneline "$old..$new" 2>/dev/null | head -20 || true
|
|
||||||
if [ -n "$(git diff --name-only "$old" "$new" -- container/)" ]; then
|
|
||||||
log "note: container/ changed; rebuild the image to pick that up (docker compose up -d --build)"
|
|
||||||
fi
|
|
||||||
echo "updated to $(short "$new")"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "update failed; going back to $(short "$old")"
|
|
||||||
apply "$old" || die "could not restore $(short "$old"): the app may be down, check: docker logs ${CONTAINER_NAME:-<container>}"
|
|
||||||
[ "$restarted" = 1 ] || { log "the running app was never touched"; exit 1; }
|
|
||||||
restart_app && wait_healthy "$(short "$old")" || die "restored $(short "$old") but it is not healthy; check: docker logs ${CONTAINER_NAME:-<container>}"
|
|
||||||
log "running $(short "$old") again"
|
|
||||||
exit 1
|
|
||||||
|
|
@ -1,232 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Install (or upgrade) __TITLE__ on a Linux server. Paste one line into a fresh server:
|
|
||||||
#
|
|
||||||
# Public repo:
|
|
||||||
# curl -fsSL __INSTALL_URL__ | bash
|
|
||||||
#
|
|
||||||
# Private repo over https (the token is asked for, not typed into history):
|
|
||||||
# read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
|
|
||||||
#
|
|
||||||
# Private repo over SSH: copy this file to the server, then
|
|
||||||
# GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh
|
|
||||||
#
|
|
||||||
# What it does: installs git and Docker (Engine + Compose) if missing, clones the repo into
|
|
||||||
# $INSTALL_DIR, writes $INSTALL_DIR/.env (repo URL, branch, credentials, port) for the
|
|
||||||
# container's `update`, builds the image, starts the container and waits until it is
|
|
||||||
# healthy. Re-running it is safe: it keeps .env (values you pass replace those keys),
|
|
||||||
# pulls the checkout, rebuilds the image and restarts. Run it again whenever container/
|
|
||||||
# changes; for ordinary deploys use `docker exec __NAME__ update`.
|
|
||||||
#
|
|
||||||
# Settings (environment variables, all optional):
|
|
||||||
# INSTALL_DIR default /opt/__NAME__
|
|
||||||
# REPO_URL default __REPO_URL__
|
|
||||||
# REPO_REF default __BRANCH__
|
|
||||||
# GIT_TOKEN, GIT_USERNAME private repo over https
|
|
||||||
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
|
|
||||||
# HOST_PORT default __PORT__ (bound to 127.0.0.1)
|
|
||||||
#
|
|
||||||
# Everything is inside main(), so a partial download runs nothing.
|
|
||||||
|
|
||||||
main() {
|
|
||||||
set -euo pipefail
|
|
||||||
local NAME=__NAME__
|
|
||||||
INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME}
|
|
||||||
local DEFAULT_REPO_URL="__REPO_URL__" DEFAULT_REF="__BRANCH__" DEFAULT_PORT="__PORT__"
|
|
||||||
# Which keys the caller passed explicitly (these replace values in an existing .env).
|
|
||||||
local passed=()
|
|
||||||
for k in REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT; do
|
|
||||||
[ -n "${!k:-}" ] && passed+=("$k")
|
|
||||||
done
|
|
||||||
|
|
||||||
[ "$(uname -s)" = Linux ] || die "this installer is for Linux servers"
|
|
||||||
SUDO=
|
|
||||||
if [ "$(id -u)" != 0 ]; then
|
|
||||||
command -v sudo >/dev/null || die "run as root, or install sudo"
|
|
||||||
SUDO=sudo
|
|
||||||
fi
|
|
||||||
|
|
||||||
step "prerequisites"
|
|
||||||
install_packages
|
|
||||||
install_docker
|
|
||||||
|
|
||||||
step "source"
|
|
||||||
load_existing_env
|
|
||||||
REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL}
|
|
||||||
REPO_REF=${REPO_REF:-$DEFAULT_REF}
|
|
||||||
HOST_PORT=${HOST_PORT:-$DEFAULT_PORT}
|
|
||||||
git_auth
|
|
||||||
check_access
|
|
||||||
checkout
|
|
||||||
|
|
||||||
step "configuration"
|
|
||||||
write_env
|
|
||||||
|
|
||||||
step "container"
|
|
||||||
(cd "$INSTALL_DIR" && $DOCKER compose up -d --build --remove-orphans)
|
|
||||||
wait_healthy
|
|
||||||
|
|
||||||
step "done"
|
|
||||||
cat <<EOF
|
|
||||||
$NAME is running at $(health_version) on http://127.0.0.1:$HOST_PORT (loopback; put a reverse proxy or tunnel in front).
|
|
||||||
deploy a new commit: docker exec $NAME update
|
|
||||||
see what's new: docker exec $NAME update --check
|
|
||||||
undo the last update: docker exec $NAME update --rollback
|
|
||||||
logs: docker logs -f $NAME
|
|
||||||
settings: $INSTALL_DIR/.env (re-read on every update)
|
|
||||||
rebuild/upgrade: run this installer again
|
|
||||||
EOF
|
|
||||||
[ "$DOCKER" = docker ] || echo " (prefix docker with sudo, or add yourself to the docker group)"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Run a command directly, and only with sudo if that fails (no password prompt when not needed).
|
|
||||||
priv() { "$@" 2>/dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; }
|
|
||||||
read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; }
|
|
||||||
|
|
||||||
step() { printf '\n==> %s\n' "$*"; }
|
|
||||||
log() { printf ' %s\n' "$*"; }
|
|
||||||
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
|
|
||||||
|
|
||||||
install_packages() {
|
|
||||||
local need=()
|
|
||||||
command -v git >/dev/null || need+=(git)
|
|
||||||
command -v curl >/dev/null || need+=(curl)
|
|
||||||
command -v ssh >/dev/null || need+=(ssh)
|
|
||||||
[ ${#need[@]} -eq 0 ] && { log "git, curl, ssh: present"; return; }
|
|
||||||
log "installing ${need[*]}"
|
|
||||||
if command -v apt-get >/dev/null; then
|
|
||||||
local pkgs=("${need[@]/ssh/openssh-client}")
|
|
||||||
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq
|
|
||||||
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates "${pkgs[@]}" >/dev/null
|
|
||||||
elif command -v dnf >/dev/null; then
|
|
||||||
$SUDO dnf install -y -q ca-certificates "${need[@]/ssh/openssh-clients}"
|
|
||||||
elif command -v apk >/dev/null; then
|
|
||||||
$SUDO apk add -q ca-certificates "${need[@]/ssh/openssh-client}"
|
|
||||||
else
|
|
||||||
die "no apt-get, dnf or apk: install ${need[*]} yourself and re-run"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
install_docker() {
|
|
||||||
if ! command -v docker >/dev/null; then
|
|
||||||
log "installing Docker Engine + Compose (get.docker.com)"
|
|
||||||
local dlog; dlog=$(mktemp)
|
|
||||||
curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; }
|
|
||||||
rm -f "$dlog"
|
|
||||||
fi
|
|
||||||
if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \
|
|
||||||
&& command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then
|
|
||||||
$SUDO systemctl enable --now docker >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi
|
|
||||||
$DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running"
|
|
||||||
$DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)"
|
|
||||||
log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Values already in .env fill in whatever the caller did not pass.
|
|
||||||
load_existing_env() {
|
|
||||||
local f="$INSTALL_DIR/.env" line key val
|
|
||||||
[ -f "$f" ] || return 0
|
|
||||||
log "keeping existing $f"
|
|
||||||
while IFS= read -r line || [ -n "$line" ]; do
|
|
||||||
line=${line%$'\r'}
|
|
||||||
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
|
|
||||||
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
|
|
||||||
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
|
|
||||||
case $key in REPO_URL|REPO_REF|GIT_TOKEN|GIT_USERNAME|GIT_SSH_KEY|HOST_PORT)
|
|
||||||
[ -n "${!key:-}" ] || printf -v "$key" '%s' "$val" ;;
|
|
||||||
esac
|
|
||||||
done < <(read_file "$f")
|
|
||||||
}
|
|
||||||
|
|
||||||
# Credentials reach git through the environment only; nothing is stored in the checkout.
|
|
||||||
git_auth() {
|
|
||||||
export GIT_TERMINAL_PROMPT=0
|
|
||||||
if [ -n "${GIT_TOKEN:-}" ]; then
|
|
||||||
export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}"
|
|
||||||
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
|
|
||||||
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
|
|
||||||
fi
|
|
||||||
local ssh="ssh -o StrictHostKeyChecking=accept-new"
|
|
||||||
if [ -n "${GIT_SSH_KEY:-}" ]; then
|
|
||||||
KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT
|
|
||||||
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)"
|
|
||||||
ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes"
|
|
||||||
fi
|
|
||||||
export GIT_SSH_COMMAND="$ssh"
|
|
||||||
}
|
|
||||||
|
|
||||||
check_access() {
|
|
||||||
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; }
|
|
||||||
# Private https repo and no token yet: ask on the terminal (stdin is this script).
|
|
||||||
if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then
|
|
||||||
printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty
|
|
||||||
IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty
|
|
||||||
passed+=(GIT_TOKEN)
|
|
||||||
git_auth
|
|
||||||
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; }
|
|
||||||
fi
|
|
||||||
die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo"
|
|
||||||
}
|
|
||||||
|
|
||||||
# The host checkout holds compose.yml and container/ (what the image is built from).
|
|
||||||
# The app itself runs from the container's own checkout, which `update` manages.
|
|
||||||
checkout() {
|
|
||||||
if [ ! -d "$INSTALL_DIR/.git" ]; then
|
|
||||||
priv mkdir -p "$INSTALL_DIR"
|
|
||||||
[ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
|
|
||||||
[ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME"
|
|
||||||
log "new checkout in $INSTALL_DIR"
|
|
||||||
git -C "$INSTALL_DIR" init --quiet
|
|
||||||
git -C "$INSTALL_DIR" remote add origin "$REPO_URL"
|
|
||||||
fi
|
|
||||||
# First install and re-runs alike: fetch and check out REPO_REF.
|
|
||||||
git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"
|
|
||||||
git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin
|
|
||||||
local target
|
|
||||||
target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}")
|
|
||||||
git -C "$INSTALL_DIR" reset --quiet --hard "$target"
|
|
||||||
log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')"
|
|
||||||
}
|
|
||||||
|
|
||||||
# .env: created from .env.example on first install; on re-runs only the keys the caller
|
|
||||||
# passed are replaced. Owned by uid 1000 (the container's user), group = installer, mode 640.
|
|
||||||
write_env() {
|
|
||||||
local f="$INSTALL_DIR/.env" tmp line key out=() seen=" "
|
|
||||||
if [ -f "$f" ]; then mapfile -t lines < <(read_file "$f"); else
|
|
||||||
mapfile -t lines < "$INSTALL_DIR/.env.example"
|
|
||||||
passed=(REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT)
|
|
||||||
log "writing $f"
|
|
||||||
fi
|
|
||||||
for line in "${lines[@]}"; do
|
|
||||||
key=${line%%=*}
|
|
||||||
if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && [[ " ${passed[*]} " == *" $key "* ]]; then
|
|
||||||
out+=("$key=${!key:-}"); seen+="$key "
|
|
||||||
else out+=("$line"); fi
|
|
||||||
done
|
|
||||||
for key in "${passed[@]}"; do [[ $seen == *" $key "* ]] || out+=("$key=${!key:-}"); done
|
|
||||||
tmp=$(mktemp)
|
|
||||||
printf '%s\n' "${out[@]}" > "$tmp"
|
|
||||||
priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f"
|
|
||||||
rm -f "$tmp"
|
|
||||||
[ ${#passed[@]} -eq 0 ] || log "set in .env: ${passed[*]}"
|
|
||||||
}
|
|
||||||
|
|
||||||
health_version() {
|
|
||||||
$DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen(f"http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null
|
|
||||||
}
|
|
||||||
|
|
||||||
wait_healthy() {
|
|
||||||
log "waiting for the app (first start clones the repo and installs requirements)"
|
|
||||||
for _ in $(seq 1 180); do
|
|
||||||
[ -n "$(health_version)" ] && { log "healthy at $(health_version)"; return; }
|
|
||||||
[ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ] && break
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
$DOCKER logs --tail 40 "$NAME" >&2 || true
|
|
||||||
die "$NAME did not become healthy (logs above)"
|
|
||||||
}
|
|
||||||
|
|
||||||
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
[pytest]
|
|
||||||
testpaths = tests
|
|
||||||
pythonpath = .
|
|
||||||
# The source may be a read-only or foreign-owned bind mount; don't write a cache into it.
|
|
||||||
addopts = -p no:cacheprovider
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
pytest==__PYTEST__
|
|
||||||
httpx2==__HTTPX__
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
fastapi==__FASTAPI__
|
|
||||||
uvicorn[standard]==__UVICORN__
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
from fastapi.testclient import TestClient
|
|
||||||
|
|
||||||
from app.main import app
|
|
||||||
|
|
||||||
|
|
||||||
def test_healthz():
|
|
||||||
with TestClient(app) as client:
|
|
||||||
response = client.get("/healthz")
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json()["status"] == "ok"
|
|
||||||
|
|
||||||
|
|
||||||
def test_index_and_assets():
|
|
||||||
with TestClient(app) as client:
|
|
||||||
page = client.get("/")
|
|
||||||
css = client.get("/static/css/app.css")
|
|
||||||
assert page.status_code == 200 and "__TITLE__" in page.text
|
|
||||||
assert css.status_code == 200 and css.headers["cache-control"] == "no-cache"
|
|
||||||
|
|
||||||
|
|
||||||
def test_info():
|
|
||||||
with TestClient(app) as client:
|
|
||||||
assert client.get("/api/info").json()["name"] == "__TITLE__"
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue