Modern Apps git

← Modern-Apps.git

rigidity: protocol-drift, generated-source, exception ratchets

Commit
a80af3c4fe6bb84e20da4d15ffe0975a81f08715
Author
Vayun Mathur <[email protected]>
When
2026-11-25 19:38 UTC (10 days ago)
Parents
e75516e
tools/structure_check.py (wired into ./check as
'structure', runs before module checks): (1) the 13
Wear protocol pairs must be token-identical after
stripping package/imports/comments (library/wearlink
excluded - shared, not copied); (2) GENERATED-header
files (15 today) must be manifest-listed with their
generator; (3) every escape-hatch marker is inventoried
in docs/structure/exceptions.tsv (44 at landing: 17 JNI,
15 screenshot-coverage, 11 scaffold-search, 1 toast) -
growth requires regenerating the inventory with its
reason. Each check proven to catch a synthetic
violation; current tree passes.

Diff

AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex 3d8d979818..51b36bc663 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -39,6 +39,7 @@ Monorepo: ~100 Gradle modules + Rust workspace. Do scoped work only. | widgets/work | `library/widgets/`, `library/work/` | Glance widgets / WorkManager | | biometric/ink | `library/biometric/`, `library/ink/` | biometric / stylus ink | | downloadservice | `library/downloadservice/` | foreground downloads (INTERNET itself) |+| format | `library/format/` | relative-age bucketing + `"<amount>m ago"` wording (opt-in; calendar dates stay in `library/ui` `DateString`) | | locationprovider | `library/locationprovider/` | location abstraction | | aosp-stubs | `library/aosp-stubs/` | compile-only hidden-API stubs | | sdk:games/cast/openassistant | `sdk/games/`, `sdk/cast/`, `sdk/openassistant/` | achievements / casting / assistant tools |@@ -121,10 +122,11 @@ Rules: `release` default (dev is almost never the right install), `dev` only whe ``` Never grep repo-wide when a filter will do. Always excluded: `target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/ *.log *.onnx metadata_data/photos/`. -`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `:<module>:lint` + `cargo check/clippy/fmt/doc --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir; fmt is advisory-only until the tree is fmt-clean):+`./check` — static verification without building: `:<module>:detekt` (rules in `detekt.yml`) + `:<module>:lint` + `cargo check/clippy/fmt/doc --locked` for Rust modules (workspace members via `-p`, standalone crates in-dir; fmt is advisory-only until the tree is fmt-clean) + structure ratchets (`tools/structure_check.py`, manifests in `docs/structure/` — Wear protocol-pair drift, generated-source guard, exception-marker inventory; runs on every invocation): ``` ./check <module> [...]   # e.g. ./check notes backup; ./check voxels ./check all              # every app + library module (pure-JVM modules excluded)+./check structure        # only the structure ratchets ``` Findings fail the task. Only `notes/`, `backup/`, `library/ui/`, `games/voxels/` are detekt-clean today; other modules carry incremental backlog — fixing a module means `./check <module>` goes green, not config relaxation. 
check
diff --git a/check b/checkindex 88e19fe9f2..6a67a4b04f 100755--- a/check+++ b/check@@ -7,6 +7,12 @@ #   ./check games/voxels maps        # multi-module, one gradlew invocation #   ./check voxels                    # shorthand -> games:voxels (same as ./install) #   ./check all                       # every app + library module+#   ./check structure                 # only the structure ratchets (below)+#+# Structure ratchets (docs/structure/README.md): tools/structure_check.py+# checks Wear protocol-pair drift, the generated-source manifest, and the+# exception-marker inventory. They run on every ./check invocation (cheap,+# no build) and their failure fails this script. # # Module notation mirrors ./install: slash == colon, games:/personal: shorthand, # 'all' keyword, deduped. Tasks run with --continue so one broken module does not@@ -57,6 +63,11 @@ all_module_dirs() {  if [[ $# -eq 0 ]]; then print_help; echo ""; echo "Error: no modules specified."; exit 1; fi for arg in "$@"; do case "$arg" in --help|-h|help) print_help; exit 0;; esac; done+for arg in "$@"; do+  if [[ "$arg" == "structure" ]]; then+    exec python3 "$ROOT/tools/structure_check.py" all+  fi+done  MODS=(); ALL_EXP=0 for raw in "$@"; do@@ -100,6 +111,16 @@ echo "Modules (${#MODS[@]}): ${MODS[*]}" echo "Gradle tasks: ${TASKS[*]}" echo "" +STRUCTURE_RC=0+if command -v python3 >/dev/null 2>&1; then+  python3 "$ROOT/tools/structure_check.py" all || STRUCTURE_RC=$?+else+  echo "Error: python3 not found; structure checks (tools/structure_check.py) cannot run." >&2+  STRUCTURE_RC=1+fi+[[ $STRUCTURE_RC -ne 0 ]] && echo "Warning: structure checks reported failures (exit $STRUCTURE_RC)."+echo ""+ DETEKT_RC=0 "$SCRIPT_DIR/gradlew" "${TASKS[@]}" --continue --console=plain || DETEKT_RC=$? echo ""@@ -213,5 +234,5 @@ if [[ ${#ROOT_CRATES[@]} -eq 0 && ${#STANDALONE_DIRS[@]} -eq 0 ]]; then   echo "No Rust crates in scope; cargo steps skipped." fi -if [[ $DETEKT_RC -ne 0 || $CARGO_RC -ne 0 || $CLIPPY_RC -ne 0 || $DOC_RC -ne 0 ]]; then exit 1; fi+if [[ $STRUCTURE_RC -ne 0 || $DETEKT_RC -ne 0 || $CARGO_RC -ne 0 || $CLIPPY_RC -ne 0 || $DOC_RC -ne 0 ]]; then exit 1; fi exit 0
check.bat
diff --git a/check.bat b/check.batindex c39f10f484..c0853877f4 100644--- a/check.bat+++ b/check.bat@@ -37,6 +37,12 @@ Usage:   check.bat games/voxels maps        # multi-module, one gradlew invocation   check.bat voxels                    # shorthand -> games:voxels (same as install.bat)   check.bat all                       # every app + library module+  check.bat structure                 # only the structure ratchets (below)++Structure ratchets (docs/structure/README.md): tools/structure_check.py+checks Wear protocol-pair drift, the generated-source manifest, and the+exception-marker inventory. They run on every check.bat invocation (cheap,+no build) and their failure fails this script.  Module notation mirrors install.bat: slash == colon, games:/personal: shorthand, 'all' keyword, deduped. Tasks run with --continue so one broken module does not@@ -107,6 +113,21 @@ foreach ($CheckA in $args) {   } } +function Invoke-CheckStructure {+  $CheckPy = Get-Command python3 -ErrorAction SilentlyContinue+  if (-not $CheckPy) { $CheckPy = Get-Command python -ErrorAction SilentlyContinue }+  if (-not $CheckPy) {+    [Console]::Error.WriteLine('Error: python3 not found; structure checks (tools/structure_check.py) cannot run.')+    return 1+  }+  & $CheckPy.Source (Join-Path $CheckRoot 'tools/structure_check.py') all+  return $LASTEXITCODE+}++foreach ($CheckA in $args) {+  if ($CheckA -eq 'structure') { exit (Invoke-CheckStructure) }+}+ $CheckMods = @() $CheckAllExp = $false foreach ($CheckRaw in $args) {@@ -151,6 +172,10 @@ Write-Output "Modules ($($CheckMods.Count)): $($CheckMods -join ' ')" Write-Output "Gradle tasks: $($CheckTasks -join ' ')" Write-Output '' +$CheckStructureRc = Invoke-CheckStructure+if ($CheckStructureRc -ne 0) { Write-Output "Warning: structure checks reported failures (exit $CheckStructureRc)." }+Write-Output ''+ # gradlew: prefer the extensionless wrapper via bash when present # (keeps one code path), else gradlew.bat on Windows. $CheckGradlewSh = Join-Path $CheckRoot 'gradlew'@@ -247,5 +272,5 @@ if (($CheckRootCrates.Count -eq 0) -and ($CheckStandaloneDirs.Count -eq 0)) {   Write-Output 'No Rust crates in scope; cargo step skipped.' } -if (($CheckDetektRc -ne 0) -or ($CheckCargoRc -ne 0)) { exit 1 }+if (($CheckStructureRc -ne 0) -or ($CheckDetektRc -ne 0) -or ($CheckCargoRc -ne 0)) { exit 1 } exit 0
docs/structure/README.md
diff --git a/docs/structure/README.md b/docs/structure/README.mdnew file mode 100644index 0000000000..72799a9f7e--- /dev/null+++ b/docs/structure/README.md@@ -0,0 +1,79 @@+# Structure ratchets++Cheap, build-free checks in `tools/structure_check.py` (Python 3 stdlib+only), wired into `./check` / `check.bat`. They run on every `./check`+invocation; `./check structure` runs only them. Each check passes on the+current tree and names every violation individually.++## Entry points++```+python3 tools/structure_check.py all          # all three checks+python3 tools/structure_check.py wear         # protocol-pair drift only+python3 tools/structure_check.py generated    # generated-source guard only+python3 tools/structure_check.py exceptions   # exception-marker ratchet only+python3 tools/structure_check.py exceptions --regen   # regenerate exceptions.tsv+./check structure                             # same as `all`, via ./check+./check <module> [...]                        # structure checks run first+```++Manifests in this directory (tab-separated, `#` comment lines):++| File | Format |+| :--- | :--- |+| `wear-protocol-pairs.tsv` | `pair_id<TAB>phone_path<TAB>wear_path` |+| `generated-sources.tsv` | `path<TAB>generator command` |+| `exceptions.tsv` | `type<TAB>file<TAB>reason<TAB>count` (generated; see below) |++## 1. Protocol-pair drift (`wear`)++Gradle cannot let one app module depend on another, so each Wear OS+companion carries a copy of the phone's `Wear*Protocol.kt` under its own+package. `wear-protocol-pairs.tsv` lists the 13 duplicated pairs+(`library/wearlink/WearLinkProtocol.kt` is a shared library both sides+depend on, not a copy, and is deliberately not listed).++Normalization per file: strip all comments with a string-aware scanner+(Kotlin `//`, nested `/* */`, `"..."`, `"""..."""`, char literals), drop+`package`/`import` lines, then tokenize (`[A-Za-z_]\w*`, numbers, single+punctuation chars). The two token streams must be identical; a violation+names the pair, both token counts, and the first differing token with+context. Comment-only or package/import-only edits do not trip it; any+code or string-literal change on one side does.++## 2. Generated-source guard (`generated`)++A file counts as generated when, within its first 40 lines, a line matches+one of: `BEGIN GENERATED`, `@generated`, `GENERATED` at the start of a+comment line (e.g. `//! GENERATED from ...`, ` * GENERATED — ...`),+`Code generated ... DO NOT EDIT`, `// Generated constants|constant tables`,+or `Do not hand-edit`. Scan scope: `*.kt`/`*.rs`, excluding the root+AGENTS.md "Never scan" dirs (`build/`, `target/`, `third_party/`,+`analysis/`, `personal/`, ...) plus `lint-rules/`, `tools/`, `docs/`+(which quote header strings as data).++Every such file must be listed in `generated-sources.tsv` with the+command that regenerates it (a recorded generator with no script in the+repo is stated as such in the manifest), and every listed file must+still exist and still carry its header. Presence only: the check never+regenerates anything.++## 3. Exception-marker ratchet (`exceptions`)++`exceptions.tsv` inventories every escape-hatch marker occurrence in+Kotlin sources (`*.kt`/`*.kts`, same exclusions as above): the canonical+types from root AGENTS.md §2 — `PACKAGE_JNI` (the verbatim+`// PACKAGE STRUCTURE EXCEPTION (JNI)` marker; reason column records+that it carries no free-text reason), `RAW_SCAFFOLD`, `TOAST`,+`RAW_ANIMATION`, `SCAFFOLD_LOADING`, `SCAFFOLD_SEARCH`,+`SCREENSHOT_COVERAGE`. The reason column is the verbatim text after the+marker colon in the source.++`./check` fails when the TSV does not match the tree exactly (type,+file, reason, count). Line numbers are deliberately not recorded, so+moving a marker inside its file does not churn the inventory. To add or move a marker intentionally: edit the+source, run `python3 tools/structure_check.py exceptions --regen`,+review the `exceptions.tsv` diff (that review is the reason edit), and+include both in the change. Malformed markers (missing colon/reason)+are still caught by lint (`ExceptionMarkerFormatDetector`); this+ratchet catches growth and drift.
docs/structure/exceptions.tsv
diff --git a/docs/structure/exceptions.tsv b/docs/structure/exceptions.tsvnew file mode 100644index 0000000000..58762fc3a5--- /dev/null+++ b/docs/structure/exceptions.tsv@@ -0,0 +1,47 @@+# type	file	reason	count+# Generated by: python3 tools/structure_check.py exceptions --regen+# A new/changed marker requires regenerating this file and reviewing the diff; the reason column is copied verbatim from the source marker.+PACKAGE_JNI	code/src/main/java/com/vayunmathur/code/util/TreeSitterNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	library/e2ee-openpgp/src/main/java/com/vayunmathur/e2ee/PgpNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	networklocation/src/main/java/com/vayunmathur/networklocation/GeocoderNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	networklocation/src/main/java/com/vayunmathur/networklocation/NetworkLocationNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	networklocation/src/main/java/com/vayunmathur/networklocation/WpsStoreNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	office/src/main/java/com/vayunmathur/office/util/OfficeNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	passwords/src/main/java/com/vayunmathur/passwords/util/KdbxNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	share/src/main/java/com/vayunmathur/share/protocol/ShareNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	share/src/main/java/com/vayunmathur/share/protocol/ShareNativeDiscovery.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	vpn/src/main/java/com/vayunmathur/vpn/util/VpnNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	web/src/main/java/com/vayunmathur/web/shields/ShieldsNative.kt	JNI (verbatim marker; no free-text reason)	1+PACKAGE_JNI	youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/YouPipeNative.kt	JNI (verbatim marker; no free-text reason)	1+SCAFFOLD_SEARCH	astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.kt	full-bleed sky-map screen with TopAppBarOverlay chrome; no scaffold host for the catalog search field	1+SCAFFOLD_SEARCH	calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.kt	language-picker dialog-local search filter in this file; the screen's country search uses the scaffold search parameter	1+SCAFFOLD_SEARCH	calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/TimezonePickerDialog.kt	dialog-local timezone filter inside a picker dialog; no scaffold host	1+SCAFFOLD_SEARCH	communicate/src/main/java/com/vayunmathur/communicate/ui/NewMessagePicker.kt	dialog-local contact filter inside the NewMessage dialog route, no scaffold host	1+SCAFFOLD_SEARCH	health/src/main/java/com/vayunmathur/health/ui/IngredientSearchDialog.kt	dialog-local ingredient search inside an AlertDialog; no scaffold host	1+SCAFFOLD_SEARCH	launcher/src/main/java/com/vayunmathur/launcher/ui/DrawerContent.kt	app-drawer overlay over the home screen (not a scaffold screen); apps must stay draggable into the home gesture root	1+SCAFFOLD_SEARCH	launcher/src/main/java/com/vayunmathur/launcher/ui/WidgetPickerContent.kt	bottom-sheet-local widget picker content hosted by a ModalBottomSheet, not a scaffold screen	1+SCAFFOLD_SEARCH	library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt	<reason>` marker.	1+SCAFFOLD_SEARCH	library/ui/src/main/java/com/vayunmathur/library/ui/CommonSearchBar.kt	<reason>` marker (sheet/drawer-local pickers).	1+SCAFFOLD_SEARCH	photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt	expandable SearchBar supplied as the AppScaffold topBar; its expanded overlay is the search-results photo grid	1+SCAFFOLD_SEARCH	youpipe/src/main/java/com/vayunmathur/youpipe/ui/SearchScreen.kt	expandable Material3 SearchBar whose expanded overlay is the search-results/suggestions surface (see the raw-scaffold exception below)	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	Accounts: reads Keystore-sealed DataStore line sessions; no stateless slice for Layoutlib	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	Call: live WebRTC/telecom call surface (mic/camera); the car in-call template is the renderable in-call capture	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	GoogleVoiceSignIn: WebView sign-in page; Layoutlib cannot render the live voice.google.com WebView	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	RcsGroupMembers: group member list loads from RCS session state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	RcsStatus: RCS provisioning screen reads live SIP/provisioning state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	RcsVerify: safety-number screen loads peer keys from RCS session state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	SignalRegistration.Captcha: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	SignalRegistration.Code: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	SignalRegistration.Done: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	SignalRegistration.Number: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	WhatsAppBackupImport: backup import reads the SAF picker and encrypted backup state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	WhatsAppRegistration.Code: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	WhatsAppRegistration.Done: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	WhatsAppRegistration.Number: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+SCREENSHOT_COVERAGE	communicate/src/main/java/com/vayunmathur/communicate/Route.kt	WhatsAppRegistration.Pin: registration wizard reads Keystore-sealed session and provider state; no stateless slice	1+TOAST	share/src/main/java/com/vayunmathur/share/platform/receive/ShareSaveActivity.kt	no UI to host a snackbar.	1
docs/structure/generated-sources.tsv
diff --git a/docs/structure/generated-sources.tsv b/docs/structure/generated-sources.tsvnew file mode 100644index 0000000000..ba977ca661--- /dev/null+++ b/docs/structure/generated-sources.tsv@@ -0,0 +1,20 @@+# path	generator+# Every Kotlin/Rust file with a GENERATED/@generated header (see+# docs/structure/README.md for the header definition) must be listed here+# with the command that regenerates it. tools/structure_check.py verifies+# presence only (listed + header still present); it never regenerates.+news/src/main/java/com/vayunmathur/news/domain/GeneratedSources.kt	python3 analysis/news-scale/curate_r2.py --apply (aggregator; round 1 alone: curate.py --apply)+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesA.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesB.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesC.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesD.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesE.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesF.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesG.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesH.kt	python3 analysis/news-scale/curate_r2.py --apply+news/src/main/java/com/vayunmathur/news/domain/GeneratedSourcesI.kt	python3 analysis/news-scale/curate_r2.py --apply+communicate/src/main/rust/src/wa_tokens.rs	Regenerate the token tables from communicate WhatsAppProtocol.kt (header: GENERATED from WhatsAppProtocol.kt; no generator script in repo)+library/ml/src/main/rust/src/logmel_extra.rs	python3 scripts/ml/nnfp_reference.py (generated reference constants; see note inside file)+library/ml/src/main/rust/src/microfrontend_part1.rs	python3 scripts/ml/nnfp_reference.py (generated reference constants; see note inside file)+library/ml/src/main/rust/src/nets/gemma4_part5.rs	Generated constant tables read off the Gemma 4 source bundle (see header in file; no generator script in repo)+office/src/screenshotTest/kotlin/com/vayunmathur/office/ui/SampleDocx.kt	Run the app OoxmlImporter over metadata_data/assets/sample1.docx and emit the first 14 blocks (see header in file; no generator script in repo)
docs/structure/wear-protocol-pairs.tsv
diff --git a/docs/structure/wear-protocol-pairs.tsv b/docs/structure/wear-protocol-pairs.tsvnew file mode 100644index 0000000000..a33479eba4--- /dev/null+++ b/docs/structure/wear-protocol-pairs.tsv@@ -0,0 +1,20 @@+# pair_id	phone_path	wear_path+# Duplicated Wear protocol files (phone <-> wear). Gradle cannot let one app+# module depend on another, so each wear module carries a copy of the phone+# file under its own package. tools/structure_check.py strips package/import+# lines and all comments, then requires token-stream identity per pair.+# library/wearlink/WearLinkProtocol.kt is deliberately NOT listed: it is a+# shared library module both sides depend on, not a duplicated copy.+appstore	appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt	appstore/wear/src/main/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocol.kt+calendar	calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt	calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt+camera	camera/src/main/java/com/vayunmathur/camera/domain/WearCameraProtocol.kt	camera-wear/src/main/java/com/vayunmathur/camera/wear/domain/WearCameraProtocol.kt+clock	clock/src/main/java/com/vayunmathur/clock/domain/WearClockProtocol.kt	clock-wear/src/main/java/com/vayunmathur/clock/wear/domain/WearClockProtocol.kt+communicate	communicate/src/main/java/com/vayunmathur/communicate/domain/WearCommunicateProtocol.kt	communicate-wear/src/main/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocol.kt+contacts	contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.kt	contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.kt+findfamily	findfamily/src/main/java/com/vayunmathur/findfamily/domain/WearFindFamilyProtocol.kt	findfamily-wear/src/main/java/com/vayunmathur/findfamily/wear/domain/WearFindFamilyProtocol.kt+launcher	launcher/src/main/java/com/vayunmathur/launcher/domain/WearLauncherProtocol.kt	launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocol.kt+maps	maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt	maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt+music	music/src/main/java/com/vayunmathur/music/domain/WearMusicProtocol.kt	music-wear/src/main/java/com/vayunmathur/music/wear/domain/WearMusicProtocol.kt+notes	notes/src/main/java/com/vayunmathur/notes/domain/WearNotesProtocol.kt	notes-wear/src/main/java/com/vayunmathur/notes/wear/domain/WearNotesProtocol.kt+todo	todo/src/main/java/com/vayunmathur/todo/domain/WearTodoProtocol.kt	todo-wear/src/main/java/com/vayunmathur/todo/wear/domain/WearTodoProtocol.kt+weather	weather/src/main/java/com/vayunmathur/weather/domain/WearWeatherProtocol.kt	weather-wear/src/main/java/com/vayunmathur/weather/wear/domain/WearWeatherProtocol.kt
tools/structure_check.py
diff --git a/tools/structure_check.py b/tools/structure_check.pynew file mode 100755index 0000000000..7c8b946901--- /dev/null+++ b/tools/structure_check.py@@ -0,0 +1,317 @@+#!/usr/bin/env python3+"""Cheap structure ratchets for Modern-Apps (no build, stdlib only).++Three checks, wired into ./check (see docs/structure/README.md):++  wear       Token-stream identity of the duplicated Wear protocol pairs+             listed in docs/structure/wear-protocol-pairs.tsv. Each file is+             normalized (package/import lines dropped, comments stripped+             with a string-aware scanner) and the resulting token streams+             must be identical per pair.+  generated  Every Kotlin/Rust file carrying a GENERATED/@generated header+             (definition in docs/structure/README.md) must be listed in+             docs/structure/generated-sources.tsv with a generator command,+             and every listed file must still exist and carry the header.+             Presence only: nothing is regenerated.+  exceptions Every escape-hatch marker occurrence in Kotlin sources must+             match docs/structure/exceptions.tsv exactly (type, file,+             reason). Regenerate with --regen after an intentional change+             and review the TSV diff; a new marker without a reason edit+             fails here (and malformed markers fail lint anyway).++Usage:+  python3 tools/structure_check.py [wear|generated|exceptions|all]+  python3 tools/structure_check.py exceptions --regen++Exit code 0 = clean, 1 = violations (each violation is named).+Scope exclusions follow root AGENTS.md "Never scan": build/, target/,+third_party/, analysis/, personal/, .git/ etc. are never walked, and+lint-rules/ + tools/ + docs/ are excluded from the marker/generated scans+because they legitimately quote marker/header strings as data.+"""+import os+import re+import sys++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+DOCS = os.path.join(ROOT, "docs", "structure")+WEAR_TSV = os.path.join(DOCS, "wear-protocol-pairs.tsv")+GENERATED_TSV = os.path.join(DOCS, "generated-sources.tsv")+EXCEPTIONS_TSV = os.path.join(DOCS, "exceptions.tsv")++SKIP_DIRS = {+    ".git", ".gradle", ".kotlin", "build", "target", "analysis",+    "third_party", "personal", "release", "captures", ".idea", "__pycache__",+}+# Dirs whose files quote markers/headers as data, not as uses.+DATA_DIRS = ("lint-rules/", "tools/", "docs/")+++def rel(path):+    return os.path.relpath(path, ROOT).replace(os.sep, "/")+++def walk_files(exts):+    for dirpath, dirnames, filenames in os.walk(ROOT):+        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]+        for name in sorted(filenames):+            if name.endswith(exts):+                yield os.path.join(dirpath, name)+++def is_data_path(rpath):+    return rpath.startswith(DATA_DIRS)+++# ---------------------------------------------------------------- wear ----+def strip_comments(text):+    """Remove // and /* */ comments, respecting Kotlin strings/chars."""+    out = []+    i, n = 0, len(text)+    while i < n:+        if text.startswith('"""', i):+            j = text.find('"""', i + 3)+            j = n if j < 0 else j + 3+            out.append(text[i:j]); i = j+        elif text[i] == '"':+            j = i + 1+            while j < n and text[j] != '"':+                j += 2 if text[j] == "\\" else 1+            out.append(text[i:j + 1]); i = j + 1+        elif text[i] == "'":+            j = i + 1+            while j < n and text[j] != "'":+                j += 2 if text[j] == "\\" else 1+            out.append(text[i:j + 1]); i = j + 1+        elif text.startswith("//", i):+            j = text.find("\n", i)+            i = n if j < 0 else j+        elif text.startswith("/*", i):+            depth, j = 1, i + 2+            while j < n and depth:+                if text.startswith("/*", j):+                    depth += 1; j += 2+                elif text.startswith("*/", j):+                    depth -= 1; j += 2+                else:+                    j += 1+            out.append(" "); i = j+        else:+            out.append(text[i]); i += 1+    return "".join(out)+++TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|[^\w\s]")+++def normalized_tokens(path):+    text = open(path, encoding="utf-8", errors="ignore").read()+    text = strip_comments(text)+    lines = [+        ln for ln in text.splitlines()+        if not re.match(r"\s*(package|import)\s", ln)+    ]+    return TOKEN_RE.findall("\n".join(lines))+++def check_wear():+    violations = []+    pairs = []+    for ln, line in enumerate(open(WEAR_TSV, encoding="utf-8"), 1):+        if not line.strip() or line.startswith("#"):+            continue+        parts = line.rstrip("\n").split("\t")+        if len(parts) != 3:+            violations.append(f"wear: {WEAR_TSV}:{ln}: expected 3 tab-separated fields")+            continue+        pairs.append(parts)+    for pair_id, phone, wear in pairs:+        pp, wp = os.path.join(ROOT, phone), os.path.join(ROOT, wear)+        if not os.path.isfile(pp):+            violations.append(f"wear[{pair_id}]: missing phone file {phone}")+            continue+        if not os.path.isfile(wp):+            violations.append(f"wear[{pair_id}]: missing wear file {wear}")+            continue+        a, b = normalized_tokens(pp), normalized_tokens(wp)+        if a != b:+            idx = next((k for k in range(min(len(a), len(b))) if a[k] != b[k]),+                       min(len(a), len(b)))+            lo = max(0, idx - 6)+            violations.append(+                f"wear[{pair_id}]: DRIFT {phone} <-> {wear} "+                f"(tokens phone={len(a)} wear={len(b)}, first diff at token {idx}: "+                f"phone ...{' '.join(a[lo:idx + 6])} | wear ...{' '.join(b[lo:idx + 6])})")+    print(f"wear: {len(pairs)} pairs checked")+    return violations+++# ------------------------------------------------------------- generated ----+GENERATED_RE = re.compile(+    r"BEGIN GENERATED|@generated\b"+    r"|^\s*(?://[!/]?|/\*+|\*)?\s*GENERATED\b"+    r"|Code generated[^\n]*DO NOT EDIT|// Generated (constants|constant tables)"+    r"|Do not hand-edit")+HEADER_LINES = 40+++def has_generated_header(path):+    try:+        with open(path, encoding="utf-8", errors="ignore") as fh:+            for i, line in enumerate(fh):+                if i >= HEADER_LINES:+                    break+                if GENERATED_RE.search(line):+                    return line.strip()+    except OSError:+        return None+    return None+++def check_generated():+    violations = []+    listed = {}+    for ln, line in enumerate(open(GENERATED_TSV, encoding="utf-8"), 1):+        if not line.strip() or line.startswith("#"):+            continue+        parts = line.rstrip("\n").split("\t")+        if len(parts) != 2 or not parts[1].strip():+            violations.append(+                f"generated: {GENERATED_TSV}:{ln}: expected '<path>\\t<generator command>'")+            continue+        listed[parts[0]] = parts[1]+    found = {}+    for path in walk_files((".kt", ".rs")):+        rpath = rel(path)+        if is_data_path(rpath):+            continue+        marker = has_generated_header(path)+        if marker:+            found[rpath] = marker+    for rpath in sorted(found):+        if rpath not in listed:+            violations.append(+                f"generated: UNLISTED {rpath} (header: {found[rpath][:100]}) "+                f"-- add it to docs/structure/generated-sources.tsv with its generator")+    for rpath in sorted(listed):+        path = os.path.join(ROOT, rpath)+        if not os.path.isfile(path):+            violations.append(f"generated: STALE {rpath} listed but file is gone")+        elif not has_generated_header(path):+            violations.append(+                f"generated: STALE {rpath} listed but its GENERATED header is gone")+    print(f"generated: {len(found)} generated files in tree, {len(listed)} listed")+    return violations+++# ------------------------------------------------------------ exceptions ----+# Canonical markers (verbatim list in root AGENTS.md and+# lint-rules ExceptionMarkerFormatDetector). type -> (keyword, reason prefix)+MARKERS = [+    ("PACKAGE_JNI", "PACKAGE STRUCTURE EXCEPTION (JNI)", None),+    ("RAW_SCAFFOLD", "RAW SCAFFOLD EXCEPTION", "// RAW SCAFFOLD EXCEPTION:"),+    ("TOAST", "TOAST EXCEPTION", "// TOAST EXCEPTION:"),+    ("RAW_ANIMATION", "RAW ANIMATION EXCEPTION", "// RAW ANIMATION EXCEPTION:"),+    ("SCAFFOLD_LOADING", "SCAFFOLD LOADING EXCEPTION", "// SCAFFOLD LOADING EXCEPTION:"),+    ("SCAFFOLD_SEARCH", "SCAFFOLD SEARCH EXCEPTION", "// SCAFFOLD SEARCH EXCEPTION:"),+    ("SCREENSHOT_COVERAGE", "SCREENSHOT COVERAGE EXCEPTION",+     "// SCREENSHOT COVERAGE EXCEPTION:"),+]+++def scan_exceptions():+    # Aggregated by (type, file, reason) with an occurrence count: line+    # numbers are deliberately not recorded, so moving a marker inside its+    # file does not churn the inventory -- only adding, removing, or+    # rewording a marker does (the growth this ratchet exists to catch).+    from collections import Counter+    counts = Counter()+    total = 0+    for path in walk_files((".kt", ".kts")):+        rpath = rel(path)+        if is_data_path(rpath):+            continue+        with open(path, encoding="utf-8", errors="ignore") as fh:+            for line in fh:+                for mtype, keyword, prefix in MARKERS:+                    if keyword in line:+                        if prefix is None:+                            reason = "JNI (verbatim marker; no free-text reason)"+                        else:+                            idx = line.find(prefix)+                            reason = (line[idx + len(prefix):].strip()+                                      if idx >= 0 else "(malformed: no colon prefix)")+                        counts[(mtype, rpath, reason)] += 1+                        total += 1+                        break+    rows = [(t, f, r, str(c)) for (t, f, r), c in sorted(counts.items())]+    return rows, total+++def exceptions_tsv_text(rows):+    out = ["# type\tfile\treason\tcount",+           "# Generated by: python3 tools/structure_check.py exceptions --regen",+           "# A new/changed marker requires regenerating this file and reviewing "+           "the diff; the reason column is copied verbatim from the source marker."]+    out += ["\t".join(r) for r in rows]+    return "\n".join(out) + "\n"+++def check_exceptions(regen=False):+    rows, total = scan_exceptions()+    if regen:+        with open(EXCEPTIONS_TSV, "w", encoding="utf-8", newline="\n") as fh:+            fh.write(exceptions_tsv_text(rows))+        print(f"exceptions: regenerated {EXCEPTIONS_TSV} with {total} markers")+        return []+    expected = exceptions_tsv_text(rows)+    actual = ""+    if os.path.isfile(EXCEPTIONS_TSV):+        actual = open(EXCEPTIONS_TSV, encoding="utf-8").read()+    if actual != expected:+        exp = [l for l in expected.splitlines() if l and not l.startswith("#")]+        act = [l for l in actual.splitlines() if l and not l.startswith("#")]+        violations = []+        for l in sorted(set(exp) - set(act)):+            violations.append(f"exceptions: UNRECORDED {l}")+        for l in sorted(set(act) - set(exp)):+            violations.append(f"exceptions: STALE {l}")+        violations.append(+            "exceptions: run `python3 tools/structure_check.py exceptions --regen` "+            "and review/commit the docs/structure/exceptions.tsv diff")+        recorded = sum(int(l.split("\t")[3]) for l in act if len(l.split("\t")) == 4)+        print(f"exceptions: {total} markers in tree, {recorded} recorded")+        return violations+    from collections import Counter+    counts = Counter()+    for r in rows:+        counts[r[0]] += int(r[3])+    print(f"exceptions: {total} markers recorded "+          f"({', '.join(f'{k}={v}' for k, v in sorted(counts.items()))})")+    return []+++def main(argv):+    which = argv[1] if len(argv) > 1 else "all"+    regen = "--regen" in argv+    violations = []+    if which in ("wear", "all"):+        violations += check_wear()+    if which in ("generated", "all"):+        violations += check_generated()+    if which in ("exceptions", "all"):+        violations += check_exceptions(regen=regen)+    if which not in ("wear", "generated", "exceptions", "all"):+        print(__doc__)+        return 2+    if violations:+        print("\nSTRUCTURE CHECK FAILURES:")+        for v in violations:+            print(f"  - {v}")+        return 1+    print("structure: OK")+    return 0+++if __name__ == "__main__":+    sys.exit(main(sys.argv))