Modern Apps git

← Modern-Apps.git

update root scripts

Commit
e2ba1765fc252315e51a59a1db96dcc7cd043142
Author
vayun-mathur <[email protected]>
When
2026-09-19 17:54 UTC (2 months ago)
Parents
86984a7

Diff

CONTRIBUTING.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 30a38388f6..1f98ee8339 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -477,7 +477,7 @@ lint check would be the wrong way round.  ## Store metadata -Every app module needs a `metadata_data/<module-key>.md`. `release.sh` and the release workflow+Every app module needs a `metadata_data/<module-key>.md`. `./release` (`release.bat` on Windows) and the release workflow take line 1 as the store short description and the whole file as the full description, so the format is strict and `./gradlew checkMetadata` enforces it both ways โ€” a missing file and an orphaned file are both errors.@@ -626,7 +626,7 @@ the file's line endings โ€” fix that rather than committing the churn.  Releases are manual: the `๐Ÿš€ Publish Next Release` workflow is `workflow_dispatch` only. `version.txt` holds the version code on line 1 and the version name on line 2, and both are-injected into every app module at release time. `release.sh` does the same locally and refuses+injected into every app module at release time. `./release` (`release.bat` on Windows) does the same locally and refuses to run on a dirty tree.  Reproducible output is a standing requirement โ€” archives use fixed timestamps and ordering,
analyze.bat
diff --git a/analyze.bat b/analyze.batnew file mode 100644index 0000000000..373768b2a4--- /dev/null+++ b/analyze.bat@@ -0,0 +1,222 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# analyze.bat - Codebase metrics for Modern-Apps. (PowerShell twin of ./analyze.)+#+# Usage (cmd):+#   analyze.bat package [-m MODULE] [--nolib]    # .kt lines grouped by package (directory)+#   analyze.bat module [-m MODULE] [--nolib]     # .kt lines grouped by module+#   analyze.bat structure [-m MODULE] [--nolib]  # root packages x modules using them+#   analyze.bat ram                               # live device RAM via adb dumpsys meminfo+#+#   -m MODULE filters to one module directory name. --nolib skips top-level library/.+$ErrorActionPreference = 'Stop'++$AnalyzeRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }++function Show-AnalyzeHelp {+  @'+Usage:+  analyze.bat package [-m MODULE] [--nolib]    # .kt lines grouped by package (directory)+  analyze.bat module [-m MODULE] [--nolib]     # .kt lines grouped by module+  analyze.bat structure [-m MODULE] [--nolib]  # root packages x modules using them+  analyze.bat ram                               # live device RAM via adb dumpsys meminfo++  -m MODULE filters to one module directory name. --nolib skips top-level library/.+'@+}++function Get-AnalyzeAdb {+  $AdbCmd = Get-Command adb -ErrorAction SilentlyContinue+  if ($AdbCmd) { return $AdbCmd.Source }+  $AnalyzeSdkBases = @()+  if ($env:ANDROID_HOME) { $AnalyzeSdkBases += $env:ANDROID_HOME }+  if ($env:ANDROID_SDK_ROOT) { $AnalyzeSdkBases += $env:ANDROID_SDK_ROOT }+  $AnalyzeSdkBases += (Join-Path $HOME 'Android/Sdk')+  $AnalyzeSdkBases += (Join-Path $HOME 'Library/Android/sdk')+  if ($env:LOCALAPPDATA) { $AnalyzeSdkBases += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }+  foreach ($AnalyzeBase in $AnalyzeSdkBases) {+    if (-not $AnalyzeBase) { continue }+    foreach ($AnalyzeName in @('platform-tools/adb', 'platform-tools/adb.exe')) {+      $AnalyzeCand = Join-Path $AnalyzeBase $AnalyzeName+      if (Test-Path -LiteralPath $AnalyzeCand -PathType Leaf) { return $AnalyzeCand }+    }+  }+  return ''+}++function Get-KtLineCount([string]$Path) {+  $AnalyzeCount = 0+  foreach ($AnalyzeLine in [System.IO.File]::ReadLines($Path)) { $AnalyzeCount++ }+  return $AnalyzeCount+}++function Format-AnalyzeBytes([long]$Bytes) {+  if ($Bytes -ge 1073741824) { return ('{0:F2} GB' -f ($Bytes / 1073741824)) }+  return ('{0:F2} MB' -f ($Bytes / 1048576))+}++$AnalyzeType = ''+$AnalyzeModule = ''+$AnalyzeNoLib = $false+$AnalyzeIdx = 0+while ($AnalyzeIdx -lt $args.Count) {+  $AnalyzeArg = [string]$args[$AnalyzeIdx]+  if ($AnalyzeArg -eq '-h' -or $AnalyzeArg -eq '--help' -or $AnalyzeArg -eq 'help') {+    Show-AnalyzeHelp+    exit 0+  }+  elseif ($AnalyzeArg -in @('package', 'module', 'ram', 'structure')) {+    $AnalyzeType = $AnalyzeArg+    $AnalyzeIdx+++  }+  elseif ($AnalyzeArg -eq '-m' -or $AnalyzeArg -eq '--module') {+    if ($AnalyzeIdx + 1 -ge $args.Count) {+      [Console]::Error.WriteLine('Error: --module needs a value.')+      exit 1+    }+    $AnalyzeModule = [string]$args[$AnalyzeIdx + 1]+    $AnalyzeIdx += 2+  }+  elseif ($AnalyzeArg -eq '--nolib' -or $AnalyzeArg -eq '-nolib') {+    $AnalyzeNoLib = $true+    $AnalyzeIdx+++  }+  else {+    [Console]::Error.WriteLine("Error: unknown arg '$AnalyzeArg'.")+    exit 1+  }+}+if (-not $AnalyzeType) {+  [Console]::Error.WriteLine('Error: give a type: package, module, ram, structure.')+  exit 1+}++if ($AnalyzeType -eq 'ram') {+  $AnalyzeAdb = Get-AnalyzeAdb+  if (-not $AnalyzeAdb) {+    [Console]::Error.WriteLine('Error: adb not found.')+    exit 1+  }+  $AnalyzeDevices = & $AnalyzeAdb devices 2>$null+  if (-not ($AnalyzeDevices | Where-Object { $_ -match "`tdevice$" })) {+    [Console]::Error.WriteLine('Error: no authorized device (adb devices).')+    exit 1+  }+  Write-Output 'Fetching RAM metrics via adb...'+  $AnalyzeMeminfo = & $AnalyzeAdb shell dumpsys meminfo 2>$null+  $AnalyzeMax = @{}+  $AnalyzeNames = @{}+  foreach ($AnalyzeRow in $AnalyzeMeminfo) {+    if ($AnalyzeRow -match '^\s*([\d,]+)\s+(?:K|kB|KB|K:):?\s*([A-Za-z0-9_.\-:+]+)\s+\(pid\s+(\d+)') {+      $AnalyzeBytes = [long]($Matches[1] -replace ',', '') * 1024+      $AnalyzePid = $Matches[3]+      if ((-not $AnalyzeMax.ContainsKey($AnalyzePid)) -or ($AnalyzeBytes -gt $AnalyzeMax[$AnalyzePid])) {+        $AnalyzeMax[$AnalyzePid] = $AnalyzeBytes+        $AnalyzeNames[$AnalyzePid] = $Matches[2]+      }+    }+  }+  $AnalyzeTotal = 0+  $AnalyzeRamRows = foreach ($AnalyzePid in $AnalyzeMax.Keys) {+    $AnalyzeTotal += $AnalyzeMax[$AnalyzePid]+    [pscustomobject]@{ Pid = $AnalyzePid; Name = $AnalyzeNames[$AnalyzePid]; Bytes = $AnalyzeMax[$AnalyzePid] }+  }+  $AnalyzeRamRows += [pscustomobject]@{ Pid = 'TOTAL'; Name = 'TOTAL RUNNING PROCESS RAM'; Bytes = $AnalyzeTotal }+  foreach ($AnalyzeRow in ($AnalyzeRamRows | Sort-Object -Property Bytes -Descending)) {+    '{0,-8} {1,-60} {2}' -f $AnalyzeRow.Pid, $AnalyzeRow.Name, (Format-AnalyzeBytes $AnalyzeRow.Bytes)+  }+  exit 0+}++# file list: all .kt under a src/ dir, optionally one module, optionally no library/+$AnalyzeFiles = Get-ChildItem -LiteralPath $AnalyzeRoot -Recurse -Filter '*.kt' -File -Force -ErrorAction SilentlyContinue |+  Where-Object {+    $AnalyzeFull = $_.FullName.Replace('\', '/')+    if ($AnalyzeFull -notlike '*/src/*') { return $false }+    if ($AnalyzeFull -like '*/build/*' -or $AnalyzeFull -like '*/target/*' -or $AnalyzeFull -like '*/.git/*') { return $false }+    if ($AnalyzeNoLib -and ($AnalyzeFull -like '*/library/*')) { return $false }+    if ($AnalyzeModule -and ($AnalyzeFull -notlike "*/$AnalyzeModule/src/*")) { return $false }+    return $true+  }+if (-not $AnalyzeFiles) {+  $AnalyzeSuffix = if ($AnalyzeModule) { " in module: $AnalyzeModule" } else { '' }+  [Console]::Error.WriteLine("No Kotlin files found$AnalyzeSuffix.")+  exit 1+}++switch ($AnalyzeType) {+  'package' {+    # group by containing directory name+    '{0,-50} {1}' -f 'PACKAGE(dir)', 'LINES'+    $AnalyzeByDir = @{}+    foreach ($AnalyzeFile in $AnalyzeFiles) {+      $AnalyzeDir = $AnalyzeFile.DirectoryName+      if (-not $AnalyzeByDir.ContainsKey($AnalyzeDir)) { $AnalyzeByDir[$AnalyzeDir] = 0 }+      $AnalyzeByDir[$AnalyzeDir] += Get-KtLineCount $AnalyzeFile.FullName+    }+    foreach ($AnalyzeEntry in ($AnalyzeByDir.GetEnumerator() | Sort-Object -Property Value -Descending)) {+      '{0,-50} {1}' -f (Split-Path -Leaf $AnalyzeEntry.Key), $AnalyzeEntry.Value+    }+  }+  'module' {+    # group by module = directory holding src/+    '{0,-30} {1}' -f 'MODULE', 'LINES'+    $AnalyzeMl = @{}+    $AnalyzeTotal = 0+    foreach ($AnalyzeFile in $AnalyzeFiles) {+      $AnalyzeRel = $AnalyzeFile.FullName.Replace('\', '/')+      $AnalyzeRootSlash = $AnalyzeRoot.Replace('\', '/').TrimEnd('/')+      if ($AnalyzeRel.StartsWith("$AnalyzeRootSlash/")) { $AnalyzeRel = $AnalyzeRel.Substring($AnalyzeRootSlash.Length + 1) }+      $AnalyzeSrcIdx = $AnalyzeRel.IndexOf('/src/')+      $AnalyzeMod = if ($AnalyzeSrcIdx -ge 0) { $AnalyzeRel.Substring(0, $AnalyzeSrcIdx) } else { $AnalyzeRel }+      $AnalyzeN = Get-KtLineCount $AnalyzeFile.FullName+      if (-not $AnalyzeMl.ContainsKey($AnalyzeMod)) { $AnalyzeMl[$AnalyzeMod] = 0 }+      $AnalyzeMl[$AnalyzeMod] += $AnalyzeN+    }+    foreach ($AnalyzeEntry in ($AnalyzeMl.GetEnumerator() | Sort-Object -Property Value -Descending)) {+      '{0,-30} {1}' -f $AnalyzeEntry.Key, $AnalyzeEntry.Value+      $AnalyzeTotal += $AnalyzeEntry.Value+    }+    Write-Output ''+    '{0,-30} {1}' -f 'TOTAL', $AnalyzeTotal+  }+  'structure' {+    # root package = path segment right after the module-name segment under src/+    '{0,-20} {1,-8} {2}' -f 'PACKAGE', 'MODULES', 'MODULENAMES'+    $AnalyzePkgMods = @{}+    foreach ($AnalyzeFile in $AnalyzeFiles) {+      $AnalyzeRel = $AnalyzeFile.FullName.Replace('\', '/')+      $AnalyzeRootSlash = $AnalyzeRoot.Replace('\', '/').TrimEnd('/')+      if ($AnalyzeRel.StartsWith("$AnalyzeRootSlash/")) { $AnalyzeRel = $AnalyzeRel.Substring($AnalyzeRootSlash.Length + 1) }+      $AnalyzeSrcIdx = $AnalyzeRel.IndexOf('/src/')+      if ($AnalyzeSrcIdx -lt 0) { continue }+      $AnalyzePre = $AnalyzeRel.Substring(0, $AnalyzeSrcIdx)+      $AnalyzeModName = Split-Path -Leaf $AnalyzePre+      $AnalyzePost = $AnalyzeRel.Substring($AnalyzeSrcIdx + 5)+      $AnalyzeSegs = $AnalyzePost.Split('/')+      $AnalyzeFound = -1+      for ($AnalyzeI = 0; $AnalyzeI -lt $AnalyzeSegs.Count; $AnalyzeI++) {+        if ($AnalyzeSegs[$AnalyzeI] -ceq $AnalyzeModName) { $AnalyzeFound = $AnalyzeI; break }+      }+      if (($AnalyzeFound -ge 0) -and (($AnalyzeFound + 1) -lt $AnalyzeSegs.Count)) {+        $AnalyzePkg = $AnalyzeSegs[$AnalyzeFound + 1]+      }+      else {+        $AnalyzePkg = Split-Path -Leaf $AnalyzeFile.FullName+      }+      if (-not $AnalyzePkgMods.ContainsKey($AnalyzePkg)) { $AnalyzePkgMods[$AnalyzePkg] = @() }+      if ($AnalyzePkgMods[$AnalyzePkg] -notcontains $AnalyzeModName) { $AnalyzePkgMods[$AnalyzePkg] += $AnalyzeModName }+    }+    foreach ($AnalyzeEntry in ($AnalyzePkgMods.GetEnumerator() | Sort-Object -Property @{ Expression = { $_.Value.Count }; Descending = $true }, @{ Expression = { $_.Key } })) {+      $AnalyzeMods = $AnalyzeEntry.Value+      '{0,-20} {1,-8} {2}' -f $AnalyzeEntry.Key, $AnalyzeMods.Count, ($AnalyzeMods -join ',')+    }+  }+}+exit 0
check.bat
diff --git a/check.bat b/check.batnew file mode 100644index 0000000000..4434471e11--- /dev/null+++ b/check.bat@@ -0,0 +1,242 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# check.bat - Static verification without building or installing.+# (PowerShell twin of ./check.)+#   check.bat <module> [module...]     # detekt + cargo check+#   check.bat 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+#+# Module notation mirrors install.bat: slash == colon, games:/personal: shorthand,+# 'all' keyword, deduped. Tasks run with --continue so one broken module does not+# block the rest; exit code is nonzero if anything failed.+#+# Rust: a module with src/main/rust/Cargo.toml is checked with `cargo check+# --locked`: workspace members together via `-p` from the repo root, standalone+# crates (own [workspace]) individually in their own dir (host target: fast smoke+# check; the real aarch64 cross-build runs inside the Gradle build via+# cargoNdkBuild). No rust modules -> cargo step skipped.+$ErrorActionPreference = 'Stop'++$CheckRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }++function Show-CheckHelp {+  @'+Usage:+  check.bat <module> [module...]     # detekt (config/detekt/detekt.yml) + cargo check+  check.bat 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++Module notation mirrors install.bat: slash == colon, games:/personal: shorthand,+'all' keyword, deduped. Tasks run with --continue so one broken module does not+block the rest; exit code is nonzero if anything failed.++Rust: a module with src/main/rust/Cargo.toml is checked with `cargo check+--locked`: workspace members together via `-p` from the repo root, standalone+crates (own [workspace]) individually in their own dir (host target: fast smoke+check; the real aarch64 cross-build runs inside the Gradle build via+cargoNdkBuild). No rust modules -> cargo step skipped.+'@+}++function Normalize-CheckModule([string]$M) {+  $M = $M.Trim()+  $M = [regex]::Replace($M, '^[/:]+', '')+  $M = [regex]::Replace($M, '[/:]+$', '')+  $M = $M.Replace('/', ':')+  while ($M.Contains('::')) { $M = $M.Replace('::', ':') }+  return $M.ToLowerInvariant()+}++# all = app + library convention modules (both apply dev.detekt; pure-JVM+# modules like youpipe:extractor do not, so they are excluded here but still+# accepted when named explicitly and left for Gradle to report on).+function Get-CheckAllModuleDirs {+  $CheckSettings = Join-Path $CheckRoot 'settings.gradle.kts'+  $CheckFound = @()+  if (-not (Test-Path -LiteralPath $CheckSettings)) { return $CheckFound }+  foreach ($CheckLine in [System.IO.File]::ReadLines($CheckSettings)) {+    if ($CheckLine -match 'include\(":([^"]+)"\)') {+      $CheckP = $Matches[1].Replace(':', '/')+      if (-not $CheckP) { continue }+      $CheckBuild = Join-Path $CheckRoot "$CheckP/build.gradle.kts"+      if ((Test-Path -LiteralPath $CheckBuild) -and+          (Select-String -LiteralPath $CheckBuild -Pattern 'common-conventions-(app|library)' -Quiet)) {+        $CheckFound += $CheckP+      }+    }+  }+  return @($CheckFound | Sort-Object -Unique)+}++function Get-CheckCargoBin {+  $CheckCargoCmd = Get-Command cargo -ErrorAction SilentlyContinue+  if ($CheckCargoCmd) { return $CheckCargoCmd.Source }+  $CheckCargoHome = if ($env:CARGO_HOME) { $env:CARGO_HOME } else { Join-Path $HOME '.cargo' }+  $CheckCand = Join-Path $CheckCargoHome 'bin/cargo'+  if (Test-Path -LiteralPath $CheckCand -PathType Leaf) { return $CheckCand }+  $CheckCandExe = "$CheckCand.exe"+  if (Test-Path -LiteralPath $CheckCandExe -PathType Leaf) { return $CheckCandExe }+  return ''+}++if ($args.Count -eq 0) {+  Show-CheckHelp+  Write-Output ''+  Write-Output 'Error: no modules specified.'+  exit 1+}+foreach ($CheckA in $args) {+  if ($CheckA -eq '--help' -or $CheckA -eq '-h' -or $CheckA -eq 'help') {+    Show-CheckHelp+    exit 0+  }+}++$CheckMods = @()+$CheckAllExp = $false+foreach ($CheckRaw in $args) {+  $CheckNorm = Normalize-CheckModule ([string]$CheckRaw)+  if (-not $CheckNorm) { continue }+  if ($CheckNorm -eq 'all') {+    if (-not $CheckAllExp) {+      foreach ($CheckSm in (Get-CheckAllModuleDirs)) {+        if ($CheckSm) { $CheckMods += $CheckSm }+      }+      $CheckAllExp = $true+    }+    continue+  }+  if (-not $CheckNorm.Contains(':')) {+    foreach ($CheckPfx in @('games', 'personal')) {+      if (Test-Path -LiteralPath (Join-Path $CheckRoot "$CheckPfx/$CheckNorm/build.gradle.kts")) {+        $CheckNorm = "$CheckPfx`:$CheckNorm"+        break+      }+    }+  }+  $CheckFs = $CheckNorm.Replace(':', '/')+  if (-not (Test-Path -LiteralPath (Join-Path $CheckRoot "$CheckFs/build.gradle.kts"))) {+    [Console]::Error.WriteLine("Error: unknown module '$CheckRaw' (-> $CheckFs/, no build.gradle.kts).")+    exit 1+  }+  if ($CheckMods -notcontains $CheckFs) { $CheckMods += $CheckFs }+}+if ($CheckMods.Count -eq 0) {+  [Console]::Error.WriteLine('Error: no valid modules.')+  exit 1+}++$CheckTasks = @()+foreach ($CheckMod in $CheckMods) {+  $CheckTasks += ":$($CheckMod.Replace('/', ':')):detekt"+}+Write-Output "Modules ($($CheckMods.Count)): $($CheckMods -join ' ')"+Write-Output "Gradle tasks: $($CheckTasks -join ' ')"+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'+$CheckGradlewBat = Join-Path $CheckRoot 'gradlew.bat'+$CheckBashCmd = Get-Command bash -ErrorAction SilentlyContinue+if ($CheckBashCmd -and (Test-Path -LiteralPath $CheckGradlewSh)) {+  $CheckPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  & $CheckBashCmd.Source $CheckGradlewSh @CheckTasks --continue --console=plain+  $CheckDetektRc = $LASTEXITCODE+  $ErrorActionPreference = $CheckPrevPref+}+elseif (Test-Path -LiteralPath $CheckGradlewBat) {+  $CheckPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  & $CheckGradlewBat @CheckTasks --continue --console=plain+  $CheckDetektRc = $LASTEXITCODE+  $ErrorActionPreference = $CheckPrevPref+}+else {+  [Console]::Error.WriteLine('Error: no Gradle wrapper found (gradlew / gradlew.bat).')+  exit 1+}+Write-Output ''+if ($CheckDetektRc -ne 0) { Write-Output "Warning: detekt reported failures (exit $CheckDetektRc)." }++# --- cargo check (rust modules only) ---+# Workspace members share one root `cargo check -p ...` invocation; standalone+# crates (own [workspace] table + lockfile, e.g. games:voxels, code) are checked+# individually with cwd set to the crate dir.+$CheckRootCrates = @()+$CheckStandaloneDirs = @()+foreach ($CheckMod in $CheckMods) {+  $CheckRdir = Join-Path $CheckRoot "$CheckMod/src/main/rust"+  $CheckCt = Join-Path $CheckRdir 'Cargo.toml'+  if (Test-Path -LiteralPath $CheckCt -PathType Leaf) {+    if (Select-String -LiteralPath $CheckCt -Pattern '^\[workspace\]\s*$' -Quiet) {+      $CheckStandaloneDirs += $CheckRdir+      Write-Output "Rust: $CheckMod -> standalone crate ($CheckRdir)"+    }+    else {+      $CheckName = $null+      foreach ($CheckLine in [System.IO.File]::ReadLines($CheckCt)) {+        if ($CheckLine -match '^\s*name\s*=\s*"([^"]+)"') { $CheckName = $Matches[1]; break }+      }+      if ($CheckName) {+        $CheckRootCrates += $CheckName+        Write-Output "Rust: $CheckMod -> workspace crate $CheckName"+      }+    }+  }+}+$CheckCargoRc = 0+$CheckCargoBin = Get-CheckCargoBin+if (-not $CheckCargoBin) {+  [Console]::Error.WriteLine('Error: cargo not found (install Rust or set CARGO_HOME).')+  exit 1+}+if ($CheckRootCrates.Count -gt 0) {+  Write-Output ''+  $CheckCargoArgs = @()+  foreach ($CheckC in $CheckRootCrates) { $CheckCargoArgs += @('-p', $CheckC) }+  Write-Output "Running: cargo check --locked $($CheckCargoArgs -join ' ')"+  $CheckPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  Push-Location -LiteralPath $CheckRoot+  try {+    & $CheckCargoBin check --locked @CheckCargoArgs+    $CheckCargoRc = $LASTEXITCODE+  }+  finally {+    Pop-Location+    $ErrorActionPreference = $CheckPrevPref+  }+  if ($CheckCargoRc -ne 0) { Write-Output "Warning: cargo check (workspace) reported failures (exit $CheckCargoRc)." }+}+foreach ($CheckRdir in $CheckStandaloneDirs) {+  Write-Output ''+  Write-Output "Running: cargo check --locked (in $CheckRdir)"+  $CheckPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  Push-Location -LiteralPath $CheckRdir+  try {+    & $CheckCargoBin check --locked+    $CheckCargoRc = $LASTEXITCODE+  }+  finally {+    Pop-Location+    $ErrorActionPreference = $CheckPrevPref+  }+  if ($CheckCargoRc -ne 0) { Write-Output "Warning: cargo check ($CheckRdir) reported failures (exit $CheckCargoRc)." }+}+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 }+exit 0
dhu.bat
diff --git a/dhu.bat b/dhu.batnew file mode 100644index 0000000000..2c5e113910--- /dev/null+++ b/dhu.bat@@ -0,0 +1,138 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# dhu.bat - Desktop Head Unit loopback against the Pixel 8: adb forward,+# fresh logcat capture, and the DHU in its own window. (PowerShell twin of ./dhu.)+#+# Usage (cmd):+#   dhu.bat                                # full loop, log to analysis/dhu-<timestamp>.log+#   dhu.bat --no-log                       # skip the logcat capture (DHU only)+#   dhu.bat --device-id 44050DLJH001PC     # target a different device+#+# Notes:+#   DHU is interactive: piping its stdout closes stdin and it exits, so it+#   always launches detached. `adb logcat -d` has proven unreliable (stale+#   buffer); this captures live to a file instead.+$ErrorActionPreference = 'Stop'++$DhuScriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }+$DhuDeviceId = '44050DLJH001PC'+$DhuNoLog = $false++function Show-DhuHelp {+  @'+Usage:+  dhu.bat                                # full loop, log to analysis/dhu-<timestamp>.log+  dhu.bat --no-log                       # skip the logcat capture (DHU only)+  dhu.bat --device-id 44050DLJH001PC     # target a different device++Notes:+  DHU is interactive: piping its stdout closes stdin and it exits, so it+  always launches detached. `adb logcat -d` has proven unreliable (stale+  buffer); this captures live to a file instead.+'@+}++$DhuIdx = 0+while ($DhuIdx -lt $args.Count) {+  $DhuArg = [string]$args[$DhuIdx]+  if ($DhuArg -eq '-h' -or $DhuArg -eq '--help' -or $DhuArg -eq 'help') {+    Show-DhuHelp+    exit 0+  }+  elseif ($DhuArg -eq '--no-log' -or $DhuArg -eq '--nolog' -or $DhuArg -eq '-NoLog') {+    $DhuNoLog = $true+    $DhuIdx+++  }+  elseif ($DhuArg -eq '--device-id' -or $DhuArg -eq '-DeviceId') {+    if ($DhuIdx + 1 -ge $args.Count) {+      [Console]::Error.WriteLine('Error: --device-id needs a value.')+      exit 1+    }+    $DhuDeviceId = [string]$args[$DhuIdx + 1]+    $DhuIdx += 2+  }+  elseif ($DhuArg -like '--device-id=*') {+    $DhuDeviceId = $DhuArg.Substring('--device-id='.Length)+    $DhuIdx+++  }+  else {+    [Console]::Error.WriteLine("Error: unknown arg '$DhuArg'. Usage: dhu.bat [--no-log] [--device-id SERIAL]")+    exit 1+  }+}++# SDK location: prefer env, then the usual per-OS defaults (plus Windows LOCALAPPDATA).+$DhuBases = @()+if ($env:ANDROID_HOME) { $DhuBases += $env:ANDROID_HOME }+if ($env:ANDROID_SDK_ROOT) { $DhuBases += $env:ANDROID_SDK_ROOT }+$DhuBases += (Join-Path $HOME 'Android/Sdk')+$DhuBases += (Join-Path $HOME 'Library/Android/sdk')+$DhuBases += '/c/Android/Sdk'+$DhuBases += 'C:/Android/Sdk'+if ($env:LOCALAPPDATA) { $DhuBases += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }++$DhuExe = ''+foreach ($DhuBase in $DhuBases) {+  if (-not $DhuBase) { continue }+  $DhuCand = Join-Path $DhuBase 'extras/google/auto/desktop-head-unit'+  if (Test-Path -LiteralPath $DhuCand -PathType Leaf) { $DhuExe = $DhuCand; break }+  $DhuCandExe = "$DhuCand.exe"+  if (Test-Path -LiteralPath $DhuCandExe -PathType Leaf) { $DhuExe = $DhuCandExe; break }+}+if (-not $DhuExe) {+  [Console]::Error.WriteLine('Error: DHU not found (looked under ANDROID_HOME, ~/Android/Sdk, ~/Library/Android/sdk, /c/Android/Sdk).')+  exit 1+}++# adb: prefer PATH, then platform-tools under the same SDK bases.+$DhuAdbCmd = Get-Command adb -ErrorAction SilentlyContinue+$DhuAdb = if ($DhuAdbCmd) { $DhuAdbCmd.Source } else { '' }+if (-not $DhuAdb) {+  foreach ($DhuBase in $DhuBases) {+    if (-not $DhuBase) { continue }+    foreach ($DhuName in @('platform-tools/adb', 'platform-tools/adb.exe')) {+      $DhuCand = Join-Path $DhuBase $DhuName+      if (Test-Path -LiteralPath $DhuCand -PathType Leaf) { $DhuAdb = $DhuCand; break }+    }+    if ($DhuAdb) { break }+  }+}+if (-not $DhuAdb) {+  [Console]::Error.WriteLine('Error: adb not found (install platform-tools or set ANDROID_HOME).')+  exit 1+}++# The phone listens; the DHU reaches it through the forward.+& $DhuAdb -s $DhuDeviceId forward tcp:5277 tcp:5277+if ($LASTEXITCODE -ne 0) {+  [Console]::Error.WriteLine('Error: adb forward failed.')+  exit 1+}+Write-Output "forward tcp:5277 -> $DhuDeviceId"++if (-not $DhuNoLog) {+  & $DhuAdb -s $DhuDeviceId logcat -c+  $DhuStamp = Get-Date -Format 'yyyyMMdd-HHmmss'+  $DhuLogFile = Join-Path $DhuScriptDir "analysis/dhu-$DhuStamp.log"+  New-Item -ItemType Directory -Force -Path (Split-Path -Parent $DhuLogFile) | Out-Null+  $DhuTags = @(+    '-s', $DhuDeviceId, 'logcat', '-v', 'time',+    'MaAuto.Service:V', 'MaAuto.Server:V', 'MaAuto.Video:V', 'MaAuto.Sensors:V',+    'MaAuto.Input:V', 'MaAuto.HostManager:V', 'MaAuto.HostSession:V', '*:S'+  )+  $DhuJob = Start-Job -Name "dhu-logcat-$DhuStamp" -ScriptBlock {+    param($AdbBin, $LogArgs, $LogPath)+    & $AdbBin @LogArgs *>> $LogPath+  } -ArgumentList $DhuAdb, $DhuTags, $DhuLogFile+  Write-Output "logcat -> $DhuLogFile (job $($DhuJob.Id))"+}++Start-Process -FilePath $DhuExe | Out-Null+Write-Output 'DHU launched (detached)'+exit 0
install.bat
diff --git a/install.bat b/install.batnew file mode 100644index 0000000000..0f57a7bc7b--- /dev/null+++ b/install.bat@@ -0,0 +1,641 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# install.bat - Ergonomic wrapper around gradlew assemble + adb session install.+# (PowerShell twin of ./install.)+#+# Usage (cmd):+#   install.bat [dev|release] <module> [module...]+#   install.bat <module> [module...]            # defaults to dev+#   install.bat [dev|release] all               # installs all app modules+#   install.bat all                             # same, defaults to dev+#   install.bat [dev|release] [8|9] <module>    # Pixel 8 or Pixel 9 (by model)+$ErrorActionPreference = 'Stop'++$InstallRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }++function Show-InstallHelp {+  @'+Usage:+  install.bat [dev|release] <module> [module...]+  install.bat <module> [module...]            # defaults to dev+  install.bat [dev|release] all               # installs all app modules+  install.bat all                             # same, defaults to dev+  install.bat [dev|release] [8|9] <module>    # Pixel 8 or Pixel 9 (by model)++Description:+  Ergonomic wrapper around gradlew :module:assembleDev + adb session install.+  - Variant is swappable and optional (defaults to dev)+  - Supports both slash and colon notations: games/voxels == games:voxels+  - Supports games shorthand: install.bat voxels -> games:voxels (auto-prefixed if games/<name> is a game)+  - Supports personal shorthand: install.bat dooraccess -> personal:dooraccess (auto-prefixed if personal/<name> is a personal app)+  - Supports "all" keyword: install.bat all -> installs every app module+  - Supports multiple modules in one call (single gradlew invocation)+  - 8|9 selects the Pixel 8 or Pixel 9 by model (optional; defaults to the+    first non-emulator device). Also accepts --device 8|9 / --device=8|9.+  - Installs via adb package sessions with the .idsig sidecar staged, so+    updates to preinstalled MAOS system apps get fs-verity (plain+    installDev/installRelease and `adb install` never stage it and always fail+    those updates). Auto-passes -PversionCodeOverride when the on-device+    package is at the same versionCode as the build: +1 for system apps,+    exactly the on-device version for user apps.++Examples:+  install.bat dev contacts                    -> :contacts:assembleDev + session install+  install.bat release games:voxels            -> :games:voxels:assembleRelease + session install+  install.bat dev games/voxels                -> :games:voxels:assembleDev (slash normalized)+  install.bat dev :games:voxels:              -> :games:voxels:assembleDev (colon trimming)+  install.bat voxels                          -> :games:voxels:assembleDev (shorthand auto games:)+  install.bat chess                           -> :games:chess:assembleDev (shorthand auto games:)+  install.bat dooraccess                      -> :personal:dooraccess:assembleDev (shorthand auto personal:)+  install.bat all                             -> :contacts:assembleDev :games:chess:assembleDev ... (all modules)+  install.bat dev all                         -> same as above with dev variant+  install.bat contacts calendar               -> :contacts:assembleDev :calendar:assembleDev+  install.bat release contacts                -> :contacts:assembleRelease + session install+  install.bat contacts dev                    -> :contacts:assembleDev (variant anywhere)+  install.bat 9 maps                        -> :maps:assembleDev + session install to the Pixel 9+  install.bat dev 8 maps                    -> :maps:assembleDev + session install to the Pixel 8+  install.bat --help+  install.bat --dry-run dev contacts          # prints what would run without executing gradle+  install.bat --dry-run all                   # preview all modules++Variant rules:+  - dev (default): assembleDev + session install unless explicitly asked for release+  - release: assembleRelease + session install when explicitly requested+  - debug: BLOCKED - never use assembleDebug++Notes:+  - NEVER uninstalls an app (no uninstall tasks)+  - Validates modules against app modules (those applying common-conventions-app)+  - Installs to the first connected device whose serial does not start with 'emulator'+    (unless 8|9 selects the Pixel 8 or Pixel 9)+  - Set INSTALL_DRY_RUN=1 or pass --dry-run for dry-run mode+'@+}++function Normalize-InstallModule([string]$M) {+  $M = $M.Trim()+  $M = [regex]::Replace($M, '^[/:]+', '')+  $M = [regex]::Replace($M, '[/:]+$', '')+  $M = $M.Replace('/', ':')+  while ($M.Contains('::')) { $M = $M.Replace('::', ':') }+  return $M.ToLowerInvariant()+}++function Get-InstallAppModulesSlash {+  $InstallSettings = Join-Path $InstallRoot 'settings.gradle.kts'+  $InstallFound = @()+  if (-not (Test-Path -LiteralPath $InstallSettings)) { return $InstallFound }+  foreach ($InstallLine in [System.IO.File]::ReadLines($InstallSettings)) {+    if ($InstallLine -match 'include\(":([^"]+)"\)') {+      $InstallP = $Matches[1].Replace(':', '/')+      if (-not $InstallP) { continue }+      $InstallBuild = Join-Path $InstallRoot "$InstallP/build.gradle.kts"+      if ((Test-Path -LiteralPath $InstallBuild) -and+          (Select-String -LiteralPath $InstallBuild -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {+        $InstallFound += $InstallP+      }+    }+  }+  return @($InstallFound | Sort-Object -Unique)+}++function Show-InstallValidModules {+  $InstallSlash = Get-InstallAppModulesSlash+  if ($InstallSlash.Count -eq 0) {+    Write-Output '  (could not discover app modules)'+    return+  }+  Write-Output ''+  Write-Output 'Valid app modules (slash notation for filesystem, colon for Gradle):'+  Write-Output ''+  Write-Output ('  {0,-30} {1}' -f 'Filesystem (slash)', 'Gradle (colon)')+  Write-Output ('  {0,-30} {1}' -f '--------------------', '-------------------')+  foreach ($InstallSm in $InstallSlash) {+    if (-not $InstallSm) { continue }+    Write-Output ('  {0,-30} :{1}' -f $InstallSm, $InstallSm.Replace('/', ':'))+  }+  Write-Output ''+  Write-Output 'Tip: Use either notation: install.bat dev games/voxels  OR  install.bat dev games:voxels'+  Write-Output 'Shorthand: install.bat dev voxels  (auto-expands to games:voxels if games/<name> exists)'+  Write-Output '           install.bat dev dooraccess  (auto-expands to personal:dooraccess if personal/<name> exists)'+  Write-Output 'All: install.bat all  (installs every app module)'+}++function Get-InstallAdb {+  $InstallAdbCmd = Get-Command adb -ErrorAction SilentlyContinue+  if ($InstallAdbCmd) { return $InstallAdbCmd.Source }+  $InstallSdkBases = @()+  if ($env:ANDROID_HOME) { $InstallSdkBases += $env:ANDROID_HOME }+  if ($env:ANDROID_SDK_ROOT) { $InstallSdkBases += $env:ANDROID_SDK_ROOT }+  $InstallSdkBases += (Join-Path $HOME 'Android/Sdk')+  $InstallSdkBases += (Join-Path $HOME 'Library/Android/sdk')+  if ($env:LOCALAPPDATA) { $InstallSdkBases += (Join-Path $env:LOCALAPPDATA 'Android/Sdk') }+  foreach ($InstallBase in $InstallSdkBases) {+    if (-not $InstallBase) { continue }+    foreach ($InstallName in @('platform-tools/adb', 'platform-tools/adb.exe')) {+      $InstallCand = Join-Path $InstallBase $InstallName+      if (Test-Path -LiteralPath $InstallCand -PathType Leaf) { return $InstallCand }+    }+  }+  return ''+}++# applicationId for a module (all are string literals in build.gradle.kts).+function Get-InstallApplicationId([string]$Mod) {+  $InstallBuild = Join-Path $InstallRoot "$($Mod.Replace(':', '/'))/build.gradle.kts"+  if (-not (Test-Path -LiteralPath $InstallBuild)) { return '' }+  foreach ($InstallLine in [System.IO.File]::ReadLines($InstallBuild)) {+    if ($InstallLine -match '^\s*applicationId\s*=\s*"([^"]+)"') { return $Matches[1] }+  }+  return ''+}++# APK built for a module; output-metadata.json names the file authoritatively+# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk).+function Get-InstallBuiltApk([string]$Mod, [string]$VariantLc) {+  $InstallFs = $Mod.Replace(':', '/')+  $InstallOutDir = Join-Path $InstallRoot "$InstallFs/build/outputs/apk/$VariantLc"+  $InstallMeta = Join-Path $InstallOutDir 'output-metadata.json'+  $InstallBaseName = ($Mod -split ':')[-1]+  $InstallFileName = "$InstallBaseName-$VariantLc.apk"+  if (Test-Path -LiteralPath $InstallMeta -PathType Leaf) {+    $InstallMetaText = [System.IO.File]::ReadAllText($InstallMeta)+    $InstallM = [regex]::Match($InstallMetaText, '"outputFile"\s*:\s*"([^"]+)"')+    if ($InstallM.Success -and $InstallM.Groups[1].Value) { $InstallFileName = $InstallM.Groups[1].Value }+  }+  $InstallApk = Join-Path $InstallOutDir $InstallFileName+  if (Test-Path -LiteralPath $InstallApk -PathType Leaf) { return $InstallApk }+  return ''+}++# --- Handle zero args early ---+if ($args.Count -eq 0) {+  Show-InstallHelp+  Write-Output ''+  Write-Output 'Error: No modules specified.'+  Show-InstallValidModules+  exit 1+}++# --- Detect --help/-h/help anywhere ---+foreach ($InstallA in $args) {+  if ($InstallA -eq '--help' -or $InstallA -eq '-h' -or $InstallA -eq 'help') {+    Show-InstallHelp+    exit 0+  }+}++# --- Early DRY_RUN detection ---+$InstallDryRun = ($env:INSTALL_DRY_RUN -eq '1')+foreach ($InstallA in $args) {+  if ([string]$InstallA -eq '--dry-run') { $InstallDryRun = $true }+}++# --- Build FILTERED_ARGS (exclude --dry-run) ---+$InstallFiltered = @()+foreach ($InstallA in $args) {+  if ([string]$InstallA -eq '--dry-run') { continue }+  $InstallFiltered += [string]$InstallA+}+if ($InstallFiltered.Count -eq 0) {+  Show-InstallHelp+  Write-Output ''+  Write-Output 'Error: No modules specified (dry-run mode).'+  Show-InstallValidModules+  exit 1+}++# --- Device hint: bare 8|9 anywhere, or --device 8|9 / --device=8|9 (optional) ---+$InstallDeviceHint = ''+$InstallPrescan = @()+$InstallIdx = 0+while ($InstallIdx -lt $InstallFiltered.Count) {+  $InstallArg = $InstallFiltered[$InstallIdx]+  $InstallLc = $InstallArg.ToLowerInvariant()+  if ($InstallLc -eq '--device') {+    if ($InstallIdx + 1 -ge $InstallFiltered.Count) {+      Write-Output 'Error: --device requires a value: 8 (Pixel 8) or 9 (Pixel 9).'+      exit 1+    }+    $InstallDeviceHint = $InstallFiltered[$InstallIdx + 1].ToLowerInvariant()+    $InstallIdx += 2+    continue+  }+  elseif ($InstallLc -like '--device=*') {+    $InstallDeviceHint = $InstallLc.Substring('--device='.Length)+    $InstallIdx+++    continue+  }+  elseif ($InstallLc -eq '8' -or $InstallLc -eq '9') {+    $InstallDeviceHint = $InstallLc+    $InstallIdx+++    continue+  }+  elseif ($InstallLc -match '^[0-9]+$') {+    Write-Output "Error: Invalid device '$InstallArg'. Use 8 (Pixel 8) or 9 (Pixel 9)."+    exit 1+  }+  $InstallPrescan += $InstallArg+  $InstallIdx+++}+$InstallFiltered = $InstallPrescan+if ($InstallDeviceHint -and ($InstallDeviceHint -ne '8') -and ($InstallDeviceHint -ne '9')) {+  Write-Output "Error: Invalid device '$InstallDeviceHint'. Use 8 (Pixel 8) or 9 (Pixel 9)."+  exit 1+}++# --- Arg parsing: variant detection anywhere ---+$InstallVariantLc = ''+$InstallModulesRaw = @()+foreach ($InstallArg in $InstallFiltered) {+  $InstallLc = $InstallArg.ToLowerInvariant()+  if (($InstallLc -eq 'dev') -or ($InstallLc -eq 'release') -or ($InstallLc -eq 'debug')) {+    if (-not $InstallVariantLc) {+      $InstallVariantLc = $InstallLc+    }+    elseif ($InstallVariantLc -ne $InstallLc) {+      Write-Output "Error: Multiple distinct variants specified: '$InstallVariantLc' and '$InstallLc'."+      Write-Output 'Please specify only one variant: dev or release.'+      Write-Output ''+      Show-InstallHelp+      exit 1+    }+  }+  else {+    $InstallModulesRaw += $InstallArg+  }+}+if (-not $InstallVariantLc) { $InstallVariantLc = 'dev' }++if ($InstallVariantLc -eq 'debug') {+  Write-Output "Error: 'debug' variant is blocked."+  Write-Output ''+  Write-Output '  - Never assemble or install a debug variant'+  Write-Output '  - Always install the dev build, unless specifically asked for release'+  Write-Output ''+  Write-Output 'Use ''dev'' (default) or ''release'' instead:'+  Write-Output '  install.bat dev <module>'+  Write-Output '  install.bat release <module>'+  exit 1+}++if ($InstallModulesRaw.Count -eq 0) {+  Write-Output "Error: No modules specified (only variant '$InstallVariantLc' found)."+  Write-Output ''+  Show-InstallHelp+  Show-InstallValidModules+  exit 1+}++# --- Normalization + Dedup + Shorthand + "all" + auto games: prefix ---+# (dedup via hashtable: insertion-ordered enumeration is NOT relied on; order+# follows first-seen via a companion list.)+$InstallNormalized = @()+$InstallSeenNorm = @{}+$InstallAllExpanded = $false+foreach ($InstallRaw in $InstallModulesRaw) {+  $InstallNorm = Normalize-InstallModule $InstallRaw+  if (-not $InstallNorm) {+    Write-Output "Warning: Skipping empty/invalid module token '$InstallRaw' after normalization."+    continue+  }++  if ($InstallNorm -eq 'all') {+    if (-not $InstallAllExpanded) {+      Write-Output "Info: Expanding 'all' to all app modules..."+      $InstallAllSlash = Get-InstallAppModulesSlash+      if ($InstallAllSlash.Count -eq 0) {+        Write-Output "Error: Could not discover app modules for 'all' expansion."+        Show-InstallValidModules+        exit 1+      }+      foreach ($InstallSm in $InstallAllSlash) {+        if (-not $InstallSm) { continue }+        $InstallColon = $InstallSm.Replace('/', ':')+        if (-not $InstallSeenNorm.ContainsKey($InstallColon)) {+          $InstallSeenNorm[$InstallColon] = $true+          $InstallNormalized += $InstallColon+        }+      }+      $InstallAllExpanded = $true+    }+    continue+  }++  # Auto games:/personal: prefix+  if (-not $InstallNorm.Contains(':')) {+    foreach ($InstallAutoPrefix in @('games', 'personal')) {+      $InstallPrefPath = Join-Path $InstallRoot "$InstallAutoPrefix/$InstallNorm"+      $InstallPrefBuild = Join-Path $InstallPrefPath 'build.gradle.kts'+      $InstallRootAsDir = Join-Path $InstallRoot $InstallNorm+      if ((Test-Path -LiteralPath $InstallPrefBuild) -and+          (Select-String -LiteralPath $InstallPrefBuild -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {+        $InstallExpanded = "$InstallAutoPrefix`:$InstallNorm"+        Write-Output "Info: Expanding shorthand '$InstallRaw' ($InstallNorm) -> $InstallExpanded (found $InstallAutoPrefix/$InstallNorm)"+        $InstallNorm = $InstallExpanded+        break+      }+      elseif ((-not (Test-Path -LiteralPath $InstallRootAsDir)) -and (Test-Path -LiteralPath $InstallPrefPath)) {+        $InstallExpanded = "$InstallAutoPrefix`:$InstallNorm"+        Write-Output "Info: Expanding shorthand '$InstallRaw' ($InstallNorm) -> $InstallExpanded (found $InstallAutoPrefix/$InstallNorm)"+        $InstallNorm = $InstallExpanded+        break+      }+    }+  }++  if (-not $InstallSeenNorm.ContainsKey($InstallNorm)) {+    $InstallSeenNorm[$InstallNorm] = $true+    $InstallNormalized += $InstallNorm+  }+}++if ($InstallNormalized.Count -eq 0) {+  Write-Output 'Error: No valid modules after normalization.'+  Show-InstallValidModules+  exit 1+}++# --- Validation ---+$InstallInvalid = @()+foreach ($InstallMod in $InstallNormalized) {+  $InstallFsPath = $InstallMod.Replace(':', '/')+  $InstallFullPath = Join-Path $InstallRoot $InstallFsPath+  $InstallBuildFile = Join-Path $InstallFullPath 'build.gradle.kts'+  if (-not (Test-Path -LiteralPath $InstallBuildFile)) {+    $InstallInvalid += "$InstallMod (not found: $InstallFsPath/build.gradle.kts)"+  }+  elseif (-not (Select-String -LiteralPath $InstallBuildFile -Pattern 'id("common-conventions-app")' -SimpleMatch -Quiet)) {+    $InstallInvalid += "$InstallMod (exists but is not an app module - missing common-conventions-app)"+  }+}+if ($InstallInvalid.Count -gt 0) {+  Write-Output 'Error: Some modules are invalid:'+  foreach ($InstallBad in $InstallInvalid) { Write-Output "  - $InstallBad" }+  Show-InstallValidModules+  exit 1+}++# --- Build Gradle tasks (assemble only; install happens below via adb sessions) ---+$InstallVariantCap = $InstallVariantLc.Substring(0, 1).ToUpperInvariant() + $InstallVariantLc.Substring(1)+$InstallTasks = @()+foreach ($InstallMod in $InstallNormalized) {+  $InstallTasks += ":${InstallMod}:assemble${InstallVariantCap}"+}++Write-Output "Variant: $InstallVariantLc (assemble + adb session install)"+Write-Output "Modules ($($InstallNormalized.Count)): $($InstallNormalized -join ' ')"+Write-Output "Gradle tasks: $($InstallTasks -join ' ')"+Write-Output ''++# --- Device selection: first connected device whose serial doesn't start with 'emulator' ---+$InstallAdbBin = Get-InstallAdb+$InstallTargetSerial = ''+if ($InstallAdbBin) {+  # hint '' = first non-emulator device; '8' = model Pixel_8;+  # '9' = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL).+  $InstallPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  $InstallDevLines = & $InstallAdbBin devices -l 2>$null+  $ErrorActionPreference = $InstallPrevPref+  foreach ($InstallDevLine in @($InstallDevLines)) {+    $InstallParts = ([string]$InstallDevLine -split '\s+')+    if ($InstallParts.Count -lt 2) { continue }+    $InstallDevSerial = $InstallParts[0]+    $InstallDevState = $InstallParts[1]+    if ($InstallDevState -ne 'device') { continue }+    if ($InstallDevSerial -like 'emulator*') { continue }+    if ($InstallDevSerial -eq 'List') { continue }+    if (-not $InstallDeviceHint) {+      $InstallTargetSerial = $InstallDevSerial+      break+    }+    $InstallDevModel = ''+    $InstallModelM = [regex]::Match([string]$InstallDevLine, 'model:([^\s]+)')+    if ($InstallModelM.Success) { $InstallDevModel = $InstallModelM.Groups[1].Value }+    if (($InstallDeviceHint -eq '8') -and ($InstallDevModel -eq 'Pixel_8')) {+      $InstallTargetSerial = $InstallDevSerial+      break+    }+    if (($InstallDeviceHint -eq '9') -and ($InstallDevModel -like 'Pixel_9*')) {+      $InstallTargetSerial = $InstallDevSerial+      break+    }+  }+}++if (-not $InstallAdbBin) {+  if ($InstallDryRun) {+    Write-Output '[DRY-RUN] Warning: adb not found; a device could not be selected.'+  }+  else {+    Write-Output 'Error: adb not found; cannot select a target device.'+    Write-Output 'Install Android platform-tools and put adb on PATH (or set ANDROID_HOME).'+    exit 1+  }+}+elseif ($InstallTargetSerial) {+  $env:ANDROID_SERIAL = $InstallTargetSerial+  if ($InstallDeviceHint) {+    Write-Output "Target device: $($env:ANDROID_SERIAL) (Pixel $InstallDeviceHint)"+  }+  else {+    Write-Output "Target device: $($env:ANDROID_SERIAL) (first connected device not starting with 'emulator')"+  }+}+elseif ($InstallDeviceHint) {+  Write-Output "Error: No connected Pixel $InstallDeviceHint found (check 'adb devices')."+  exit 1+}+elseif ($InstallDryRun) {+  Write-Output '[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set.'+}+else {+  Write-Output 'Error: No non-emulator device connected.'+  Write-Output "Connect a physical device (check 'adb devices'); refusing to install to an emulator."+  exit 1+}++# --- Extra Gradle args: --continue so one broken module doesn't block the rest ---+$InstallGradleArgs = @('--continue')+$InstallGradleArgsStr = ' --continue'+if (($InstallVariantLc -eq 'release') -and $InstallAllExpanded) {+  $InstallGradleArgs += '-Pandroid.r8.maxWorkers=8'+  $InstallGradleArgsStr += ' -Pandroid.r8.maxWorkers=8'+}++# --- Big-build heap (see ./install comments): escalate only for ALL_EXPANDED ---+if ($InstallAllExpanded) {+  $InstallGradleArgs += '-Dorg.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8'+  $InstallGradleArgs += '--max-workers=32'+  $InstallGradleArgsStr += ' -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32'+}++# --- versionCodeOverride (see ./install comments) ---+$InstallRepoVersion = [int]([System.IO.File]::ReadLines((Join-Path $InstallRoot 'version.txt')) | Select-Object -First 1).Trim()+$InstallNeedBump = $InstallRepoVersion+if ($InstallTargetSerial) {+  $InstallPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  foreach ($InstallMod in $InstallNormalized) {+    $InstallPkg = Get-InstallApplicationId $InstallMod+    if (-not $InstallPkg) { continue }+    $InstallListOut = & $InstallAdbBin -s $InstallTargetSerial shell pm list packages --show-versioncode $InstallPkg 2>$null+    $InstallDevV = 0+    foreach ($InstallListLine in @($InstallListOut)) {+      $InstallVm = [regex]::Match([string]$InstallListLine, 'versionCode:([0-9]+)')+      if ($InstallVm.Success) { $InstallDevV = [int]$InstallVm.Groups[1].Value; break }+    }+    if (($InstallDevV -gt 0) -and ($InstallDevV -ge $InstallNeedBump)) {+      $InstallSysOut = & $InstallAdbBin -s $InstallTargetSerial shell pm list packages -s $InstallPkg 2>$null+      $InstallIsSystem = $false+      foreach ($InstallSysLine in @($InstallSysOut)) {+        if ([string]$InstallSysLine.Trim() -eq "package:$InstallPkg") { $InstallIsSystem = $true; break }+      }+      if ($InstallIsSystem) { $InstallTarget = $InstallDevV + 1; $InstallKind = 'system app' }+      else { $InstallTarget = $InstallDevV; $InstallKind = 'user app' }+      if ($InstallTarget -gt $InstallNeedBump) {+        $InstallNeedBump = $InstallTarget+        Write-Output "Info: $InstallPkg is a $InstallKind at versionCode $InstallDevV on-device (>= repo $InstallRepoVersion); will build with -PversionCodeOverride=$InstallTarget."+      }+    }+  }+  $ErrorActionPreference = $InstallPrevPref+}+if ($InstallNeedBump -gt $InstallRepoVersion) {+  $InstallGradleArgs += "-PversionCodeOverride=$InstallNeedBump"+  $InstallGradleArgsStr += " -PversionCodeOverride=$InstallNeedBump"+}++function Install-ApkViaSession([string]$Apk, [string]$PackageId, [string]$AdbBin, [string]$Serial) {+  $InstallApkName = Split-Path -Leaf $Apk+  $InstallApkSize = (Get-Item -LiteralPath $Apk).Length+  $InstallDeviceApk = "/data/local/tmp/install_${PackageId}.apk"+  Write-Output "Installing $PackageId ($InstallApkName)..."+  $InstallPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  & $AdbBin -s $Serial push $Apk $InstallDeviceApk >$null 2>&1+  if ($LASTEXITCODE -ne 0) {+    $ErrorActionPreference = $InstallPrevPref+    Write-Output "  Error: adb push failed for $InstallApkName."+    return $false+  }+  $InstallCreateOut = & $AdbBin -s $Serial shell pm install-create -r 2>&1+  $InstallSession = ''+  $InstallSm = [regex]::Match(($InstallCreateOut -join "`n"), 'created install session \[([0-9]+)\]')+  if ($InstallSm.Success) { $InstallSession = $InstallSm.Groups[1].Value }+  if (-not $InstallSession) {+    Write-Output '  Error: could not create install session.'+    & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1+    $ErrorActionPreference = $InstallPrevPref+    return $false+  }+  # Stage the APK first, then its .idsig sidecar (V4 signature) under the+  # matching name. PackageManager enables fs-verity from a staged idsig, which+  # MAOS/GrapheneOS requires for updates to preinstalled system apps. Plain+  # `adb install` never stages the sidecar, so those updates always fail.+  & $AdbBin -s $Serial shell pm install-write -S $InstallApkSize $InstallSession base.apk $InstallDeviceApk >$null 2>&1+  if ($LASTEXITCODE -ne 0) {+    Write-Output "  Error: failed to stage $InstallApkName into session $InstallSession."+    & $AdbBin -s $Serial shell pm install-abandon $InstallSession >$null 2>&1+    & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1+    $ErrorActionPreference = $InstallPrevPref+    return $false+  }+  $InstallIdsig = "$Apk.idsig"+  if (Test-Path -LiteralPath $InstallIdsig -PathType Leaf) {+    $InstallDeviceIdsig = "$InstallDeviceApk.idsig"+    & $AdbBin -s $Serial push $InstallIdsig $InstallDeviceIdsig >$null 2>&1+    if ($LASTEXITCODE -eq 0) {+      $InstallIdsigSize = (Get-Item -LiteralPath $InstallIdsig).Length+      & $AdbBin -s $Serial shell pm install-write -S $InstallIdsigSize $InstallSession base.apk.idsig $InstallDeviceIdsig >$null 2>&1+      if ($LASTEXITCODE -ne 0) {+        Write-Output '  Warning: could not stage .idsig; system-app updates may fail fs-verity.'+      }+    }+    else {+      Write-Output '  Warning: could not push .idsig; system-app updates may fail fs-verity.'+    }+    & $AdbBin -s $Serial shell rm -f $InstallDeviceIdsig >$null 2>&1+  }+  else {+    Write-Output '  Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity.'+  }+  $InstallCommitOut = & $AdbBin -s $Serial shell pm install-commit $InstallSession 2>&1+  & $AdbBin -s $Serial shell rm -f $InstallDeviceApk >$null 2>&1+  # `pm install-commit` prints "Success" but exits 0 either way; fail on absence.+  if (-not (($InstallCommitOut -join "`n") -match '(?im)^Success')) {+    Write-Output "  Error: install failed for ${PackageId}: $($InstallCommitOut -join ' ')"+    $ErrorActionPreference = $InstallPrevPref+    return $false+  }+  Write-Output "  Installed $PackageId."+  $ErrorActionPreference = $InstallPrevPref+  return $true+}++if ($InstallDryRun) {+  $InstallGradlewDisp = if (Test-Path -LiteralPath (Join-Path $InstallRoot 'gradlew.bat')) { Join-Path $InstallRoot 'gradlew.bat' } else { Join-Path $InstallRoot 'gradlew' }+  Write-Output "[DRY-RUN] Would execute: $InstallGradlewDisp $($InstallTasks -join ' ')$InstallGradleArgsStr"+  foreach ($InstallMod in $InstallNormalized) {+    $InstallApk = Get-InstallBuiltApk $InstallMod $InstallVariantLc+    if ($InstallApk) {+      Write-Output "[DRY-RUN] Would session-install $(Get-InstallApplicationId $InstallMod) from $InstallApk"+    }+    else {+      Write-Output "[DRY-RUN] Would session-install $(Get-InstallApplicationId $InstallMod) (APK expected after assemble)"+    }+  }+  exit 0+}++# gradlew: gradlew.bat on Windows when present, else extensionless via bash.+$InstallGradlewBat = Join-Path $InstallRoot 'gradlew.bat'+$InstallGradlewSh = Join-Path $InstallRoot 'gradlew'+$InstallBashCmd = Get-Command bash -ErrorAction SilentlyContinue+$InstallPrevPref = $ErrorActionPreference+$ErrorActionPreference = 'Continue'+if (Test-Path -LiteralPath $InstallGradlewBat) {+  Write-Output "Running: $InstallGradlewBat $($InstallTasks -join ' ')$InstallGradleArgsStr"+  Write-Output ''+  & $InstallGradlewBat @InstallTasks @InstallGradleArgs+  $InstallBuildExit = $LASTEXITCODE+}+elseif ($InstallBashCmd -and (Test-Path -LiteralPath $InstallGradlewSh)) {+  Write-Output "Running: $InstallGradlewSh $($InstallTasks -join ' ')$InstallGradleArgsStr"+  Write-Output ''+  & $InstallBashCmd.Source $InstallGradlewSh @InstallTasks @InstallGradleArgs+  $InstallBuildExit = $LASTEXITCODE+}+else {+  Write-Output 'Error: no Gradle wrapper found (gradlew.bat / gradlew).'+  exit 1+}+$ErrorActionPreference = $InstallPrevPref+Write-Output ''++# Install whichever APKs were (re)built, even if sibling modules failed (--continue).+$InstallFailures = 0+if ($InstallBuildExit -ne 0) {+  Write-Output 'Warning: assemble reported failures; installing whatever APKs exist.'+}+foreach ($InstallMod in $InstallNormalized) {+  $InstallApk = Get-InstallBuiltApk $InstallMod $InstallVariantLc+  if ($InstallApk) {+    if (-not (Install-ApkViaSession $InstallApk (Get-InstallApplicationId $InstallMod) $InstallAdbBin $InstallTargetSerial)) {+      $InstallFailures+++    }+  }+  else {+    Write-Output "Error: no APK found for :${InstallMod} (assemble failed?)."+    $InstallFailures+++  }+}+if ($InstallFailures -gt 0) { exit 1 }+exit $InstallBuildExit
release
diff --git a/release.sh b/releasesimilarity index 100%rename from release.shrename to release
release.bat
diff --git a/release.bat b/release.batnew file mode 100644index 0000000000..1700721686--- /dev/null+++ b/release.bat@@ -0,0 +1,339 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# release.bat - Local script to prepare release, build, tag, and push (headless mode).+# (PowerShell twin of ./release.)+$ErrorActionPreference = 'Stop'++$ReleaseRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }+Set-Location -LiteralPath $ReleaseRoot++function Invoke-ReleaseGit([string[]]$GitArgs) {+  $ReleasePrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  $ReleaseOut = & git @GitArgs 2>&1+  $ReleaseRc = $LASTEXITCODE+  $ErrorActionPreference = $ReleasePrevPref+  return @{ Out = @($ReleaseOut); Rc = $ReleaseRc }+}++function ConvertTo-ReleaseRelative([string]$FullPath) {+  $ReleaseSlash = $FullPath.Replace('\', '/')+  $ReleaseRootSlash = $ReleaseRoot.Replace('\', '/').TrimEnd('/')+  if ($ReleaseSlash.StartsWith("$ReleaseRootSlash/")) {+    return $ReleaseSlash.Substring($ReleaseRootSlash.Length + 1)+  }+  return $ReleaseSlash+}++function Get-ReleaseJsonString([string]$S) {+  return ($S -replace '\\', '\\' -replace '"', '\"')+}++# 0. Environment check: Ensure working directory is clean+$ReleaseStatus = Invoke-ReleaseGit @('status', '--porcelain')+if (($ReleaseStatus.Out | Where-Object { [string]$_ -ne '' }).Count -gt 0) {+  Write-Output 'Error: Your working directory is not clean.'+  Write-Output 'Please commit or stash your changes before running the release script.'+  exit 1+}++# Check for GitHub CLI (gh)+$ReleaseGhCmd = Get-Command gh -ErrorAction SilentlyContinue+if (-not $ReleaseGhCmd) {+  Write-Output "Warning: 'gh' (GitHub CLI) is not installed. Release creation will be skipped."+  Write-Output '   Install it from https://cli.github.com/ (winget install GitHub.cli)'+  $ReleaseHasGh = $false+}+else {+  $ReleaseHasGh = $true+}++$ReleaseHead = Invoke-ReleaseGit @('rev-parse', 'HEAD')+$ReleaseOriginalCommit = ([string]$ReleaseHead.Out[0]).Trim()+$ReleaseVersionFile = Join-Path $ReleaseRoot 'version.txt'++if (-not (Test-Path -LiteralPath $ReleaseVersionFile -PathType Leaf)) {+  Write-Output 'Error: version.txt not found!'+  exit 1+}++$ReleaseVersionLines = [System.IO.File]::ReadAllLines($ReleaseVersionFile)+$ReleaseVersionCode = ([string]$ReleaseVersionLines[0]).Trim()+$ReleaseVersionName = ([string]$ReleaseVersionLines[1]).Trim()++$ReleaseEpoch = Invoke-ReleaseGit @('log', '-1', '--pretty=%ct')+$env:SOURCE_DATE_EPOCH = ([string]$ReleaseEpoch.Out[0]).Trim()+Write-Output "SOURCE_DATE_EPOCH=$($env:SOURCE_DATE_EPOCH) for reproducible builds"++Write-Output "Preparing headless release $ReleaseVersionName ($ReleaseVersionCode)..."++# 1. Inject version into build.gradle.kts files+Write-Output 'Injecting versions into sub-module build.gradle.kts files...'+$ReleaseBuildFiles = Get-ChildItem -LiteralPath $ReleaseRoot -Recurse -Filter 'build.gradle.kts' -File -Force -ErrorAction SilentlyContinue |+  Where-Object { $_.FullName.Replace('\', '/') -notlike '*/build-logic/*' }+foreach ($ReleaseBf in $ReleaseBuildFiles) {+  $ReleaseLines = [System.IO.File]::ReadAllLines($ReleaseBf.FullName)+  $ReleaseKept = @()+  foreach ($ReleaseLine in $ReleaseLines) {+    if ($ReleaseLine -match 'versionCode\s*=') { continue }+    if ($ReleaseLine -match 'versionName\s*=') { continue }+    $ReleaseKept += $ReleaseLine+  }+  $ReleaseInjected = @()+  foreach ($ReleaseLine in $ReleaseKept) {+    $ReleaseInjected += $ReleaseLine+    if ($ReleaseLine -match 'defaultConfig\s*\{') {+      $ReleaseInjected += "        versionCode = $ReleaseVersionCode"+      $ReleaseInjected += "        versionName = `"$ReleaseVersionName`""+    }+  }+  [System.IO.File]::WriteAllLines($ReleaseBf.FullName, $ReleaseInjected)+}++# 2. Prepare F-Droid Metadata+Write-Output 'Preparing F-Droid metadata...'+$ReleaseModuleDirs = @($ReleaseBuildFiles |+  ForEach-Object { ConvertTo-ReleaseRelative $_.FullName } |+  ForEach-Object { [regex]::Replace($_, '/build\.gradle\.kts$', '') } |+  Sort-Object -Unique)+foreach ($ReleaseDir in $ReleaseModuleDirs) {+  $ReleaseModuleKey = $ReleaseDir.Replace('/', '-')+  $ReleaseTargetPath = Join-Path $ReleaseRoot "$ReleaseDir/src/main/play/listings/en-US"+  $ReleaseMd = Join-Path $ReleaseRoot "metadata_data/$ReleaseModuleKey.md"+  $ReleaseIcon = Join-Path $ReleaseRoot "$ReleaseDir/src/main/ic_launcher-playstore.png"+  if ((Test-Path -LiteralPath $ReleaseMd) -or (Test-Path -LiteralPath $ReleaseIcon)) {+    New-Item -ItemType Directory -Force -Path "$ReleaseTargetPath/graphics/icon" | Out-Null+    New-Item -ItemType Directory -Force -Path "$ReleaseTargetPath/graphics/phone-screenshots" | Out-Null+    if (Test-Path -LiteralPath $ReleaseIcon) {+      Copy-Item -LiteralPath $ReleaseIcon -Destination "$ReleaseTargetPath/graphics/icon/icon.png" -Force+    }+    $ReleasePhotosDir = Join-Path $ReleaseRoot "metadata_data/photos/$ReleaseModuleKey"+    $ReleasePhotoFile = Join-Path $ReleaseRoot "metadata_data/photos/$ReleaseModuleKey.png"+    if (Test-Path -LiteralPath $ReleasePhotosDir -PathType Container) {+      $ReleaseI = 1+      # natural (version) sort like `sort -V`: 2.png before 10.png.+      $ReleaseShots = Get-ChildItem -LiteralPath $ReleasePhotosDir -Filter '*.png' -File |+        Sort-Object { [regex]::Replace($_.Name, '\d+', { param($M) $M.Value.PadLeft(10, '0') }) }+      foreach ($ReleaseShot in $ReleaseShots) {+        Copy-Item -LiteralPath $ReleaseShot.FullName -Destination "$ReleaseTargetPath/graphics/phone-screenshots/$ReleaseI.png" -Force+        $ReleaseI+++      }+    }+    elseif (Test-Path -LiteralPath $ReleasePhotoFile) {+      Copy-Item -LiteralPath $ReleasePhotoFile -Destination "$ReleaseTargetPath/graphics/phone-screenshots/1.png" -Force+    }+    if (Test-Path -LiteralPath $ReleaseMd) {+      $ReleaseMdLines = [System.IO.File]::ReadAllLines($ReleaseMd)+      [System.IO.File]::WriteAllText("$ReleaseTargetPath/short-description.txt", $ReleaseMdLines[0])+      Copy-Item -LiteralPath $ReleaseMd -Destination "$ReleaseTargetPath/full-description.txt" -Force+    }+  }+}++# 3. Git Commit and Tag (Done BEFORE build so build sees committed state)+Write-Output 'Creating temporary commit and tag...'+# Reproducible builds: make commit/tag timestamps deterministic using SOURCE_DATE_EPOCH+# so the tag object doesn't embed wall-clock time and can be verified.+$env:GIT_AUTHOR_DATE = "@$($env:SOURCE_DATE_EPOCH)"+$env:GIT_COMMITTER_DATE = "@$($env:SOURCE_DATE_EPOCH)"+$ReleaseAdd = Invoke-ReleaseGit @('add', '.')+$ReleaseCommit = Invoke-ReleaseGit @('commit', '-m', "chore: prepare release $ReleaseVersionName")+if ($ReleaseCommit.Rc -ne 0) {+  Write-Output 'No changes to commit'+  exit 1+}+$ReleaseTag = Invoke-ReleaseGit @('tag', '-a', $ReleaseVersionName, '-m', "Release $ReleaseVersionName")+if ($ReleaseTag.Rc -ne 0) {+  Write-Output "Error: git tag failed: $($ReleaseTag.Out -join ' ')"+  exit 1+}++# 4. Build Apps (Parallel with Worker Limits)+Write-Output 'Building all app modules in parallel (constrained)...'+# Detect modules that apply the app conventions+$ReleaseAppModules = @()+foreach ($ReleaseBf in $ReleaseBuildFiles) {+  if (Select-String -LiteralPath $ReleaseBf.FullName -Pattern 'common-conventions-app' -Quiet) {+    $ReleaseAppModules += [regex]::Replace((ConvertTo-ReleaseRelative $ReleaseBf.FullName), '/build\.gradle\.kts$', '')+  }+}+$ReleaseAppModules = @($ReleaseAppModules | Sort-Object -Unique)+$ReleaseTasks = @()+foreach ($ReleaseMod in $ReleaseAppModules) {+  $ReleaseTasks += ":$($ReleaseMod.Replace('/', ':')):assembleRelease"+}++$ReleaseDistDir = Join-Path $ReleaseRoot 'distribution_apks'+if (Test-Path -LiteralPath $ReleaseDistDir) { Remove-Item -LiteralPath $ReleaseDistDir -Recurse -Force }+New-Item -ItemType Directory -Force -Path $ReleaseDistDir | Out-Null++# - --parallel: Build modules in parallel+# - --max-workers=2: Strictly limit concurrent tasks to prevent memory spikes+# - --no-daemon: Use a fresh process to ensure memory is released after build+$ReleaseGradlewBat = Join-Path $ReleaseRoot 'gradlew.bat'+$ReleaseGradlewSh = Join-Path $ReleaseRoot 'gradlew'+$ReleaseBashCmd = Get-Command bash -ErrorAction SilentlyContinue+$ReleasePrevPref = $ErrorActionPreference+$ErrorActionPreference = 'Continue'+$ReleaseGradleArgs = @($ReleaseTasks) + @(+  '--parallel', '--max-workers=2', '--no-daemon',+  '-x', 'lint', '-x', 'test',+  '-Pandroid.enableResourceOptimizations=true',+  '-Pandroid.enableR8.fullMode=true',+  '-Dorg.gradle.jvmargs=-Xmx6g -XX:MaxMetaspaceSize=1g'+)+if ((Test-Path -LiteralPath $ReleaseGradlewBat) -and ($env:OS -eq 'Windows_NT')) {+  & $ReleaseGradlewBat @ReleaseGradleArgs+  $ReleaseBuildRc = $LASTEXITCODE+}+elseif ($ReleaseBashCmd -and (Test-Path -LiteralPath $ReleaseGradlewSh)) {+  & $ReleaseBashCmd.Source $ReleaseGradlewSh @ReleaseGradleArgs+  $ReleaseBuildRc = $LASTEXITCODE+}+else {+  $ErrorActionPreference = $ReleasePrevPref+  Write-Output 'Error: no Gradle wrapper found (gradlew.bat / gradlew).'+  exit 1+}+$ErrorActionPreference = $ReleasePrevPref+if ($ReleaseBuildRc -ne 0) {+  Write-Output "Error: Gradle build failed (exit $ReleaseBuildRc)."+  exit 1+}++# 5. Consolidate APKs+Write-Output 'Collecting APKs into distribution_apks/...'+Get-ChildItem -LiteralPath $ReleaseRoot -Recurse -Filter '*.apk' -File -Force -ErrorAction SilentlyContinue |+  Where-Object { $_.FullName.Replace('\', '/') -like '*/build/outputs/apk/release/*.apk' } |+  ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination $ReleaseDistDir -Force }++# 5b. Build index.json for the :appstore "Modern Apps" source.+# The store cannot map an asset filename back to a package name on its own+# (:games:chess builds chess-release.apk but installs as com.vayunmathur.games.chess),+# so the release has to state it. This index is NOT signed and does not need to be:+# :appstore verifies every APK from this source against its own signing certificate,+# so a rewritten index can change which bytes are offered but not which bytes install.+Write-Output 'Generating distribution_apks/index.json...'+$ReleaseSdkBase = if ($env:ANDROID_HOME) { $env:ANDROID_HOME } elseif ($env:ANDROID_SDK_ROOT) { $env:ANDROID_SDK_ROOT } else { Join-Path $HOME 'Library/Android/sdk' }+if ($env:LOCALAPPDATA -and (-not (Test-Path -LiteralPath (Join-Path $ReleaseSdkBase 'build-tools')))) {+  $ReleaseSdkBase = Join-Path $env:LOCALAPPDATA 'Android/Sdk'+}+$ReleaseAapt2 = Get-ChildItem -LiteralPath (Join-Path $ReleaseSdkBase 'build-tools') -Filter 'aapt2*' -File -Recurse -ErrorAction SilentlyContinue |+  Sort-Object FullName | Select-Object -Last 1+if (-not $ReleaseAapt2) {+  Write-Output 'Error: aapt2 not found under $ANDROID_HOME/build-tools; cannot generate index.json'+  exit 1+}++# 5b index helpers (ConvertTo-ReleaseRelative, Get-ReleaseJsonString) are defined+# at the top next to Invoke-ReleaseGit: PowerShell executes straight-line code+# in order, so helpers must be defined before step 2 calls them.+$ReleaseIndexPath = Join-Path $ReleaseDistDir 'index.json'+$ReleaseIndexLines = @(+  '{',+  "  `"versionCode`": $ReleaseVersionCode,",+  "  `"versionName`": `"$ReleaseVersionName`",",+  '  "apps": ['+)+$ReleaseFirst = $true+$ReleaseApks = @(Get-ChildItem -LiteralPath $ReleaseDistDir -Filter '*.apk' -File | Sort-Object Name)+foreach ($ReleaseApk in $ReleaseApks) {+  $ReleaseBadging = & $ReleaseAapt2.FullName dump badging $ReleaseApk.FullName 2>$null+  $ReleaseBadgingText = ($ReleaseBadging -join "`n")+  $ReleasePkg = ''+  $ReleaseVcode = ''+  $ReleaseVname = ''+  $ReleaseTsdk = ''+  $ReleaseLabel = ''+  $ReleaseM = [regex]::Match($ReleaseBadgingText, "^package: name='([^']*)'", 'Multiline')+  if ($ReleaseM.Success) { $ReleasePkg = $ReleaseM.Groups[1].Value }+  $ReleaseM = [regex]::Match($ReleaseBadgingText, "versionCode='([^']*)'")+  if ($ReleaseM.Success) { $ReleaseVcode = $ReleaseM.Groups[1].Value }+  $ReleaseM = [regex]::Match($ReleaseBadgingText, "versionName='([^']*)'")+  if ($ReleaseM.Success) { $ReleaseVname = $ReleaseM.Groups[1].Value }+  $ReleaseM = [regex]::Match($ReleaseBadgingText, "^targetSdkVersion:'([^']*)'", 'Multiline')+  if ($ReleaseM.Success) { $ReleaseTsdk = $ReleaseM.Groups[1].Value }+  $ReleaseM = [regex]::Match($ReleaseBadgingText, "^application-label:'([^']*)'", 'Multiline')+  if ($ReleaseM.Success) { $ReleaseLabel = $ReleaseM.Groups[1].Value }+  if (-not $ReleasePkg) {+    Write-Output "Warning: Skipping $($ReleaseApk.Name) (aapt2 could not read a package name)"+    continue+  }+  if (-not $ReleaseLabel) { $ReleaseLabel = $ReleasePkg }+  $ReleaseSha = (Get-FileHash -LiteralPath $ReleaseApk.FullName -Algorithm SHA256).Hash.ToLowerInvariant()+  $ReleaseSize = (Get-Item -LiteralPath $ReleaseApk.FullName).Length+  # Short description = first line of the F-Droid metadata, when there is one.+  $ReleaseFoundBuild = ''+  foreach ($ReleaseBf in $ReleaseBuildFiles) {+    if (Select-String -LiteralPath $ReleaseBf.FullName -Pattern "applicationId = `"$ReleasePkg`"" -SimpleMatch -Quiet) {+      $ReleaseFoundBuild = $ReleaseBf.FullName+      break+    }+  }+  $ReleaseSummary = ''+  if ($ReleaseFoundBuild) {+    $ReleaseModKey = [regex]::Replace((ConvertTo-ReleaseRelative $ReleaseFoundBuild), '/build\.gradle\.kts$', '').Replace('/', '-')+    $ReleaseMdPath = Join-Path $ReleaseRoot "metadata_data/$ReleaseModKey.md"+    if (Test-Path -LiteralPath $ReleaseMdPath) {+      $ReleaseSummary = Get-ReleaseJsonString ([System.IO.File]::ReadAllLines($ReleaseMdPath)[0])+    }+  }+  if (-not $ReleaseFirst) { $ReleaseIndexLines += ',' }+  $ReleaseFirst = $false+  if (-not $ReleaseVcode) { $ReleaseVcode = '0' }+  if (-not $ReleaseVname) { $ReleaseVname = $ReleaseVersionName }+  if (-not $ReleaseTsdk) { $ReleaseTsdk = '0' }+  $ReleaseIndexLines[-1] += "    {`"packageName`": `"$ReleasePkg`", `"label`": `"$(Get-ReleaseJsonString $ReleaseLabel)`", `"apk`": `"$($ReleaseApk.Name)`", `"sha256`": `"$ReleaseSha`", `"size`": $ReleaseSize, `"versionCode`": $ReleaseVcode, `"versionName`": `"$(Get-ReleaseJsonString $ReleaseVname)`", `"targetSdk`": $ReleaseTsdk, `"summary`": `"$ReleaseSummary`"}"+}+$ReleaseIndexLines += '  ]'+$ReleaseIndexLines += '}'+[System.IO.File]::WriteAllLines($ReleaseIndexPath, $ReleaseIndexLines)++$ReleaseIndexed = ([regex]::Matches([System.IO.File]::ReadAllText($ReleaseIndexPath), '"packageName"')).Count+Write-Output "   $ReleaseIndexed apps indexed"++# 6. Push Tag and Create GitHub Release+Write-Output "Pushing tag $ReleaseVersionName to origin..."+$ReleasePush = Invoke-ReleaseGit @('push', 'origin', $ReleaseVersionName)+if ($ReleasePush.Rc -ne 0) {+  Write-Output "Error: git push failed: $($ReleasePush.Out -join ' ')"+  exit 1+}++if ($ReleaseHasGh) {+  Write-Output 'Creating GitHub Release...'+  $ReleaseAssets = @((Get-ChildItem -LiteralPath $ReleaseDistDir -Filter '*.apk' -File | ForEach-Object { $_.FullName })) + @($ReleaseIndexPath)+  $ReleasePrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  & $ReleaseGhCmd.Source release create $ReleaseVersionName @ReleaseAssets `+    --title "Release $ReleaseVersionName" `+    --notes "Automated multi-module release. Version Code: $ReleaseVersionCode" `+    --draft+  $ReleaseGhRc = $LASTEXITCODE+  $ErrorActionPreference = $ReleasePrevPref+  if ($ReleaseGhRc -ne 0) {+    Write-Output "Error: gh release create failed (exit $ReleaseGhRc)."+    exit 1+  }+  Write-Output 'Release created as a draft.'+}+else {+  Write-Output 'Skipping GitHub Release creation (gh CLI not found).'+}++# 7. Restore local branch state (Headless effect)+Write-Output "Restoring local branch to original state ($ReleaseOriginalCommit)..."+$ReleaseReset = Invoke-ReleaseGit @('reset', '--hard', $ReleaseOriginalCommit)+if ($ReleaseReset.Rc -ne 0) {+  Write-Output "Error: git reset failed: $($ReleaseReset.Out -join ' ')"+  exit 1+}++Write-Output 'Done! All apps built and tag pushed.'+exit 0
search.bat
diff --git a/search.bat b/search.batnew file mode 100644index 0000000000..1b7e7f962a--- /dev/null+++ b/search.bat@@ -0,0 +1,382 @@+<# :+@echo off+setlocal+where pwsh >nul 2>nul+if %errorlevel%==0 ( set "PSBIN=pwsh" ) else ( set "PSBIN=powershell" )+%PSBIN% -NoProfile -ExecutionPolicy Bypass -Command "$env:_BATROOT='%~dp0'; $env:_BATPATH='%~f0'; & ([scriptblock]::Create((Get-Content -Raw '%~f0'))) %*"+exit /b %errorlevel%+: end batch #>+# search.bat - Scoped string search for the Modern-Apps monorepo.+# (PowerShell twin of ./search.) Uses rg when available, else Select-String.+#+# Usage (cmd):+#   search.bat PATTERN [-m MODULE ...] [-p PACKAGE ...] [-i] [--max N] [--files-only]+$ErrorActionPreference = 'Stop'++$SearchRoot = if ($PSScriptRoot) { $PSScriptRoot } else { $env:_BATROOT.TrimEnd('\') }+$SearchMaxCols = 220+$SearchDefaultMax = 200+$SearchKnownPackages = @('ui', 'data', 'domain', 'platform', 'network', 'intents', 'service', 'provider', 'widget', 'notifications', 'auth', 'sync', 'telephony')+$SearchExcludeDirs = @('target', 'build', '.gradle', '.kotlin', '.git', '.llms', 'analysis')++function Show-SearchHelp {+  @'+Usage:+  search.bat PATTERN [-m MODULE ...] [-p PACKAGE ...] [-i] [--max N] [--files-only]++  -m/--module   Repeatable, comma-separated. Slash == colon+                (games/voxels == games:voxels), shorthand (voxels -> games:voxels),+                or 'all' (every dir with build.gradle.kts).+  -p/--package  Repeatable, comma-separated root package (ui data domain platform+                network intents service provider widget notifications auth sync+                telephony). Searches only <module>/src/main/{java,kotlin}/**/<pkg>/.+                Needs -m; without it a warning is printed and it is ignored.+  -i            Case-insensitive. --max N caps output lines (default 200).+  --files-only  Print matching file paths, no contents.++Always excluded: target/ build/ .gradle/ .kotlin/ .git/ .llms/ analysis/+*.log *.onnx metadata_data/photos/. Exit code is 0 on success even with no+matches; 1 when every -m value is unknown; 2 on bad regex.+'@+}++function Normalize-SearchModule([string]$M) {+  $M = $M.Trim()+  $M = [regex]::Replace($M, '^[/:]+', '')+  $M = [regex]::Replace($M, '[/:]+$', '')+  $M = $M.Replace('/', ':')+  while ($M.Contains('::')) { $M = $M.Replace('::', ':') }+  return $M.ToLowerInvariant()+}++function Get-SearchAllModuleDirs {+  $SearchSettings = Join-Path $SearchRoot 'settings.gradle.kts'+  $SearchFound = @()+  if (-not (Test-Path -LiteralPath $SearchSettings)) { return $SearchFound }+  foreach ($SearchLine in [System.IO.File]::ReadLines($SearchSettings)) {+    if ($SearchLine -match 'include\(":([^"]+)"\)') {+      $SearchP = $Matches[1]+      $SearchP = [regex]::Replace($SearchP, '^:', '')+      $SearchP = $SearchP.Replace(':', '/')+      if ($SearchP -and (Test-Path -LiteralPath (Join-Path $SearchRoot "$SearchP/build.gradle.kts"))) {+        $SearchFound += $SearchP+      }+    }+  }+  return @($SearchFound | Sort-Object -Unique)+}++function ConvertTo-SearchRelative([string]$FullPath) {+  $SearchSlash = $FullPath.Replace('\', '/')+  $SearchRootSlash = $SearchRoot.Replace('\', '/').TrimEnd('/')+  if ($SearchSlash.StartsWith("$SearchRootSlash/")) {+    return $SearchSlash.Substring($SearchRootSlash.Length + 1)+  }+  return $SearchSlash+}++function Get-SearchPkgDirs([string]$Mod, [string[]]$Pkgs) {+  $SearchPkgFound = @()+  foreach ($SearchLang in @('java', 'kotlin')) {+    $SearchBase = Join-Path $SearchRoot "$Mod/src/main/$SearchLang"+    if (-not (Test-Path -LiteralPath $SearchBase)) { continue }+    foreach ($SearchPkg in $Pkgs) {+      # repo-relative paths (bash prints find-relatives too); absolute paths+      # would resurface as drive-colon lines that break path:line parsing.+      $SearchPkgFound += @(Get-ChildItem -LiteralPath $SearchBase -Recurse -Directory -Force -ErrorAction SilentlyContinue |+        Where-Object { $_.Name -ceq $SearchPkg } |+        ForEach-Object { ConvertTo-SearchRelative $_.FullName })+    }+  }+  # drop dirs subsumed by another match (e.g. data/ inside data/)+  $SearchKept = @()+  foreach ($SearchA in $SearchPkgFound) {+    $SearchASlash = $SearchA.Replace('\', '/')+    $SearchSkip = $false+    foreach ($SearchB in $SearchPkgFound) {+      $SearchBSlash = $SearchB.Replace('\', '/')+      if (($SearchASlash -ne $SearchBSlash) -and $SearchASlash.StartsWith("$SearchBSlash/")) {+        $SearchSkip = $true+        break+      }+    }+    if (-not $SearchSkip) { $SearchKept += $SearchA }+  }+  return @($SearchKept | Sort-Object -Unique)+}++function Test-SearchExcluded([string]$FullPath) {+  $SearchSlash = $FullPath.Replace('\', '/')+  $SearchRootSlash = $SearchRoot.Replace('\', '/').TrimEnd('/')+  if ($SearchSlash.StartsWith("$SearchRootSlash/")) {+    $SearchSlash = $SearchSlash.Substring($SearchRootSlash.Length + 1)+  }+  $SearchSegs = $SearchSlash.Split('/')+  for ($SearchI = 0; $SearchI -lt $SearchSegs.Count - 1; $SearchI++) {+    if ($SearchExcludeDirs -contains $SearchSegs[$SearchI]) { return $true }+  }+  if ($SearchSlash -like 'metadata_data/photos/*') { return $true }+  $SearchLeaf = $SearchSegs[$SearchSegs.Count - 1]+  if ($SearchLeaf -like '*.log' -or $SearchLeaf -like '*.onnx') { return $true }+  return $false+}++$SearchHasRg = $null -ne (Get-Command rg -ErrorAction SilentlyContinue)++function Invoke-SearchRg([string]$Pattern, [string[]]$Dirs) {+  $SearchRgArgs = @('--no-heading', '--line-number', '--color', 'never', '--hidden', '--path-separator', '/',+    '-g', '!target/**', '-g', '!build/**', '-g', '!.gradle/**', '-g', '!.kotlin/**',+    '-g', '!.git/**', '-g', '!.llms/**', '-g', '!analysis/**',+    '-g', '!*.log', '-g', '!*.onnx', '-g', '!metadata_data/photos/**',+    '--max-columns', "$SearchMaxCols")+  if ($SearchIgnoreCase) { $SearchRgArgs += '-i' }+  $SearchRgArgs += @('-e', $Pattern, '--') + $Dirs+  $SearchPrevPref = $ErrorActionPreference+  $ErrorActionPreference = 'Continue'+  $SearchOut = & rg @SearchRgArgs 2>$null+  $SearchRc = $LASTEXITCODE+  $ErrorActionPreference = $SearchPrevPref+  if ($SearchRc -eq 2) {+    [Console]::Error.WriteLine("error: bad regex: $Pattern")+    exit 2+  }+  $SearchLines = @()+  $SearchRootSlash = $SearchRoot.Replace('\', '/').TrimEnd('/')+  foreach ($SearchLine in @($SearchOut)) {+    $SearchNorm = ([string]$SearchLine).Replace('\', '/')+    $SearchNorm = [regex]::Replace($SearchNorm, '^\./', '')+    # defensive: if rg printed an absolute path (e.g. caller passed one),+    # relativize so path:line parsing and --files-only splits stay correct.+    if ($SearchNorm.StartsWith("$SearchRootSlash/")) {+      $SearchNorm = $SearchNorm.Substring($SearchRootSlash.Length + 1)+    }+    $SearchLines += $SearchNorm+  }+  return $SearchLines+}++function Invoke-SearchSelectString([string]$Pattern, [string[]]$Dirs) {+  try {+    $SearchOptions = [System.Text.RegularExpressions.RegexOptions]::None+    if ($SearchIgnoreCase) { $SearchOptions = [System.Text.RegularExpressions.RegexOptions]::IgnoreCase }+    $null = New-Object System.Text.RegularExpressions.Regex($Pattern, $SearchOptions)+  }+  catch {+    [Console]::Error.WriteLine("error: bad regex: $Pattern")+    exit 2+  }+  $SearchFiles = @()+  foreach ($SearchDir in $Dirs) {+    $SearchAbs = if ([System.IO.Path]::IsPathRooted($SearchDir)) { $SearchDir } else { Join-Path $SearchRoot $SearchDir }+    if (-not (Test-Path -LiteralPath $SearchAbs)) { continue }+    $SearchItem = Get-Item -LiteralPath $SearchAbs -Force -ErrorAction SilentlyContinue+    if ($null -eq $SearchItem) { continue }+    if ($SearchItem -is [System.IO.DirectoryInfo]) {+      $SearchFiles += @(Get-ChildItem -LiteralPath $SearchAbs -Recurse -File -Force -ErrorAction SilentlyContinue |+        Where-Object { -not (Test-SearchExcluded $_.FullName) })+    }+    elseif (-not (Test-SearchExcluded $SearchItem.FullName)) {+      $SearchFiles += $SearchItem+    }+  }+  $SearchLines = @()+  $SearchSelectOpts = @{}+  if ($SearchIgnoreCase) { $SearchSelectOpts['CaseSensitive'] = $false } else { $SearchSelectOpts['CaseSensitive'] = $true }+  foreach ($SearchFile in $SearchFiles) {+    $SearchMatches = Select-String -LiteralPath $SearchFile.FullName -Pattern $Pattern @SearchSelectOpts 2>$null+    foreach ($SearchM in @($SearchMatches)) {+      $SearchText = [string]$SearchM.Line+      if ($SearchText.Length -gt $SearchMaxCols) { $SearchText = $SearchText.Substring(0, $SearchMaxCols) }+      $SearchLines += "$(ConvertTo-SearchRelative $SearchFile.FullName):$($SearchM.LineNumber):$SearchText"+    }+  }+  return $SearchLines+}++function Invoke-SearchDirs([string]$Pattern, [string[]]$Dirs) {+  if ($SearchHasRg) { return Invoke-SearchRg $Pattern $Dirs }+  return Invoke-SearchSelectString $Pattern $Dirs+}++# --- arg parsing ---+$SearchPattern = ''+$SearchIgnoreCase = $false+$SearchMax = $SearchDefaultMax+$SearchFilesOnly = $false+$SearchModsRaw = @()+$SearchPkgsRaw = @()+$SearchIdx = 0+while ($SearchIdx -lt $args.Count) {+  $SearchArg = [string]$args[$SearchIdx]+  if ($SearchArg -eq '-h' -or $SearchArg -eq '--help' -or $SearchArg -eq 'help') {+    Show-SearchHelp+    exit 0+  }+  elseif ($SearchArg -eq '-m' -or $SearchArg -eq '--module') {+    $SearchIdx+++    while (($SearchIdx -lt $args.Count) -and (-not ([string]$args[$SearchIdx]).StartsWith('-'))) {+      $SearchModsRaw += [string]$args[$SearchIdx]+      $SearchIdx+++    }+  }+  elseif ($SearchArg -eq '-p' -or $SearchArg -eq '--package') {+    $SearchIdx+++    while (($SearchIdx -lt $args.Count) -and (-not ([string]$args[$SearchIdx]).StartsWith('-'))) {+      $SearchPkgsRaw += [string]$args[$SearchIdx]+      $SearchIdx+++    }+  }+  elseif ($SearchArg -eq '-i' -or $SearchArg -eq '--ignore-case') {+    $SearchIgnoreCase = $true+    $SearchIdx+++  }+  elseif ($SearchArg -eq '--max') {+    if ($SearchIdx + 1 -ge $args.Count) {+      [Console]::Error.WriteLine('Error: --max needs a value.')+      exit 1+    }+    $SearchMax = [int]$args[$SearchIdx + 1]+    $SearchIdx += 2+  }+  elseif ($SearchArg -like '--max=*') {+    $SearchMax = [int]$SearchArg.Substring('--max='.Length)+    $SearchIdx+++  }+  elseif ($SearchArg -eq '--files-only') {+    $SearchFilesOnly = $true+    $SearchIdx+++  }+  elseif ($SearchArg -eq '--') {+    $SearchIdx+++    if ((-not $SearchPattern) -and ($SearchIdx -lt $args.Count)) {+      $SearchPattern = [string]$args[$SearchIdx]+      $SearchIdx+++    }+  }+  elseif ($SearchArg.StartsWith('-')) {+    [Console]::Error.WriteLine("Error: unknown flag '$SearchArg'.")+    exit 1+  }+  else {+    if (-not $SearchPattern) {+      $SearchPattern = $SearchArg+    }+    else {+      [Console]::Error.WriteLine("Error: unexpected arg '$SearchArg' (pattern already set).")+      exit 1+    }+    $SearchIdx+++  }+}+if (-not $SearchPattern) {+  [Console]::Error.WriteLine('Error: no pattern. Usage: search.bat PATTERN [-m MODULE] [-p PACKAGE]')+  exit 1+}++# split comma-separated filter values+$SearchModsSplit = @()+foreach ($SearchM in $SearchModsRaw) {+  foreach ($SearchPart in $SearchM.Split(',')) {+    if ($SearchPart) { $SearchModsSplit += $SearchPart }+  }+}+$SearchPkgsSplit = @()+foreach ($SearchM in $SearchPkgsRaw) {+  foreach ($SearchPart in $SearchM.Split(',')) {+    if ($SearchPart) { $SearchPkgsSplit += $SearchPart.ToLowerInvariant() }+  }+}+foreach ($SearchP in $SearchPkgsSplit) {+  if ($SearchKnownPackages -notcontains $SearchP) {+    [Console]::Error.WriteLine("warning: unknown root package '$SearchP'.")+  }+}++# resolve modules+$SearchMods = @()+$SearchAllExp = $false+foreach ($SearchRaw in $SearchModsSplit) {+  $SearchNorm = Normalize-SearchModule $SearchRaw+  if ($SearchNorm -eq 'all') {+    if (-not $SearchAllExp) {+      foreach ($SearchSm in (Get-SearchAllModuleDirs)) {+        if ($SearchSm) { $SearchMods += $SearchSm }+      }+      $SearchAllExp = $true+    }+    continue+  }+  if (-not $SearchNorm.Contains(':')) {+    foreach ($SearchPfx in @('games', 'personal')) {+      if (Test-Path -LiteralPath (Join-Path $SearchRoot "$SearchPfx/$SearchNorm/build.gradle.kts")) {+        $SearchNorm = "$SearchPfx`:$SearchNorm"+        break+      }+    }+  }+  $SearchFs = $SearchNorm.Replace(':', '/')+  if (-not (Test-Path -LiteralPath (Join-Path $SearchRoot $SearchFs))) {+    [Console]::Error.WriteLine("warning: skipping unknown module '$SearchRaw' (-> $SearchFs/).")+    continue+  }+  if ($SearchMods -notcontains $SearchFs) { $SearchMods += $SearchFs }+}+if (($SearchModsRaw.Count -gt 0) -and ($SearchMods.Count -eq 0)) {+  [Console]::Error.WriteLine('error: no valid modules (all -m values unknown)')+  exit 1+}++Set-Location -LiteralPath $SearchRoot  # backends then print repo-relative paths+# NOTE: state lives in a hashtable (reference type) rather than plain vars:+# this file also runs via & ([scriptblock]::Create(...)), where $script:+# scope modifiers leak outward, so plain-variable writes from inside+# functions would miss the scriptblock-level variable.+$SearchState = @{ Total = 0; Max = $SearchMax; FilesOnly = $SearchFilesOnly; Seen = @{} }+function Emit-SearchLines($Result) {+  foreach ($SearchLine in @($Result)) {+    if ($null -eq $SearchLine) { continue }+    if ($SearchState.Total -ge $SearchState.Max) { break }+    if ($SearchState.FilesOnly) {+      $SearchF = ([string]$SearchLine -split ':', 2)[0]+      if ($SearchState.Seen.ContainsKey($SearchF)) { continue }+      $SearchState.Seen[$SearchF] = $true+      Write-Output $SearchF+    }+    else {+      Write-Output $SearchLine+    }+    $SearchState.Total+++  }+}++if ($SearchMods.Count -gt 0) {+  foreach ($SearchMod in $SearchMods) {+    $SearchDirsList = @()+    if ($SearchPkgsSplit.Count -gt 0) {+      $SearchDirsList = @(Get-SearchPkgDirs $SearchMod $SearchPkgsSplit)+      if ($SearchDirsList.Count -eq 0) {+        [Console]::Error.WriteLine("warning: $SearchMod`: no $($SearchPkgsSplit -join '/') package under src/main/{java,kotlin}, skipped")+        continue+      }+    }+    else {+      if (Test-Path -LiteralPath (Join-Path $SearchRoot "$SearchMod/src")) {+        $SearchDirsList = @("$SearchMod/src")+      }+      else {+        $SearchDirsList = @($SearchMod)+      }+    }+    Write-Output "=== $SearchMod ==="+    Emit-SearchLines (Invoke-SearchDirs $SearchPattern $SearchDirsList)+    if ($SearchState.Total -ge $SearchMax) { break }+  }+}+else {+  if ($SearchPkgsSplit.Count -gt 0) {+    [Console]::Error.WriteLine('warning: no -m given: -p needs a module scope, package filter ignored (repo-wide search)')+  }+  Emit-SearchLines (Invoke-SearchDirs $SearchPattern @('.'))+}+[Console]::Error.WriteLine("--- $($SearchState.Total) match(es) ---")+exit 0