opencode-agent-harness 0.0.0-stage → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +217 -0
  2. package/LICENSE +21 -0
  3. package/README.md +636 -2
  4. package/bin/agent-harness.js +3182 -0
  5. package/contrib/global-plugins/README.md +49 -0
  6. package/contrib/global-plugins/harness-freshness.ts +355 -0
  7. package/package.json +86 -4
  8. package/templates/.agents/AGENTS.md +148 -0
  9. package/templates/.agents/features/INDEX.md +10 -0
  10. package/templates/.agents/handoffs/README.md +87 -0
  11. package/templates/.agents/memory/dev-loop.md +59 -0
  12. package/templates/.agents/memory/domain-map.md +29 -0
  13. package/templates/.agents/memory/environments.md +35 -0
  14. package/templates/.agents/memory/flow-map.md +23 -0
  15. package/templates/.agents/memory/history.md +7 -0
  16. package/templates/.agents/memory/locations.md +14 -0
  17. package/templates/.agents/memory/model-routing.md +261 -0
  18. package/templates/.agents/memory/orchestration.md +183 -0
  19. package/templates/.agents/memory/owned-files.md +19 -0
  20. package/templates/.agents/memory/product-principles.md +37 -0
  21. package/templates/.agents/memory/quality-parameters.md +37 -0
  22. package/templates/.agents/memory/stack-versions.md +35 -0
  23. package/templates/.agents/memory/test-design-parameters.md +36 -0
  24. package/templates/.agents/nightly.json +17 -0
  25. package/templates/.agents/qa-plans/README.md +70 -0
  26. package/templates/.agents/qa-runs/README.md +21 -0
  27. package/templates/.agents/reviews/README.md +47 -0
  28. package/templates/.agents/rules/00-operating.md +199 -0
  29. package/templates/.agents/skills/data-engineer/SKILL.md +31 -0
  30. package/templates/.agents/skills/devops-engineer/SKILL.md +50 -0
  31. package/templates/.agents/skills/diagnostics-expert/SKILL.md +44 -0
  32. package/templates/.agents/skills/docs/SKILL.md +140 -0
  33. package/templates/.agents/skills/features/SKILL.md +187 -0
  34. package/templates/.agents/skills/frontend-engineer/SKILL.md +81 -0
  35. package/templates/.agents/skills/handoff/SKILL.md +85 -0
  36. package/templates/.agents/skills/mobile-engineer/SKILL.md +101 -0
  37. package/templates/.agents/skills/planner/SKILL.md +112 -0
  38. package/templates/.agents/skills/product-manager/SKILL.md +115 -0
  39. package/templates/.agents/skills/qa-architect/SKILL.md +224 -0
  40. package/templates/.agents/skills/qa-runner/SKILL.md +64 -0
  41. package/templates/.agents/skills/security-engineer/SKILL.md +53 -0
  42. package/templates/.agents/skills/system-architect/SKILL.md +42 -0
  43. package/templates/.agents/skills/ui-designer/SKILL.md +71 -0
  44. package/templates/.github/workflows/ci.yml +148 -0
  45. package/templates/.github/workflows/deploy-uat.yml +95 -0
  46. package/templates/.github/workflows/nightly.yml +83 -0
  47. package/templates/.github/workflows/uat-health.yml +41 -0
  48. package/templates/.husky/pre-push +23 -0
  49. package/templates/.ignore +28 -0
  50. package/templates/.opencode/agents/data-engineer.md +37 -0
  51. package/templates/.opencode/agents/devops-engineer.md +37 -0
  52. package/templates/.opencode/agents/diagnostics-expert.md +37 -0
  53. package/templates/.opencode/agents/docs.md +37 -0
  54. package/templates/.opencode/agents/features.md +21 -0
  55. package/templates/.opencode/agents/frontend-engineer.md +37 -0
  56. package/templates/.opencode/agents/handoff.md +21 -0
  57. package/templates/.opencode/agents/mobile-engineer.md +37 -0
  58. package/templates/.opencode/agents/planner.md +34 -0
  59. package/templates/.opencode/agents/product-manager.md +29 -0
  60. package/templates/.opencode/agents/qa-architect.md +27 -0
  61. package/templates/.opencode/agents/qa-runner.md +17 -0
  62. package/templates/.opencode/agents/security-engineer.md +37 -0
  63. package/templates/.opencode/agents/system-architect.md +37 -0
  64. package/templates/.opencode/agents/ui-designer.md +37 -0
  65. package/templates/.opencode/commands/board.md +15 -0
  66. package/templates/.opencode/commands/checkpoint.md +25 -0
  67. package/templates/.opencode/commands/feature.md +56 -0
  68. package/templates/.opencode/commands/finish.md +36 -0
  69. package/templates/.opencode/commands/next.md +49 -0
  70. package/templates/.opencode/commands/report.md +55 -0
  71. package/templates/.opencode/commands/resume.md +39 -0
  72. package/templates/.opencode/commands/switch-model.md +34 -0
  73. package/templates/.opencode/commands/tidy.md +49 -0
  74. package/templates/.opencode/plugins/backlog-notify.ts +57 -0
  75. package/templates/.opencode/plugins/backlog.ts +272 -0
  76. package/templates/.opencode/plugins/checkpoint.ts +160 -0
  77. package/templates/.opencode/plugins/context-guard.ts +1164 -0
  78. package/templates/.opencode/plugins/diff.ts +85 -0
  79. package/templates/.opencode/plugins/gates.ts +71 -0
  80. package/templates/.opencode/plugins/job-notify.ts +241 -0
  81. package/templates/.opencode/plugins/orient.ts +67 -0
  82. package/templates/.opencode/plugins/session.ts +89 -0
  83. package/templates/.opencode/plugins/wait.ts +101 -0
  84. package/templates/.opencode/plugins/where.ts +70 -0
  85. package/templates/.opencode/skills/bounded-explore/SKILL.md +38 -0
  86. package/templates/.opencode/skills/dev-loop/SKILL.md +87 -0
  87. package/templates/.vercelignore +16 -0
  88. package/templates/AGENTS.md +27 -0
  89. package/templates/BACKLOG.md +95 -0
  90. package/templates/docs/ci-cd-pipeline.md +81 -0
  91. package/templates/docs/gates.md +128 -0
  92. package/templates/docs/mcp-integrations.md +97 -0
  93. package/templates/docs/mobile-testing.md +555 -0
  94. package/templates/docs/nightly-testing.md +106 -0
  95. package/templates/docs/wsl-optimizations.md +290 -0
  96. package/templates/opencode.json +188 -0
  97. package/templates/scripts/agent-report.js +541 -0
  98. package/templates/scripts/agent-search.sh +117 -0
  99. package/templates/scripts/backlog.js +1924 -0
  100. package/templates/scripts/board-service.sh +214 -0
  101. package/templates/scripts/checkpoint.js +290 -0
  102. package/templates/scripts/finalize.js +416 -0
  103. package/templates/scripts/nightly.js +913 -0
  104. package/templates/scripts/orient.js +514 -0
  105. package/templates/scripts/qa/board-client.js +323 -0
  106. package/templates/scripts/qa/board-lib.js +96 -0
  107. package/templates/scripts/qa/board-sync.js +499 -0
  108. package/templates/scripts/qa/capacity-lib.js +916 -0
  109. package/templates/scripts/qa/check-backlog.js +434 -0
  110. package/templates/scripts/qa/check-capacity.js +85 -0
  111. package/templates/scripts/qa/check-ci-policy.js +164 -0
  112. package/templates/scripts/qa/check-concurrency.js +344 -0
  113. package/templates/scripts/qa/check-dispatch-config.js +296 -0
  114. package/templates/scripts/qa/check-docs.js +288 -0
  115. package/templates/scripts/qa/check-integrate.js +98 -0
  116. package/templates/scripts/qa/check-linger.js +160 -0
  117. package/templates/scripts/qa/check-prefix-stability.js +187 -0
  118. package/templates/scripts/qa/check-product.js +177 -0
  119. package/templates/scripts/qa/check-qa-plan.js +378 -0
  120. package/templates/scripts/qa/check-qa-scripts.js +85 -0
  121. package/templates/scripts/qa/check-quality.js +249 -0
  122. package/templates/scripts/qa/check-test-wiring.js +253 -0
  123. package/templates/scripts/qa/check-worktrees.js +93 -0
  124. package/templates/scripts/qa/ci-triage.js +346 -0
  125. package/templates/scripts/qa/ci-usage-lib.js +185 -0
  126. package/templates/scripts/qa/ci-wait-lib.js +294 -0
  127. package/templates/scripts/qa/command-classifier.js +552 -0
  128. package/templates/scripts/qa/context-guard-core.js +1618 -0
  129. package/templates/scripts/qa/diff.js +174 -0
  130. package/templates/scripts/qa/feature-scaffold.js +224 -0
  131. package/templates/scripts/qa/fixtures/backlog.md +104 -0
  132. package/templates/scripts/qa/governance.js +174 -0
  133. package/templates/scripts/qa/hash-file.js +32 -0
  134. package/templates/scripts/qa/lease-lib.js +263 -0
  135. package/templates/scripts/qa/merge-backlog.js +324 -0
  136. package/templates/scripts/qa/mobile-e2e/analyze-timings.js +300 -0
  137. package/templates/scripts/qa/mobile-e2e/apk-cache.js +420 -0
  138. package/templates/scripts/qa/mobile-e2e/backend-build-cache.js +203 -0
  139. package/templates/scripts/qa/mobile-e2e/boot-emulator.sh +432 -0
  140. package/templates/scripts/qa/mobile-e2e/build-apk.sh +210 -0
  141. package/templates/scripts/qa/mobile-e2e/check-flows.js +568 -0
  142. package/templates/scripts/qa/mobile-e2e/config.yaml +18 -0
  143. package/templates/scripts/qa/mobile-e2e/device-down.sh +88 -0
  144. package/templates/scripts/qa/mobile-e2e/device-up.sh +258 -0
  145. package/templates/scripts/qa/mobile-e2e/ios-simulator-down.sh +72 -0
  146. package/templates/scripts/qa/mobile-e2e/ios-simulator-up.sh +153 -0
  147. package/templates/scripts/qa/mobile-e2e/job-events.js +181 -0
  148. package/templates/scripts/qa/mobile-e2e/prewarm.sh +56 -0
  149. package/templates/scripts/qa/mobile-e2e/run-detached.sh +222 -0
  150. package/templates/scripts/qa/mobile-e2e/run-maestro.js +1543 -0
  151. package/templates/scripts/qa/mobile-e2e/ui-dump.js +327 -0
  152. package/templates/scripts/qa/models.allowlist.txt +32 -0
  153. package/templates/scripts/qa/provider-stats.js +878 -0
  154. package/templates/scripts/qa/run-clean.js +83 -0
  155. package/templates/scripts/qa/run-gates.js +213 -0
  156. package/templates/scripts/qa/run-loop.js +220 -0
  157. package/templates/scripts/qa/session-recon.js +512 -0
  158. package/templates/scripts/qa/store-lib.js +324 -0
  159. package/templates/scripts/qa/tool-lib.js +134 -0
  160. package/templates/scripts/qa/where.js +214 -0
  161. package/templates/scripts/qa/worktree-hygiene.js +217 -0
  162. package/templates/scripts/qa/wslconfig-merge.js +157 -0
  163. package/templates/scripts/serve.js +1328 -0
  164. package/templates/scripts/setup-nightly.sh +185 -0
  165. package/templates/scripts/setup-tmpfs.sh +374 -0
  166. package/templates/scripts/ship.js +586 -0
  167. package/templates/scripts/switch-reasoning-model.ps1 +101 -0
  168. package/templates/scripts/switch-reasoning-model.sh +104 -0
  169. package/templates/scripts/wait-for.js +342 -0
  170. package/templates/scripts/wsl-gpu.sh +180 -0
  171. package/templates/scripts/wsl-tune.sh +319 -0
@@ -0,0 +1,432 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # mobile E2E — bring up the Android device tier: the adb server, the emulator,
4
+ # and a bounded readiness gate. Harness-owned; project values come from the
5
+ # sibling `local.json`.
6
+ #
7
+ # Why a script: the adb server and the emulator are long-lived processes, so they
8
+ # must never run from the agent's own shell (see docs/mobile-testing.md). adb is
9
+ # the classic trap — `adb start-server` forks a daemon that is reaped with the
10
+ # tool's process group, so the client hangs forever with no output. Here BOTH the
11
+ # adb server and the emulator are started detached through `serve.js`, which
12
+ # returns as soon as the readiness target is up, and every later adb call is
13
+ # wrapped in `timeout` so a wedged adb fails fast instead of hanging the tool.
14
+ # Re-running is safe: an already-ready adb server / booted emulator is reused.
15
+ #
16
+ # Right-sizing (the device tier is the slowest, heaviest part of a run):
17
+ # * CPU cores are derived from the host (`nproc`) and the AVD's own
18
+ # `hw.cpu.ncore`, capped so the agent, dev server, and Windows host keep
19
+ # room. A fixed 2 cores on an 8-vCPU box made qemu the bottleneck.
20
+ # * Guest RAM comes from the capacity envelope (`emulator_ram_mb`, the single
21
+ # owner of the number), not a second hardcoded literal.
22
+ # * The emulator's cgroup cap is set EXPLICITLY (`--mem-max` = guest RAM +
23
+ # 2048 MB). serve.js sums group member CAPS, so without an explicit cap the
24
+ # EMULATOR (started after the dev server) would be tightened to the group
25
+ # remainder — which, with the dev server already holding the full default,
26
+ # equals guest RAM and pins qemu against its cap (constant reclaim). The
27
+ # +2048 MB is the documented `emulator_ram_mb + ~2 GB` headroom for qemu's
28
+ # host-side overhead and page cache.
29
+ # * The GPU backend is auto-detected: `host` only when a real GPU/renderer is
30
+ # present, else `swiftshader_indirect` (the safe WSL2 fallback). `-gpu host`
31
+ # on a box whose only renderer is llvmpipe is software GL anyway.
32
+ # On WSL2 the detection probes with Mesa's `d3d12` driver (the Windows GPU
33
+ # behind /dev/dxg) and, when accelerated, launches the emulator with the
34
+ # matching GL env — otherwise Mesa silently picks llvmpipe even with a GPU
35
+ # (F-296). Enable it once with `bash scripts/wsl-gpu.sh apply`.
36
+ # * On the WSL d3d12 path `-gpu host` is launched with `-feature -Vulkan`
37
+ # (the gfxstream Vulkan backend segfaults qemu; GLES-over-host is stable).
38
+ # * If an AUTO-selected backend still fails to boot, the tier retries once
39
+ # with `swiftshader_indirect`, unless MOBILE_E2E_GPU pins one explicitly.
40
+ # MOBILE_E2E_CORES / MOBILE_E2E_MEMORY / MOBILE_E2E_GPU override each.
41
+ #
42
+ # Tunables (env; `local.json` supplies `avd`):
43
+ # MOBILE_E2E_AVD AVD name (default: local.json `avd`)
44
+ # MOBILE_E2E_AVD_CONFIG AVD config.ini path (default: ~/.android/avd/<avd>.avd/config.ini)
45
+ # MOBILE_E2E_GPU gpu backend (default: auto-detected)
46
+ # MOBILE_E2E_CORES vCPU cores (default: host/AVD-derived)
47
+ # MOBILE_E2E_MEMORY RAM in MB (default: envelope emulator_ram_mb)
48
+ # MOBILE_E2E_MEM_MAX cgroup cap in MB (default: MOBILE_E2E_MEMORY + 2048)
49
+ # MOBILE_E2E_TIER_GROUP heavy-tier group (default: mobile)
50
+ # MOBILE_E2E_SNAPSHOT quickboot snapshot (default 1; `0` = cold boot)
51
+ # MOBILE_E2E_SNAPSHOT_NAME snapshot name (default agent-e2e)
52
+ # Quickboot forces ANDROID_EMU_FORCE_QUICKBOOT_FILE_BACKED=1 (the emulator
53
+ # disables file-backed snapshots by default; this AVD needs them to save/load
54
+ # at all). A snapshot without `ram.bin` is discarded as a failed save.
55
+ # MOBILE_E2E_RESOLUTION logical display size (WxH; default device 1080x2400)
56
+ # MOBILE_E2E_DENSITY logical display dpi (default device 420)
57
+ # Applied post-boot with `wm size`/`wm density` — a latency lever, not a
58
+ # layout change: scale size and density together (720x1600 @ 280 keeps the
59
+ # same dp geometry as 1080x2400 @ 420) so selectors are unaffected while the
60
+ # emulator moves ~2.3x fewer pixels per command. Env wins; otherwise the
61
+ # project-owned `local.json` `resolution`/`density` keys supply them. Both
62
+ # unset = the AVD's own.
63
+ # ANDROID_HOME Android SDK root (default ~/android-sdk)
64
+ #
65
+ # Boot speed: a quickboot snapshot turns the ~40-60 s cold boot into a few
66
+ # seconds. It is stateful, so a snapshot that fails the bounded boot gate is
67
+ # retried once WITHOUT a snapshot (cold boot) before the tier is declared dead.
68
+ #
69
+ # Modes:
70
+ # boot-emulator.sh boot the tier
71
+ # boot-emulator.sh --print-profile print the resolved profile as JSON and exit
72
+ set -euo pipefail
73
+
74
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
75
+ LOCAL_CONFIG="$ROOT/scripts/qa/mobile-e2e/local.json"
76
+ SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/android-sdk}}"
77
+ EMULATOR="$SDK/emulator/emulator"
78
+ ADB="$SDK/platform-tools/adb"
79
+ TIER_GROUP="${MOBILE_E2E_TIER_GROUP:-mobile}"
80
+
81
+ PRINT_PROFILE=0
82
+ for arg in "$@"; do
83
+ case "$arg" in
84
+ --print-profile) PRINT_PROFILE=1 ;;
85
+ -h|--help) PRINT_PROFILE=2 ;;
86
+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
87
+ esac
88
+ done
89
+
90
+ # Platform selection: env MOBILE_E2E_PLATFORM > local.json `platform` > android.
91
+ # This script owns the Android bring-up only; on iOS it delegates to the sibling
92
+ # ios-simulator-up.sh (no Android/adb/simctl logic is attempted inline here).
93
+ resolve_platform() {
94
+ local p="${MOBILE_E2E_PLATFORM:-}"
95
+ [ -z "$p" ] && [ -f "$LOCAL_CONFIG" ] && p="$(node -e "try{process.stdout.write(String(require('$LOCAL_CONFIG').platform||''))}catch(e){}" 2>/dev/null || true)"
96
+ case "$p" in ios|iOS|IOS) echo ios ;; *) echo android ;; esac
97
+ }
98
+ PLATFORM="$(resolve_platform)"
99
+
100
+ # `-h/--help` still prints this script's Android runbook (and exits) below; every
101
+ # other invocation on the iOS platform delegates.
102
+ if [ "$PLATFORM" = "ios" ] && [ "$PRINT_PROFILE" != "2" ]; then
103
+ echo "platform=ios — delegating to ios-simulator-up.sh (boot-emulator.sh owns the Android bring-up)"
104
+ exec bash "$(dirname "${BASH_SOURCE[0]}")/ios-simulator-up.sh"
105
+ fi
106
+
107
+ # AVD: env override, else local.json `avd`, else fail with the available list.
108
+ AVD="${MOBILE_E2E_AVD:-}"
109
+ if [ -z "$AVD" ] && [ -f "$LOCAL_CONFIG" ]; then
110
+ AVD="$(node -e "try{process.stdout.write(String(require('$LOCAL_CONFIG').avd||''))}catch(e){}" 2>/dev/null || true)"
111
+ fi
112
+
113
+ # --- Profile resolution (pure; never starts anything) ------------------------
114
+ avd_config() {
115
+ if [ -n "${MOBILE_E2E_AVD_CONFIG:-}" ]; then
116
+ echo "$MOBILE_E2E_AVD_CONFIG"
117
+ elif [ -n "$AVD" ]; then
118
+ echo "$HOME/.android/avd/$AVD.avd/config.ini"
119
+ else
120
+ echo ""
121
+ fi
122
+ }
123
+
124
+ avd_ncore() {
125
+ local cfg n
126
+ cfg="$(avd_config)"
127
+ n=""
128
+ [ -n "$cfg" ] && [ -f "$cfg" ] && n="$(grep -iE '^hw\.cpu\.ncore' "$cfg" 2>/dev/null | head -1 | cut -d= -f2 | tr -d ' ')"
129
+ case "$n" in ''|*[!0-9]*) n=4 ;; esac
130
+ echo "$n"
131
+ }
132
+
133
+ resolve_cores() {
134
+ local host reserve avail avd n
135
+ host="$(nproc 2>/dev/null || echo 2)"
136
+ case "$host" in ''|*[!0-9]*) host=2 ;; esac
137
+ avd="$(avd_ncore)"
138
+ reserve=$(( host / 4 )); [ "$reserve" -lt 2 ] && reserve=2
139
+ avail=$(( host - reserve )); [ "$avail" -lt 2 ] && avail=2
140
+ if [ "$avd" -lt "$avail" ]; then n="$avd"; else n="$avail"; fi
141
+ [ "$n" -lt 2 ] && n=2
142
+ echo "$n"
143
+ }
144
+
145
+ resolve_memory() {
146
+ local m
147
+ m="$(node -e "try{process.stdout.write(String(require('$ROOT/scripts/qa/capacity-lib.js').readEnvelope('$ROOT').emulatorRamMb||''))}catch(e){}" 2>/dev/null || true)"
148
+ case "$m" in ''|*[!0-9]*) m=2048 ;; esac
149
+ echo "$m"
150
+ }
151
+
152
+ # GL renderer as the emulator's `-gpu host` would actually see it. On WSL the
153
+ # Windows GPU is behind /dev/dxg and Mesa defaults to llvmpipe, so the probe
154
+ # forces the d3d12 driver (exactly what `wsl-gpu.sh apply` verifies); without
155
+ # that, a real GPU reads as software and the emulator never uses it (F-296).
156
+ is_wsl_gpu() { [ -e /dev/dxg ]; }
157
+
158
+ gl_renderer() {
159
+ command -v glxinfo >/dev/null 2>&1 || return 0
160
+ if is_wsl_gpu; then
161
+ MESA_LOADER_DRIVER_OVERRIDE=d3d12 GALLIUM_DRIVER=d3d12 glxinfo -B 2>/dev/null \
162
+ | grep -i 'OpenGL renderer string' | head -1 | sed 's/.*: //' || true
163
+ else
164
+ glxinfo -B 2>/dev/null | grep -i 'OpenGL renderer string' | head -1 | sed 's/.*: //' || true
165
+ fi
166
+ }
167
+
168
+ detect_gpu() {
169
+ # An NVIDIA driver answers directly (no GL probe needed).
170
+ if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1; then echo host; return; fi
171
+ # Otherwise trust the effective renderer: a software renderer means `host` GL
172
+ # is llvmpipe and buys nothing over swiftshader.
173
+ local r
174
+ r="$(gl_renderer | tr 'A-Z' 'a-z')"
175
+ case "$r" in
176
+ *llvmpipe*|*softpipe*|*swrast*|*"software rasterizer"*) echo swiftshader_indirect; return ;;
177
+ "") echo swiftshader_indirect; return ;;
178
+ esac
179
+ echo host
180
+ }
181
+
182
+ HOST_CPUS="$(nproc 2>/dev/null || echo 2)"
183
+ AVD_CORES="$(avd_ncore)"
184
+ CORES="${MOBILE_E2E_CORES:-$(resolve_cores)}"
185
+ MEMORY="${MOBILE_E2E_MEMORY:-$(resolve_memory)}"
186
+ GPU="${MOBILE_E2E_GPU:-$(detect_gpu)}"
187
+ case "$CORES" in ''|*[!0-9]*) CORES=2 ;; esac
188
+ case "$MEMORY" in ''|*[!0-9]*) MEMORY=2048 ;; esac
189
+ # Explicit cgroup cap so serve.js's group budget does not tighten the emulator
190
+ # (started after the dev server) down to the group remainder = guest RAM. Guest
191
+ # RAM + 2048 MB covers qemu's host-side overhead + page cache (docs: keep the
192
+ # cap >= emulator_ram_mb + ~2 GB).
193
+ MEM_CAP="${MOBILE_E2E_MEM_MAX:-$((MEMORY + 2048))}"
194
+ case "$MEM_CAP" in ''|*[!0-9]*) MEM_CAP=$((MEMORY + 2048)) ;; esac
195
+
196
+ # Optional display override (`wm size`/`wm density` after boot). Validated so a
197
+ # typo cannot smuggle an arbitrary token into an adb shell command; an invalid
198
+ # value is ignored with a warning rather than aborting the boot. Env wins; else
199
+ # the project-owned `local.json` `resolution`/`density` keys are the defaults.
200
+ RESOLUTION="${MOBILE_E2E_RESOLUTION:-}"
201
+ DENSITY="${MOBILE_E2E_DENSITY:-}"
202
+ if [ -f "$LOCAL_CONFIG" ]; then
203
+ [ -z "$RESOLUTION" ] && RESOLUTION="$(node -e "try{process.stdout.write(String(require('$LOCAL_CONFIG').resolution||''))}catch(e){}" 2>/dev/null || true)"
204
+ [ -z "$DENSITY" ] && DENSITY="$(node -e "try{process.stdout.write(String(require('$LOCAL_CONFIG').density||''))}catch(e){}" 2>/dev/null || true)"
205
+ fi
206
+ if [ -n "$RESOLUTION" ] && ! [[ "$RESOLUTION" =~ ^[0-9]+x[0-9]+$ ]]; then
207
+ echo "! ignoring invalid MOBILE_E2E_RESOLUTION='$RESOLUTION' (want WxH)" >&2
208
+ RESOLUTION=""
209
+ fi
210
+ if [ -n "$DENSITY" ] && ! [[ "$DENSITY" =~ ^[0-9]+$ ]]; then
211
+ echo "! ignoring invalid MOBILE_E2E_DENSITY='$DENSITY' (want an integer)" >&2
212
+ DENSITY=""
213
+ fi
214
+
215
+ # When the backend is a real GPU reached over WSL's d3d12 path, the emulator
216
+ # inherits the same driver selection (serve.js runs the command through a shell
217
+ # and forwards the caller's env) — otherwise `-gpu host` would still use llvmpipe.
218
+ GPU_ENV=""
219
+ GPU_EXTRA=""
220
+ if [ "$GPU" = "host" ] && is_wsl_gpu; then
221
+ GPU_ENV="MESA_LOADER_DRIVER_OVERRIDE=d3d12 GALLIUM_DRIVER=d3d12"
222
+ # Disable the emulator's Vulkan feature on the WSL d3d12 path: its gfxstream
223
+ # Vulkan backend segfaults qemu mid-boot (the "Segmentation fault (core
224
+ # dumped)" that made every F-296 run fall back to the software rasterizer),
225
+ # while GLES-over-host on d3d12 is stable. Verified: `-gpu host -feature
226
+ # -Vulkan` boots to `D3D12 (Intel(R) Graphics)`; without `-feature -Vulkan` it
227
+ # crashes. Native (non-WSL) host GPUs keep Vulkan.
228
+ GPU_EXTRA="-feature -Vulkan"
229
+ fi
230
+
231
+ # WSL GPU passthrough available but GL resolved to software: the emulator is
232
+ # about to render at a fraction of the speed for no reason. Name the fix.
233
+ if [ "$GPU" != "host" ] && is_wsl_gpu && [ -z "${MOBILE_E2E_GPU:-}" ]; then
234
+ echo "! WSL GPU passthrough is present but GL is software (llvmpipe)." >&2
235
+ echo " Enable D3D12 acceleration once: bash scripts/wsl-gpu.sh apply" >&2
236
+ fi
237
+
238
+ if [ "$PRINT_PROFILE" = "2" ]; then
239
+ sed -n '2,/^set -euo pipefail$/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'
240
+ exit 0
241
+ fi
242
+
243
+ if [ "$PRINT_PROFILE" = "1" ]; then
244
+ node -e "process.stdout.write(JSON.stringify({avd:process.argv[1]||null,hostCpus:Number(process.argv[2]),avdCores:Number(process.argv[3]),cores:Number(process.argv[4]),memory:Number(process.argv[5]),memMax:Number(process.argv[6]),gpu:process.argv[7],gpuEnv:process.argv[8]||null,gpuExtra:process.argv[9]||null,tierGroup:process.argv[10],resolution:process.argv[11]||null,density:Number(process.argv[12])||null},null,2)+'\n')" \
245
+ "$AVD" "$HOST_CPUS" "$AVD_CORES" "$CORES" "$MEMORY" "$MEM_CAP" "$GPU" "$GPU_ENV" "$GPU_EXTRA" "$TIER_GROUP" "$RESOLUTION" "$DENSITY"
246
+ exit 0
247
+ fi
248
+
249
+ if [ -z "$AVD" ]; then
250
+ echo "FAIL — no AVD set. Set MOBILE_E2E_AVD or add \"avd\": \"<name>\" to scripts/qa/mobile-e2e/local.json." >&2
251
+ [ -x "$EMULATOR" ] && "$EMULATOR" -list-avds >&2 || true
252
+ exit 1
253
+ fi
254
+
255
+ if [ ! -x "$EMULATOR" ]; then
256
+ echo "FAIL — emulator binary not found at $EMULATOR (set ANDROID_HOME)." >&2
257
+ exit 1
258
+ fi
259
+ if [ ! -x "$ADB" ]; then
260
+ echo "FAIL — adb binary not found at $ADB (set ANDROID_HOME)." >&2
261
+ exit 1
262
+ fi
263
+
264
+ cd "$ROOT"
265
+
266
+ echo "device profile: avd=$AVD cores=$CORES/$HOST_CPUS memory=${MEMORY}MB gpu=$GPU${GPU_ENV:+ ($GPU_ENV)} (avd declares ${AVD_CORES} cores)"
267
+ [ -n "$RESOLUTION" ] && echo "display override: size=$RESOLUTION${DENSITY:+ density=$DENSITY}"
268
+ if [ "$CORES" -gt "$AVD_CORES" ]; then
269
+ echo " ! cores ($CORES) exceed the AVD's hw.cpu.ncore ($AVD_CORES); the guest may cap them." >&2
270
+ fi
271
+
272
+ # 0. Ensure a writable XDG_RUNTIME_DIR. The emulator aborts hard ("Aborted (core
273
+ # dumped)") when XDG_RUNTIME_DIR is unset or points at a missing/unwritable
274
+ # directory — exactly the case on a systemd-less WSL where /run/user/<uid> is
275
+ # absent, which cost a whole failed bring-up (F-296). Resolve a usable one and
276
+ # export it; serve.js forwards the caller's env to the emulator command.
277
+ if [ -z "${XDG_RUNTIME_DIR:-}" ] || [ ! -d "${XDG_RUNTIME_DIR:-}" ] || [ ! -w "${XDG_RUNTIME_DIR:-}" ]; then
278
+ XDG_RUNTIME_DIR="${TMPDIR:-/tmp}/agent-emulator-runtime-$(id -u)"
279
+ mkdir -p "$XDG_RUNTIME_DIR" && chmod 700 "$XDG_RUNTIME_DIR"
280
+ export XDG_RUNTIME_DIR
281
+ echo "XDG_RUNTIME_DIR was unset/unwritable; using $XDG_RUNTIME_DIR (the emulator aborts without a writable runtime dir)"
282
+ fi
283
+
284
+ # 1. Reap dead `.serve/` records so a stale adb-server/emulator entry from a
285
+ # previous session cannot misreport the machine.
286
+ node scripts/serve.js prune >/dev/null 2>&1 || true
287
+
288
+ # 2. Ensure the adb SERVER is up, detached, BEFORE any adb client call. A bare
289
+ # `adb devices`/`start-server` hangs when the server is down (the forked
290
+ # daemon is tied to this tool's process group), so it is launched through
291
+ # serve.js like any other long-lived process. Idempotent: if 5037 already
292
+ # answers, this is a no-op.
293
+ if ! timeout 5 "$ADB" devices >/dev/null 2>&1; then
294
+ echo "adb server not ready — starting it detached (serve.js, port 5037)"
295
+ node scripts/serve.js start \
296
+ --cmd "$ADB -a nodaemon server" \
297
+ --name adb-server --port 5037 --timeout 30000
298
+ fi
299
+ if ! timeout 10 "$ADB" devices >/dev/null 2>&1; then
300
+ echo "FAIL — adb server did not come up on port 5037." >&2
301
+ echo " Inspect: .serve/adb-server.err.log" >&2
302
+ exit 1
303
+ fi
304
+
305
+ # 3. Start (or reuse) the emulator, detached, ready when its adb port answers.
306
+ # `--group` lets the emulator and the dev server share one machine-wide
307
+ # mobile-tier budget instead of fighting the single-heavy-tier lock.
308
+ SNAPSHOT="${MOBILE_E2E_SNAPSHOT:-1}"
309
+ SNAPSHOT_NAME="${MOBILE_E2E_SNAPSHOT_NAME:-agent-e2e}"
310
+
311
+ # Quickboot on this AVD needs FILE-BACKED snapshots. The emulator ships with
312
+ # `Feature QuickbootFileBacked` OFF ("disabled due to stability issues") and the
313
+ # AVD keeps its data in a qcow2 overlay, so a snapshot save/load silently fails
314
+ # (the boot log: `Device 'cache' does not have the requested snapshot`) and every
315
+ # bring-up pays a full cold boot. Forcing it on is what makes the warm boot
316
+ # actually work on WSL: measured 9 s wall-clock / ~4 s to restore the snapshot
317
+ # vs ~24-31 s cold (F-30x device-tier startup). It is stateful; a failed boot
318
+ # still retries cold below. Opt out entirely with MOBILE_E2E_SNAPSHOT=0.
319
+ if [ "$SNAPSHOT" != "0" ]; then
320
+ export ANDROID_EMU_FORCE_QUICKBOOT_FILE_BACKED="${ANDROID_EMU_FORCE_QUICKBOOT_FILE_BACKED:-1}"
321
+ fi
322
+
323
+ # An incomplete snapshot save leaves a stray tiny `snapshot.pb` and no `ram.bin`;
324
+ # loading it fails and the emulator cold-boots anyway. Discard it up front so the
325
+ # next boot starts clean and re-saves, instead of logging a failed load every run.
326
+ SNAP_DIR="$HOME/.android/avd/${AVD}.avd/snapshots/${SNAPSHOT_NAME}"
327
+ if [ "$SNAPSHOT" != "0" ] && [ -d "$SNAP_DIR" ] && [ ! -f "$SNAP_DIR/ram.bin" ]; then
328
+ echo "quickboot: discarding an incomplete snapshot '$SNAPSHOT_NAME' (no ram.bin) — cold-booting once to re-save"
329
+ rm -rf "$SNAP_DIR" 2>/dev/null || true
330
+ fi
331
+
332
+ start_emulator() {
333
+ local gpu="$1" gpu_env="$2" gpu_extra="$3" snap="$4" snaparg
334
+ if [ "$snap" = "on" ]; then snaparg="-snapshot $SNAPSHOT_NAME"; else snaparg="-no-snapshot"; fi
335
+ node scripts/serve.js start \
336
+ --cmd "$gpu_env $EMULATOR -avd $AVD -no-window -no-audio -no-boot-anim $snaparg -gpu $gpu $gpu_extra -cores $CORES -memory $MEMORY" \
337
+ --name emulator --port 5554 --group "$TIER_GROUP" --mem-max "${MEM_CAP}M" --timeout 180000
338
+ }
339
+
340
+ # 4. Bounded readiness gate — never sleep-and-pray, and never let a wedged adb
341
+ # hang the tool. `adb wait-for-device` returns once a device is attached; then
342
+ # poll `sys.boot_completed` (bounded) until Android is fully up. Returns
343
+ # non-zero when the device never finishes booting (a dead/segfaulted qemu).
344
+ wait_boot() {
345
+ echo "waiting for the device to finish booting (bounded)…"
346
+ timeout 90 "$ADB" wait-for-device
347
+ boot=""
348
+ for _ in $(seq 1 30); do
349
+ boot="$(timeout 10 "$ADB" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r' || true)"
350
+ [ "$boot" = "1" ] && break
351
+ sleep 2
352
+ done
353
+ [ "$boot" = "1" ]
354
+ }
355
+
356
+ log_emulator_failure() {
357
+ echo " adb devices (bounded):" >&2
358
+ timeout 10 "$ADB" devices >&2 || true
359
+ if [ -f ".serve/emulator.err.log" ]; then
360
+ echo " .serve/emulator.err.log (tail):" >&2
361
+ tail -8 .serve/emulator.err.log >&2 || true
362
+ fi
363
+ }
364
+
365
+ restart_emulator() {
366
+ node scripts/serve.js stop --name emulator >/dev/null 2>&1 || true
367
+ node scripts/serve.js prune >/dev/null 2>&1 || true
368
+ }
369
+
370
+ # Optional post-boot display override. `wm size`/`wm density` change the Android
371
+ # logical display (SurfaceFlinger) without touching the AVD; applied after every
372
+ # boot so a quickboot restore cannot silently revert it. Scale size and density
373
+ # together to keep dp geometry (and therefore selectors) identical.
374
+ apply_display() {
375
+ [ -z "$RESOLUTION" ] && [ -z "$DENSITY" ] && return 0
376
+ if [ -n "$RESOLUTION" ]; then
377
+ timeout 20 "$ADB" shell wm size "$RESOLUTION" >/dev/null 2>&1 \
378
+ || echo " ! wm size $RESOLUTION failed (display unchanged)" >&2
379
+ fi
380
+ if [ -n "$DENSITY" ]; then
381
+ timeout 20 "$ADB" shell wm density "$DENSITY" >/dev/null 2>&1 \
382
+ || echo " ! wm density $DENSITY failed (display unchanged)" >&2
383
+ fi
384
+ echo "display applied: size=${RESOLUTION:-device} density=${DENSITY:-device}"
385
+ }
386
+
387
+ # One boot attempt: start with the given flags, hold the bounded boot gate, then
388
+ # apply the optional display override.
389
+ try_boot() {
390
+ start_emulator "$1" "$2" "$3" "$4"
391
+ if ! wait_boot; then return 1; fi
392
+ apply_display
393
+ }
394
+
395
+ WANT_SNAP="on"
396
+ [ "$SNAPSHOT" = "0" ] && WANT_SNAP="off"
397
+
398
+ BOOTED=0
399
+ if try_boot "$GPU" "$GPU_ENV" "$GPU_EXTRA" "$WANT_SNAP"; then
400
+ BOOTED=1
401
+ else
402
+ log_emulator_failure
403
+ # A quickboot snapshot can go stale/corrupt (or the WSL d3d12 backend can
404
+ # segfault restoring it). Retry once cold before blaming the GPU.
405
+ if [ "$WANT_SNAP" = "on" ]; then
406
+ echo " snapshot boot failed; retrying once WITHOUT a snapshot (cold boot)…" >&2
407
+ restart_emulator
408
+ if try_boot "$GPU" "$GPU_ENV" "$GPU_EXTRA" "off"; then BOOTED=1; fi
409
+ fi
410
+ fi
411
+
412
+ # A healthy emulator uses a GPU backend that actually boots. If it still has not,
413
+ # and the user did not pin MOBILE_E2E_GPU, fall back ONCE to the software
414
+ # rasterizer: the 2026-09-30 F-296 case was the auto-selected WSL `host`+d3d12
415
+ # path segfaulting qemu, and the run only proceeded after a manual
416
+ # `MOBILE_E2E_GPU=swiftshader_indirect`. Bake that recovery in.
417
+ if [ "$BOOTED" != "1" ] && [ -z "${MOBILE_E2E_GPU:-}" ] && [ "$GPU" != "swiftshader_indirect" ]; then
418
+ echo " auto-selected gpu=$GPU crashed; retrying once with the software rasterizer (gpu=swiftshader_indirect)…" >&2
419
+ restart_emulator
420
+ GPU="swiftshader_indirect"
421
+ GPU_ENV=""
422
+ GPU_EXTRA=""
423
+ if try_boot "$GPU" "$GPU_ENV" "$GPU_EXTRA" "off"; then BOOTED=1; fi
424
+ fi
425
+
426
+ if [ "$BOOTED" != "1" ]; then
427
+ echo "FAIL — emulator did not finish booting (sys.boot_completed != 1)." >&2
428
+ log_emulator_failure
429
+ exit 1
430
+ fi
431
+ echo "boot ok"
432
+ node scripts/serve.js list
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # mobile E2E — build the release APK the device run installs, CAPPED.
4
+ #
5
+ # Why this exists: the Android release build is a Gradle daemon + Kotlin daemon
6
+ # + R8/D8 job that can take several GB. On 2026-09-30 it ran inline as
7
+ # `bash .../build-dev-apk.sh` — no `serve.js`, no cgroup cap, no envelope
8
+ # preflight — while the emulator and the dev server were already up; the three
9
+ # together filled the 10 GB WSL VM, thrashed swap, and starved the host<->VM
10
+ # relay so every terminal froze at once. This wrapper runs the one-shot build
11
+ # through `serve.js run`, which puts it in a transient systemd scope with a
12
+ # `MemoryMax` (default 3 GB, `MOBILE_E2E_APK_MEM_MAX` overrides) so a runaway is
13
+ # OOM-killed inside its own cgroup instead of freezing the box, and it right-sizes
14
+ # Gradle (single worker, no daemon, one ABI, small heap) so the build fits.
15
+ #
16
+ # The app must be a RELEASE build with its JS bundle embedded: a debug / Metro
17
+ # dev-client build is the F-288 `clearState` blocker (`clearState` wipes the
18
+ # dev-server URL). The bundle also bakes the dev backend URL, and the generated
19
+ # Android manifest must allow cleartext HTTP to `10.0.2.2:3000`.
20
+ #
21
+ # Order is always: prebuild (only when the android project is absent) -> PATCH
22
+ # cleartext -> assemble. `expo prebuild` re-writes AndroidManifest.xml and DROPS
23
+ # `usesCleartextTraffic`, so we never prebuild over an existing project.
24
+ # cleartext is NEVER set in `mobile/app.json` — production would inherit it; it
25
+ # is patched into the generated (gitignored) manifest only.
26
+ #
27
+ # Caching (apk-cache.js): the native shell and the JS bundle are content-
28
+ # addressed independently, so a fresh worktree reuses the invariant native
29
+ # compile and only re-bundles JS. Order: full-key cache hit -> native-base +
30
+ # fresh-bundle OVERLAY (re-sign only) -> full Gradle build. The cache is a pure
31
+ # accelerator: any miss or doubt falls through to a real build, and the overlay
32
+ # never touches resources.arsc.
33
+ #
34
+ # Android SDK: resolved from the conventional locations and exported for Gradle
35
+ # (`ANDROID_HOME` / `ANDROID_SDK_ROOT`, then `~/android-sdk`), mirroring
36
+ # `device-up.sh`. A headless run (the nightly systemd timer, CI) has a stripped
37
+ # env with no `ANDROID_HOME`, so the Gradle Android plugin aborts
38
+ # "SDK location not found" before it configures — this wrapper is self-contained,
39
+ # so no project needs an env shim.
40
+ #
41
+ # Project config: `scripts/qa/mobile-e2e/local.json` (`appId`, `avd`); the paths
42
+ # below follow the conventional Expo/React-Native layout. Tunables (env):
43
+ # MOBILE_E2E_APK output APK path (default: conventional Gradle path)
44
+ # MOBILE_E2E_ABI ABI to build (default: x86_64 — the emulator)
45
+ # MOBILE_E2E_APK_MEM_MAX cgroup MemoryMax (default: 6G — a cold release
46
+ # D8/dex-merge needs ~4-6 GB; 3G OOMs)
47
+ # MOBILE_E2E_APK_CPU_MAX cgroup CPUQuota (default: 600%)
48
+ # MOBILE_E2E_SKIP_CACHE set 1 to bypass the cache entirely
49
+ # MOBILE_E2E_APK_OVERLAY set 0 to disable the native-base overlay (full
50
+ # build on every JS change instead)
51
+ #
52
+ # Usage:
53
+ # scripts/qa/mobile-e2e/build-apk.sh [--api-url http://10.0.2.2:3000]
54
+ #
55
+ # Output: the release APK path on success (also echoed as `APK=...`).
56
+ set -euo pipefail
57
+
58
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
59
+ ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
60
+ MOBILE_DIR="${ROOT}/mobile"
61
+ ANDROID_DIR="${MOBILE_DIR}/android"
62
+ MANIFEST="${ANDROID_DIR}/app/src/main/AndroidManifest.xml"
63
+ APK="${MOBILE_E2E_APK:-${ANDROID_DIR}/app/build/outputs/apk/release/app-release.apk}"
64
+ ABIS="${MOBILE_E2E_ABI:-x86_64}"
65
+ MEM_MAX="${MOBILE_E2E_APK_MEM_MAX:-6G}"
66
+ CPU_MAX="${MOBILE_E2E_APK_CPU_MAX:-600%}"
67
+
68
+ API_URL="http://10.0.2.2:3000"
69
+ while [ "$#" -gt 0 ]; do
70
+ case "$1" in
71
+ --api-url) API_URL="$2"; shift 2 ;;
72
+ --api-url=*) API_URL="${1#*=}"; shift ;;
73
+ -h|--help) grep '^#' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;
74
+ *) echo "Unknown argument: $1" >&2; exit 2 ;;
75
+ esac
76
+ done
77
+
78
+ command -v node >/dev/null 2>&1 || { echo "FAIL: node is not on PATH" >&2; exit 1; }
79
+ [ -d "$MOBILE_DIR" ] || { echo "FAIL: no mobile/ project at $MOBILE_DIR" >&2; exit 1; }
80
+
81
+ # Resolve the Android SDK and export it for Gradle. A headless invocation (the
82
+ # nightly systemd timer, CI) runs with a stripped env that has no ANDROID_HOME,
83
+ # so the Gradle Android plugin aborts "SDK location not found" before it even
84
+ # configures. Mirror device-up.sh's default so this wrapper is self-contained —
85
+ # no project-side shim is needed (F-331).
86
+ SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/android-sdk}}"
87
+ export ANDROID_HOME="$SDK"
88
+ export ANDROID_SDK_ROOT="$SDK"
89
+
90
+ echo "Mobile E2E release APK build (capped: mem≤${MEM_MAX}, cpu≤${CPU_MAX}, abi=${ABIS})"
91
+ echo " repo: ${ROOT}"
92
+ echo " api url: ${API_URL}"
93
+ echo " sdk: ${SDK}"
94
+ echo ""
95
+
96
+ # The bundle key bakes the API URL, so the cache and the build must agree on it.
97
+ export MOBILE_E2E_API_URL="${API_URL}"
98
+ CACHE_JS="${ROOT}/scripts/qa/mobile-e2e/apk-cache.js"
99
+
100
+ # 0. Reuse before building. A full-key hit means native + JS are unchanged; the
101
+ # overlay re-signs a fresh bundle onto the cached native base. Both are pure
102
+ # accelerators — any failure (exit != 0) falls through to the Gradle build.
103
+ if [ "${MOBILE_E2E_SKIP_CACHE:-0}" != "1" ] && [ -f "${CACHE_JS}" ]; then
104
+ if hit="$(node "${CACHE_JS}" get 2>/dev/null)"; then
105
+ echo "cache hit (native + JS unchanged): reusing ${hit}"
106
+ echo ""
107
+ echo "APK=${hit}"
108
+ exit 0
109
+ fi
110
+ if [ "${MOBILE_E2E_APK_OVERLAY:-1}" != "0" ]; then
111
+ if hit="$(node "${CACHE_JS}" overlay 2>/dev/null)"; then
112
+ echo "cache overlay (native base + fresh JS bundle): ${hit}"
113
+ echo ""
114
+ echo "APK=${hit}"
115
+ exit 0
116
+ fi
117
+ fi
118
+ echo "cache miss — building (override with MOBILE_E2E_SKIP_CACHE=1)"
119
+ fi
120
+
121
+ # 1. Generate the native project only when it is absent. Never prebuild over an
122
+ # existing android/ (it would wipe the cleartext patch below).
123
+ if [ ! -d "${ANDROID_DIR}" ]; then
124
+ echo "-> android/ project missing; running 'npx expo prebuild -p android'"
125
+ (cd "${MOBILE_DIR}" && npx expo prebuild -p android)
126
+ fi
127
+
128
+ # 2. Ensure the manifest allows cleartext to the emulator dev backend. Idempotent:
129
+ # a no-op when the attribute is already present.
130
+ echo "-> ensuring android:usesCleartextTraffic=\"true\" in the generated manifest"
131
+ node - "${MANIFEST}" <<'NODE'
132
+ const fs = require('fs');
133
+ const file = process.argv[2];
134
+ let xml = fs.readFileSync(file, 'utf8');
135
+ if (xml.includes('android:usesCleartextTraffic')) {
136
+ console.log(' already present');
137
+ } else if (/<application\b[^>]*>/.test(xml)) {
138
+ xml = xml.replace(/<application\b/, '<application android:usesCleartextTraffic="true"');
139
+ fs.writeFileSync(file, xml);
140
+ console.log(' patched');
141
+ } else {
142
+ console.error(' FAIL: no <application> element found in ' + file);
143
+ process.exit(1);
144
+ }
145
+ NODE
146
+
147
+ # 3. Right-size Gradle for a ~10 GB VM. mobile/android/ is gitignored and
148
+ # regenerated by `expo prebuild`, so the tuning lives in one MANAGED block at
149
+ # the end of gradle.properties (marked `safe to delete`). The block is
150
+ # REFRESHED each run, not merely appended once: a cold release `mergeDexRelease`
151
+ # (D8) needs ~4-6 GB, so a stale or hand-edited 1 GB heap OOMs (F-296), and a
152
+ # later `expo prebuild` that regenerates the file would otherwise leave two
153
+ # competing `org.gradle.jvmargs`. Workers + the Kotlin daemon are separate
154
+ # processes, but they share this one capped cgroup — keep the sum under MEM_MAX.
155
+ GRADLE_PROPS="${ANDROID_DIR}/gradle.properties"
156
+ node - "$GRADLE_PROPS" <<'NODE'
157
+ const fs = require("fs");
158
+ const file = process.argv[2];
159
+ const MARKER = "# agent-harness mobile E2E build tuning (managed; safe to delete)";
160
+ let text = "";
161
+ try { text = fs.readFileSync(file, "utf8"); } catch (_) { text = ""; }
162
+ const at = text.indexOf(MARKER);
163
+ if (at !== -1) text = text.slice(0, at); // drop our own block (and anything after it)
164
+ text = text.replace(/\s*$/, "");
165
+ const block =
166
+ "\n" +
167
+ MARKER +
168
+ "\n" +
169
+ "org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=768m\n" +
170
+ "org.gradle.parallel=false\n" +
171
+ "org.gradle.workers.max=1\n" +
172
+ "kotlin.daemon.jvmargs=-Xmx1024m\n" +
173
+ // Reuse invariant task outputs across worktrees (the shared build cache lives
174
+ // in the common ~/.gradle). The configuration cache skips re-configuring the
175
+ // project each run; `problems=warn` degrades to a normal configure instead of
176
+ // failing if a React-Native/Expo plugin is not yet configuration-cache safe.
177
+ "org.gradle.caching=true\n" +
178
+ "org.gradle.configuration-cache=true\n" +
179
+ "org.gradle.configuration-cache.problems=warn\n";
180
+ fs.writeFileSync(file, text + block);
181
+ NODE
182
+
183
+ # 4. Assemble the release APK inside a capped cgroup, with the dev backend URL
184
+ # baked into the JS bundle. `serve.js run` streams output and returns the
185
+ # build's exit code; a Gradle runaway is OOM-killed in its own scope, not the
186
+ # whole VM. One ABI (the emulator's) keeps the native build from compiling
187
+ # all four.
188
+ echo "-> serve.js run: ./gradlew assembleRelease (EXPO_PUBLIC_API_URL=${API_URL})"
189
+ GRADLE_CMD="cd \"${ANDROID_DIR}\" && EXPO_PUBLIC_API_URL=\"${API_URL}\" ./gradlew --no-daemon --build-cache --configuration-cache --max-workers=1 -PreactNativeArchitectures=${ABIS} assembleRelease"
190
+ node "${ROOT}/scripts/serve.js" run \
191
+ --name apk-build \
192
+ --mem-max "${MEM_MAX}" \
193
+ --cpu-max "${CPU_MAX}" \
194
+ --cmd "${GRADLE_CMD}"
195
+
196
+ if [ ! -f "${APK}" ]; then
197
+ echo "FAIL: expected APK not found at ${APK}" >&2
198
+ exit 1
199
+ fi
200
+
201
+ # 5. Populate the cache for the next run/worktree (best-effort): the native base
202
+ # (reused by the overlay) and the full-key artifact (instant no-op reuse).
203
+ if [ "${MOBILE_E2E_SKIP_CACHE:-0}" != "1" ] && [ -f "${CACHE_JS}" ]; then
204
+ node "${CACHE_JS}" base-put "${APK}" >/dev/null 2>&1 || true
205
+ node "${CACHE_JS}" put "${APK}" >/dev/null 2>&1 || true
206
+ fi
207
+
208
+ echo ""
209
+ echo "OK — release dev APK built:"
210
+ echo "APK=${APK}"