@1aboveio/app-dev-skills 0.0.0-stage → 0.1.1

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 (89) hide show
  1. package/README.md +30 -2
  2. package/package.json +34 -4
  3. package/skills/airflow/LICENSE +3 -0
  4. package/skills/airflow/SKILL.md +199 -0
  5. package/skills/airflow/release-check.mjs +93 -0
  6. package/skills/android-foundation/LICENSE +3 -0
  7. package/skills/android-foundation/SKILL.md +192 -0
  8. package/skills/android-foundation/assets/android-ci-job.yml +217 -0
  9. package/skills/android-foundation/references/ci.md +87 -0
  10. package/skills/android-foundation/references/gotchas.md +221 -0
  11. package/skills/android-foundation/references/setup.md +164 -0
  12. package/skills/android-foundation/release-check.mjs +93 -0
  13. package/skills/android-foundation/scripts/device-run.sh +176 -0
  14. package/skills/android-foundation/scripts/device-run.test.mjs +172 -0
  15. package/skills/app-debug/LICENSE +3 -0
  16. package/skills/app-debug/SKILL.md +110 -0
  17. package/skills/app-debug/references/common-errors.md +128 -0
  18. package/skills/app-debug/release-check.mjs +93 -0
  19. package/skills/better-auth/LICENSE +3 -0
  20. package/skills/better-auth/SKILL.md +598 -0
  21. package/skills/better-auth/references/feishu-api.md +270 -0
  22. package/skills/better-auth/release-check.mjs +93 -0
  23. package/skills/data-catalog/LICENSE +3 -0
  24. package/skills/data-catalog/SKILL.md +207 -0
  25. package/skills/data-catalog/agents/openai.yaml +3 -0
  26. package/skills/data-catalog/references/data-catalog-conventions.md +76 -0
  27. package/skills/data-catalog/references/field-definitions.md +123 -0
  28. package/skills/data-catalog/references/format.md +130 -0
  29. package/skills/data-catalog/release-check.mjs +93 -0
  30. package/skills/data-catalog/scripts/data-catalog.test.mjs +36 -0
  31. package/skills/data-catalog/scripts/data_catalog.py +1435 -0
  32. package/skills/data-catalog/scripts/persist-conventions-core.mjs +117 -0
  33. package/skills/data-catalog/scripts/persist-conventions.mjs +17 -0
  34. package/skills/data-catalog/scripts/test_data_catalog.py +603 -0
  35. package/skills/ios-foundation/LICENSE +3 -0
  36. package/skills/ios-foundation/SKILL.md +184 -0
  37. package/skills/ios-foundation/references/setup.md +243 -0
  38. package/skills/ios-foundation/release-check.mjs +93 -0
  39. package/skills/monorepo/LICENSE +3 -0
  40. package/skills/monorepo/SKILL.md +462 -0
  41. package/skills/monorepo/release-check.mjs +93 -0
  42. package/skills/nextjs-fullstack/LICENSE +3 -0
  43. package/skills/nextjs-fullstack/SKILL.md +211 -0
  44. package/skills/nextjs-fullstack/conventions.md +318 -0
  45. package/skills/nextjs-fullstack/frontend-conventions.md +61 -0
  46. package/skills/nextjs-fullstack/nextjs16.md +287 -0
  47. package/skills/nextjs-fullstack/release-check.mjs +93 -0
  48. package/skills/nextjs-fullstack/server-actions.md +409 -0
  49. package/skills/prisma-setup/LICENSE +3 -0
  50. package/skills/prisma-setup/SKILL.md +181 -0
  51. package/skills/prisma-setup/nextjs.md +258 -0
  52. package/skills/prisma-setup/release-check.mjs +93 -0
  53. package/skills/prisma-setup/turborepo.md +301 -0
  54. package/skills/pyspark/LICENSE +3 -0
  55. package/skills/pyspark/SKILL.md +127 -0
  56. package/skills/pyspark/assets/templates/etl.py +748 -0
  57. package/skills/pyspark/assets/templates/utils/__init__.py +1 -0
  58. package/skills/pyspark/assets/templates/utils/hudi_metadata.py +14 -0
  59. package/skills/pyspark/references/diagnosis-and-profiling.md +169 -0
  60. package/skills/pyspark/references/etl-contract.md +129 -0
  61. package/skills/pyspark/references/production-validation.md +131 -0
  62. package/skills/pyspark/references/reconciliation.md +38 -0
  63. package/skills/pyspark/references/transformation-design.md +190 -0
  64. package/skills/pyspark/references/velocity-feature-calculation.md +193 -0
  65. package/skills/pyspark/release-check.mjs +93 -0
  66. package/skills/pyspark/scripts/spark_eventlog_summary.py +223 -0
  67. package/skills/python-backend/LICENSE +3 -0
  68. package/skills/python-backend/SKILL.md +325 -0
  69. package/skills/python-backend/assets/uv-install.sh +48 -0
  70. package/skills/python-backend/references/uv-installs.md +83 -0
  71. package/skills/python-backend/release-check.mjs +93 -0
  72. package/skills/shadcn/LICENSE +3 -0
  73. package/skills/shadcn/SKILL.md +120 -0
  74. package/skills/shadcn/assets/shadcn-small.png +0 -0
  75. package/skills/shadcn/assets/shadcn.png +0 -0
  76. package/skills/shadcn/cli.md +411 -0
  77. package/skills/shadcn/customization.md +224 -0
  78. package/skills/shadcn/mcp.md +101 -0
  79. package/skills/shadcn/release-check.mjs +93 -0
  80. package/skills/shadcn/rules/base-vs-radix.md +323 -0
  81. package/skills/shadcn/rules/component-selection.md +67 -0
  82. package/skills/shadcn/rules/composition.md +195 -0
  83. package/skills/shadcn/rules/data-table.md +201 -0
  84. package/skills/shadcn/rules/forms.md +255 -0
  85. package/skills/shadcn/rules/icons.md +103 -0
  86. package/skills/shadcn/rules/styling.md +167 -0
  87. package/skills/zod-v4/LICENSE +3 -0
  88. package/skills/zod-v4/SKILL.md +286 -0
  89. package/skills/zod-v4/release-check.mjs +93 -0
@@ -0,0 +1,164 @@
1
+ # Android foundation: shell snippets
2
+
3
+ Replace each `<placeholder>` with the repo's real value. Tool shells do not keep variables,
4
+ functions or traps between calls: step 1 writes `.cache/android-env.sh`, which also `cd`s
5
+ into the worktree, and every later block starts by sourcing it by absolute path, and steps 6–8 run as one command through the bundled
6
+ `scripts/device-run.sh`.
7
+
8
+ ## 1. Checkout and environment
9
+
10
+ ```bash
11
+ set -euo pipefail
12
+ git fetch origin main
13
+ git worktree add -b <new-branch> ../<repo>-android-setup origin/main
14
+ cd ../<repo>-android-setup
15
+ git rev-parse HEAD
16
+ mkdir -p .cache
17
+ { echo 'set -euo pipefail'; printf 'cd %q\n' "$PWD"; } > .cache/android-env.sh
18
+ cat >> .cache/android-env.sh <<'ENV'
19
+
20
+ # Repo-specific names, read from the repo's journey wrapper and device harness.
21
+ export APP_FILTER=<android-workspace-package> # pnpm --filter target
22
+ export DEVICE_PYTHON_DIR=<venv-dir-the-wrapper-reads> # e.g. the default in the wrapper
23
+ export DB_NAME_PREFIX=<db-prefix-the-harness-accepts> # the harness rejects other names
24
+ export DB_URL_VAR=<harness-admin-url-variable> # e.g. SHARD_ADMIN_URL
25
+ export DB_NAME_VAR=<harness-db-name-variable> # e.g. SHARD_DB_NAME
26
+
27
+ # Host paths. Example values are for Apple Silicon with Android Studio.
28
+ export JAVA_HOME=/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home
29
+ export ANDROID_HOME="$HOME/Library/Android/sdk"
30
+ export ANDROID_SDK_ROOT="$ANDROID_HOME"
31
+ export SOURCE_AVD="$HOME/.android/avd/<installed-avd>.avd"
32
+ export SEED_GRADLE_HOME="$HOME/.gradle"
33
+ export PATH="$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$PATH"
34
+
35
+ # Private caches.
36
+ export GRADLE_USER_HOME="$PWD/.cache/gradle"
37
+ export ANDROID_USER_HOME="$PWD/.cache/android-user"
38
+ export ANDROID_AVD_HOME="$PWD/.cache/android-avd"
39
+ export TMPDIR="$PWD/.cache/tmp"
40
+ export npm_config_cache="$PWD/.cache/npm"
41
+ export npm_config_devdir="$PWD/.cache/node-gyp"
42
+ export PNPM_CONFIG_STORE_DIR="$PWD/.cache/pnpm-store"
43
+ export PNPM_CONFIG_CACHE_DIR="$PWD/.cache/pnpm"
44
+ case "${JAVA_TOOL_OPTIONS:-}" in *java.io.tmpdir*) ;; *)
45
+ export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }-Djava.io.tmpdir=$TMPDIR" ;; esac
46
+
47
+ # Run identifiers: an even console port in 5554-5584 (adb scans only that range),
48
+ # and backend/Metro ports under the names the journey wrapper reads.
49
+ export SETUP_AVD=<new-unique-avd-name>
50
+ export EMULATOR_PORT=<even-port-5554-5584>
51
+ export ANDROID_BACKEND_PORT=<free-port>
52
+ export ANDROID_METRO_PORT=<free-port>
53
+ ENV
54
+ source .cache/android-env.sh
55
+ mkdir -p "$TMPDIR" "$npm_config_cache" "$npm_config_devdir" \
56
+ "$ANDROID_USER_HOME" "$ANDROID_AVD_HOME" .cache/logs
57
+
58
+ node --version; pnpm --version; java -version; python3 --version
59
+ adb version; "$ANDROID_HOME/emulator/emulator" -version
60
+ # Versions come from the repo's native config and CI preflight.
61
+ for component in platforms/android-<api> build-tools/<build-tools> ndk/<ndk> cmake/<cmake>; do
62
+ test -d "$ANDROID_HOME/$component" || { echo "Missing SDK: $component" >&2; exit 1; }
63
+ done
64
+ ```
65
+
66
+ If the wrapper reads its port or Python variables under other names, export those names in
67
+ `android-env.sh` instead.
68
+
69
+ ## 2. Install and check
70
+
71
+ ```bash
72
+ source <worktree>/.cache/android-env.sh
73
+ pnpm install --frozen-lockfile --store-dir "$PWD/.cache/pnpm-store"
74
+ pnpm --filter "$APP_FILTER" test
75
+ pnpm --filter "$APP_FILTER" typecheck
76
+ EXPO_PUBLIC_API_URL=https://app.invalid \
77
+ pnpm --filter "$APP_FILTER" exec expo export --platform android
78
+ python3 -m venv "$DEVICE_PYTHON_DIR"
79
+ "$DEVICE_PYTHON_DIR/bin/python3" -m pip install uiautomator2==<harness-pinned-version>
80
+ ```
81
+
82
+ ## 3. Gradle dependencies (pick one)
83
+
84
+ Seed from a trusted Gradle home:
85
+
86
+ ```bash
87
+ source <worktree>/.cache/android-env.sh
88
+ mkdir -p "$GRADLE_USER_HOME/caches/modules-2/files-2.1"
89
+ rsync -r --ignore-existing \
90
+ --exclude='*.lock' --exclude='*.lck' --exclude='*.tmp' \
91
+ "$SEED_GRADLE_HOME/caches/modules-2/files-2.1/" \
92
+ "$GRADLE_USER_HOME/caches/modules-2/files-2.1/"
93
+ ```
94
+
95
+ Or wire a trusted Maven proxy into the private Gradle home. Append the exports to
96
+ `android-env.sh` so the build in step 4 sees them. Route every repository the build uses,
97
+ JitPack included; a route left unset goes straight upstream.
98
+
99
+ ```bash
100
+ source <worktree>/.cache/android-env.sh
101
+ cat >> "$PWD/.cache/android-env.sh" <<'ENV'
102
+ export GRADLE_MAVEN_REPOSITORY=<proxy>/maven/
103
+ export GRADLE_GOOGLE_REPOSITORY=<proxy>/google-maven/
104
+ export GRADLE_PLUGIN_REPOSITORY=<proxy>/gradle-plugins/
105
+ export GRADLE_JITPACK_REPOSITORY=<proxy>/jitpack/
106
+ ENV
107
+ curl --fail --silent --show-error --max-time 10 <proxy-health-url>
108
+ install -d "$GRADLE_USER_HOME/init.d"
109
+ install -m 0644 <path/to/proxy.init.gradle> "$GRADLE_USER_HOME/init.d/proxy.init.gradle"
110
+ ```
111
+
112
+ ## 4. Build
113
+
114
+ ```bash
115
+ source <worktree>/.cache/android-env.sh
116
+ pnpm build:android --max-workers=2 -Dorg.gradle.parallel=false \
117
+ -Pandroid.builder.sdkDownload=false --console=plain --info \
118
+ 2>&1 | tee .cache/logs/gradle.log
119
+ APK=<path/to/app/build/outputs/apk/debug/app-debug.apk>
120
+ shasum -a 256 "$APK" # sha256sum on Linux
121
+ unzip -l "$APK" | grep -E 'lib/[^/]+/libreactnative\.so'
122
+ ```
123
+
124
+ ## 5. Owned emulator
125
+
126
+ ```bash
127
+ source <worktree>/.cache/android-env.sh
128
+ test -f "$SOURCE_AVD/config.ini"
129
+ test ! -e "$ANDROID_AVD_HOME/$SETUP_AVD.ini"
130
+ test ! -e "$ANDROID_AVD_HOME/$SETUP_AVD.avd"
131
+ grep '^image.sysdir.1' "$SOURCE_AVD/config.ini" # must be an installed, host-compatible image
132
+ mkdir "$ANDROID_AVD_HOME/$SETUP_AVD.avd"
133
+ # Copy without the source's RAM size and give the guest 4 GB (gotchas: adb transport drops).
134
+ grep -Ev '^hw\.ramSize[[:space:]]*=' "$SOURCE_AVD/config.ini" > "$ANDROID_AVD_HOME/$SETUP_AVD.avd/config.ini"
135
+ echo 'hw.ramSize=4096' >> "$ANDROID_AVD_HOME/$SETUP_AVD.avd/config.ini"
136
+ printf 'avd.ini.encoding=UTF-8\npath=%s\ntarget=android-<api>\n' \
137
+ "$ANDROID_AVD_HOME/$SETUP_AVD.avd" > "$ANDROID_AVD_HOME/$SETUP_AVD.ini"
138
+ ```
139
+
140
+ ## 6–8. Cleanup, resources and journey: one command
141
+
142
+ ```bash
143
+ source <worktree>/.cache/android-env.sh
144
+ bash <skill-base-dir>/scripts/device-run.sh \
145
+ --drop node <path/to/device-harness.mjs> drop \
146
+ -- bash <path/to/foundation-journey-wrapper.sh>
147
+ ```
148
+
149
+ Pass each command as separate words, not as one quoted string. The script:
150
+
151
+ 1. Registers the cleanup trap before anything starts.
152
+ 2. Refuses an emulator port outside 5554–5584 and any busy port.
153
+ 3. Starts the ADB server, then the emulator (its PID recorded), then `postgres` with
154
+ `--cidfile` on a random loopback port. Override the image with `POSTGRES_IMAGE`.
155
+ 4. Waits for `sys.boot_completed=1` and `pg_isready`. Every command has a 30-second limit
156
+ (`BOUNDED_SECONDS`) that kills the command's whole process group; exit 124 is terminal.
157
+ 5. Exports `$DB_URL_VAR`, `$DB_NAME_VAR` (`$DB_NAME_PREFIX` plus a unique suffix) and
158
+ `ANDROID_EMULATOR_SERIAL`, then runs the journey.
159
+ 6. Drops the database, stops the emulator PID (`TERM`, then `KILL` after 10 seconds),
160
+ removes the container by its CID, and prints `original_stage_exit=<n> cleanup_exit=<n>`.
161
+ It exits with the journey's status if the journey failed, else the cleanup status.
162
+
163
+ The journey stops its own backend and Metro children. Capture the command's exit status and
164
+ the last output line for the evidence record.
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+ const WEEK_MS = 7 * DAY_MS;
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+
12
+ function readJson(path, fallback = {}) {
13
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
14
+ }
15
+
16
+ function frontmatterValue(text, key) {
17
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? '';
18
+ const match = new RegExp('^' + key + ':\\s*([^\\n]+)$', 'm').exec(frontmatter);
19
+ return match?.[1].trim().replace(/^['"]|['"]$/g, '') ?? null;
20
+ }
21
+
22
+ function repositoryOf(source) {
23
+ const value = String(source ?? '').trim();
24
+ const match = /^(?:git@github\.com:|https:\/\/github\.com\/)?([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(value);
25
+ return match?.[1] ?? null;
26
+ }
27
+
28
+ function stableVersion(value) {
29
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(value ?? '').trim());
30
+ return match ? match.slice(1).map(Number) : null;
31
+ }
32
+
33
+ function newer(left, right) {
34
+ for (let index = 0; index < 3; index += 1) {
35
+ if (left[index] !== right[index]) return left[index] > right[index];
36
+ }
37
+ return false;
38
+ }
39
+
40
+ function writeCache(path, value) {
41
+ try {
42
+ mkdirSync(dirname(path), { recursive: true });
43
+ writeFileSync(path, JSON.stringify(value));
44
+ } catch { /* A read-only cache must not block skill use. */ }
45
+ }
46
+
47
+ function main(now = Date.now()) {
48
+ if (process.env.ONEABOVEIO_NO_UPDATE_CHECK) return;
49
+ const skill = readFileSync(join(here, 'SKILL.md'), 'utf8');
50
+ const name = frontmatterValue(skill, 'name');
51
+ const localVersion = stableVersion(frontmatterValue(skill, 'release-version'));
52
+ if (!name || !localVersion) return;
53
+
54
+ const lock = readJson(join(process.env.HOME || homedir(), '.agents', '.skill-lock.json'));
55
+ const entry = lock.skills?.[name];
56
+ const repository = repositoryOf(entry?.sourceUrl || entry?.source);
57
+ if (!repository) return;
58
+
59
+ const cacheRoot = process.env.XDG_CACHE_HOME || join(process.env.HOME || homedir(), '.cache');
60
+ const cachePath = join(cacheRoot, '1aboveio-skills', 'release-check.json');
61
+ const all = readJson(cachePath);
62
+ const cache = all[repository] && typeof all[repository] === 'object' ? all[repository] : {};
63
+
64
+ if (!cache.lastCheck || now - cache.lastCheck >= DAY_MS) {
65
+ const result = spawnSync('gh', ['api', 'repos/' + repository + '/releases/latest', '--jq', '.tag_name'], {
66
+ encoding: 'utf8',
67
+ stdio: ['ignore', 'pipe', 'ignore'],
68
+ timeout: 1500,
69
+ });
70
+ cache.lastCheck = now;
71
+ if (result.status === 0 && stableVersion(result.stdout)) cache.latestTag = result.stdout.trim();
72
+ else delete cache.latestTag;
73
+ all[repository] = cache;
74
+ writeCache(cachePath, all);
75
+ }
76
+
77
+ const latestVersion = stableVersion(cache.latestTag);
78
+ if (!latestVersion || !newer(latestVersion, localVersion)) return;
79
+ if (cache.notifiedTag === cache.latestTag && cache.notifiedAt && now - cache.notifiedAt < WEEK_MS) return;
80
+
81
+ cache.notifiedTag = cache.latestTag;
82
+ cache.notifiedAt = now;
83
+ all[repository] = cache;
84
+ writeCache(cachePath, all);
85
+ const command = `npx skills@1.5.23 add '${repository}#${cache.latestTag}' --global --agent universal claude-code --skill ${name} --yes`;
86
+ process.stdout.write(
87
+ `UPDATE_AVAILABLE: A newer 1AboveIO skills release (${cache.latestTag}) is available; this skill is `
88
+ + `v${localVersion.join('.')}. Ask once whether to refresh ${name}. On approval run \`${command}\`. `
89
+ + 'The refreshed instructions apply next session. Either way, continue the current task and do not ask again this session.\n',
90
+ );
91
+ }
92
+
93
+ try { main(); } catch { /* Update checks are advisory and always fail silent. */ }
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env bash
2
+ # Boot an owned emulator and a disposable PostgreSQL, run the device journey, and
3
+ # clean up only what this run started. Run it as ONE command: an agent's tool
4
+ # shell does not keep variables, functions or traps between calls.
5
+ #
6
+ # Usage:
7
+ # device-run.sh --drop <db-drop command...> -- <journey command...>
8
+ #
9
+ # Required environment:
10
+ # ANDROID_HOME SDK root (emulator/emulator)
11
+ # SETUP_AVD private AVD name under $ANDROID_AVD_HOME
12
+ # EMULATOR_PORT even console port, 5554-5584 (adb scans only this range)
13
+ # ANDROID_BACKEND_PORT backend port the journey uses
14
+ # ANDROID_METRO_PORT Metro port the journey uses
15
+ # DB_NAME_PREFIX database-name prefix the harness accepts, e.g. app_e2e_
16
+ # Optional environment:
17
+ # POSTGRES_IMAGE (postgres:17) DB_URL_VAR (SHARD_ADMIN_URL) DB_NAME_VAR (SHARD_DB_NAME)
18
+ # LOG_DIR (.cache/logs) BOUNDED_SECONDS (30) BOOT_ATTEMPTS (60) KILL_GRACE_SECONDS (10)
19
+ #
20
+ # Exports ANDROID_EMULATOR_SERIAL, $DB_URL_VAR and $DB_NAME_VAR to both commands.
21
+ # Prints `original_stage_exit=<n> cleanup_exit=<n>` last and exits with the
22
+ # stage's status when it failed, else the cleanup status.
23
+ set -euo pipefail
24
+
25
+ drop_cmd=()
26
+ journey_cmd=()
27
+ if test "${1:-}" != --drop; then
28
+ echo "usage: device-run.sh --drop <cmd...> -- <journey cmd...>" >&2
29
+ exit 2
30
+ fi
31
+ shift
32
+ while test $# -gt 0 && test "$1" != --; do drop_cmd+=("$1"); shift; done
33
+ if test $# -eq 0; then echo "missing -- before the journey command" >&2; exit 2; fi
34
+ shift
35
+ journey_cmd=("$@")
36
+ if test ${#drop_cmd[@]} -eq 0 || test ${#journey_cmd[@]} -eq 0; then
37
+ echo "both the drop command and the journey command are required" >&2
38
+ exit 2
39
+ fi
40
+
41
+ : "${ANDROID_HOME:?}" "${SETUP_AVD:?}" "${EMULATOR_PORT:?}"
42
+ : "${ANDROID_BACKEND_PORT:?}" "${ANDROID_METRO_PORT:?}" "${DB_NAME_PREFIX:?}"
43
+ POSTGRES_IMAGE="${POSTGRES_IMAGE:-postgres:17}"
44
+ DB_URL_VAR="${DB_URL_VAR:-SHARD_ADMIN_URL}"
45
+ DB_NAME_VAR="${DB_NAME_VAR:-SHARD_DB_NAME}"
46
+ LOG_DIR="${LOG_DIR:-.cache/logs}"
47
+ BOUNDED_SECONDS="${BOUNDED_SECONDS:-30}"
48
+ BOOT_ATTEMPTS="${BOOT_ATTEMPTS:-60}"
49
+ KILL_GRACE_SECONDS="${KILL_GRACE_SECONDS:-10}"
50
+
51
+ if ! [[ "$EMULATOR_PORT" =~ ^[0-9]+$ ]] || (( EMULATOR_PORT < 5554 || EMULATOR_PORT > 5584 || EMULATOR_PORT % 2 )); then
52
+ echo "EMULATOR_PORT must be an even port in 5554-5584: $EMULATOR_PORT" >&2
53
+ exit 2
54
+ fi
55
+
56
+ mkdir -p "$LOG_DIR"
57
+ run_dir="$(mktemp -d "${TMPDIR:-/tmp}/android-device-run.XXXXXX")"
58
+ emulator_pid=""
59
+ db_ready=""
60
+ export ANDROID_EMULATOR_SERIAL="emulator-$EMULATOR_PORT"
61
+
62
+ bounded() {
63
+ # Kill the whole process group on timeout: a surviving grandchild would hold
64
+ # the output pipe open and stall the caller past the deadline.
65
+ python3 -c 'import os, signal, subprocess, sys
66
+ limit = float(sys.argv[1])
67
+ child = subprocess.Popen(sys.argv[2:], start_new_session=True)
68
+ try:
69
+ sys.exit(child.wait(timeout=limit))
70
+ except subprocess.TimeoutExpired:
71
+ os.killpg(child.pid, signal.SIGKILL)
72
+ child.wait()
73
+ print("Command exceeded %s seconds: %s" % (sys.argv[1], " ".join(sys.argv[2:])), file=sys.stderr)
74
+ sys.exit(124)' "$BOUNDED_SECONDS" "$@"
75
+ }
76
+
77
+ cleanup() {
78
+ original_status=$?
79
+ trap - EXIT INT TERM
80
+ set +e
81
+ cleanup_status=0
82
+ if test -n "$db_ready"; then
83
+ bounded "${drop_cmd[@]}" || cleanup_status=1
84
+ fi
85
+ if test -n "$emulator_pid"; then
86
+ if kill -0 "$emulator_pid" 2>/dev/null; then
87
+ kill -TERM "$emulator_pid" || cleanup_status=1
88
+ fi
89
+ for _ in $(seq 1 "$KILL_GRACE_SECONDS"); do
90
+ kill -0 "$emulator_pid" 2>/dev/null || break
91
+ sleep 1
92
+ done
93
+ if kill -0 "$emulator_pid" 2>/dev/null; then
94
+ cleanup_status=1
95
+ kill -KILL "$emulator_pid"
96
+ sleep 1
97
+ fi
98
+ if kill -0 "$emulator_pid" 2>/dev/null; then
99
+ cleanup_status=1
100
+ else
101
+ wait "$emulator_pid"
102
+ emulator_status=$?
103
+ # 0 = clean exit; 143 = ended by our TERM. A KILL was already counted above.
104
+ case "$emulator_status" in 0|143) ;; *) cleanup_status=1 ;; esac
105
+ fi
106
+ fi
107
+ if test -s "$run_dir/postgres.cid"; then
108
+ container_id="$(< "$run_dir/postgres.cid")"
109
+ bounded docker rm --force "$container_id" >/dev/null || cleanup_status=1
110
+ remaining="$(bounded docker ps -a --no-trunc --filter "id=$container_id" --format '{{.ID}}')" || cleanup_status=1
111
+ test -z "$remaining" || cleanup_status=1
112
+ fi
113
+ printf 'original_stage_exit=%s cleanup_exit=%s\n' "$original_status" "$cleanup_status"
114
+ if test "$original_status" -ne 0; then exit "$original_status"; fi
115
+ exit "$cleanup_status"
116
+ }
117
+ trap cleanup EXIT
118
+ trap 'exit 130' INT
119
+ trap 'exit 143' TERM
120
+
121
+ # Every port this run listens on or dials must be free before anything starts.
122
+ python3 -c 'import socket, sys
123
+ for port in map(int, sys.argv[1:]):
124
+ with socket.socket() as probe:
125
+ probe.bind(("127.0.0.1", port))' \
126
+ "$EMULATOR_PORT" "$((EMULATOR_PORT + 1))" "$ANDROID_BACKEND_PORT" "$ANDROID_METRO_PORT"
127
+
128
+ # Start the ADB server first so the emulator registers with it on boot.
129
+ bounded adb start-server
130
+
131
+ # -memory 4096 overrides the AVD's hw.ramSize, so a reused 2 GB AVD cannot starve the
132
+ # guest kernel's vsock allocations and drop adb mid-journey (references/gotchas.md).
133
+ "$ANDROID_HOME/emulator/emulator" -avd "$SETUP_AVD" -port "$EMULATOR_PORT" -memory 4096 \
134
+ -no-window -no-audio -no-snapshot -gpu swiftshader_indirect -accel on \
135
+ > "$LOG_DIR/emulator.log" 2>&1 &
136
+ emulator_pid=$!
137
+
138
+ container_name="android-device-run-$(date +%s)-$$"
139
+ bounded docker run --detach --name "$container_name" --cidfile "$run_dir/postgres.cid" \
140
+ --publish 127.0.0.1::5432 --env POSTGRES_USER=postgres \
141
+ --env POSTGRES_PASSWORD=postgres --env POSTGRES_DB=postgres "$POSTGRES_IMAGE" >/dev/null
142
+ db_port="$(bounded docker port "$container_name" 5432/tcp | head -1 | awk -F: '{print $NF}')"
143
+ test -n "$db_port"
144
+
145
+ boot_state=""
146
+ for _ in $(seq 1 "$BOOT_ATTEMPTS"); do
147
+ if boot_state="$(bounded adb -s "$ANDROID_EMULATOR_SERIAL" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')"; then
148
+ if test "$boot_state" = 1; then break; fi
149
+ else
150
+ probe_status=$?
151
+ # A stalled command is terminal, not "not ready yet".
152
+ if test "$probe_status" -eq 124; then exit 124; fi
153
+ fi
154
+ sleep 2
155
+ done
156
+ if test "$boot_state" != 1; then echo "emulator did not finish booting" >&2; exit 1; fi
157
+
158
+ pg_ready=""
159
+ for _ in $(seq 1 30); do
160
+ if bounded docker exec "$container_name" pg_isready -U postgres >/dev/null; then
161
+ pg_ready=1
162
+ break
163
+ else
164
+ probe_status=$?
165
+ if test "$probe_status" -eq 124; then exit 124; fi
166
+ fi
167
+ sleep 1
168
+ done
169
+ if test -z "$pg_ready"; then echo "PostgreSQL did not become ready" >&2; exit 1; fi
170
+
171
+ # The password belongs only to this disposable loopback container.
172
+ export "$DB_URL_VAR=postgresql://postgres:postgres@127.0.0.1:$db_port/postgres"
173
+ export "$DB_NAME_VAR=${DB_NAME_PREFIX}$(date +%s)_$$"
174
+ db_ready=1
175
+
176
+ "${journey_cmd[@]}"
@@ -0,0 +1,172 @@
1
+ // device-run.sh against stand-in emulator, adb and docker binaries: the cleanup
2
+ // owns exactly what the run started, keeps the stage's status, and treats a
3
+ // stalled command as terminal.
4
+ import { test } from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
8
+ import { createServer } from 'node:net';
9
+ import { tmpdir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), 'device-run.sh');
14
+
15
+ async function fakeHost() {
16
+ const root = mkdtempSync(join(tmpdir(), 'device-run-'));
17
+ const bin = join(root, 'bin');
18
+ const sdk = join(root, 'sdk');
19
+ mkdirSync(bin);
20
+ mkdirSync(join(sdk, 'emulator'), { recursive: true });
21
+ const log = join(root, 'calls.log');
22
+ writeFileSync(log, '');
23
+ const tool = (path, body) => {
24
+ writeFileSync(path, `#!/usr/bin/env bash\necho "$(basename "$0") $*" >> "$FAKE_LOG"\n${body}\n`);
25
+ chmodSync(path, 0o755);
26
+ };
27
+ tool(join(sdk, 'emulator', 'emulator'), `
28
+ if test -n "\${FAKE_EMULATOR_IGNORES_TERM:-}"; then trap '' TERM; fi
29
+ while :; do sleep 0.1; done`);
30
+ tool(join(bin, 'adb'), `
31
+ case "$*" in
32
+ start-server) exit 0 ;;
33
+ *getprop*) if test -n "\${FAKE_ADB_HANG:-}"; then sleep 30; fi; echo 1 ;;
34
+ esac`);
35
+ tool(join(bin, 'docker'), `
36
+ case "$1" in
37
+ run) while test $# -gt 0; do if test "$1" = --cidfile; then echo fakecid42 > "$2"; fi; shift; done; echo fakecid42 ;;
38
+ port) echo 127.0.0.1:55432 ;;
39
+ exec) exit 0 ;;
40
+ rm) exit 0 ;;
41
+ ps) exit 0 ;;
42
+ esac`);
43
+ return { root, bin, sdk, log, ports: await hostPorts() };
44
+ }
45
+
46
+ // Runners share the host network, so every port this suite hands the script is one the
47
+ // OS reports free right now, never a fixed number another job may already hold.
48
+ function listen(port) {
49
+ return new Promise((resolve, reject) => {
50
+ const server = createServer();
51
+ server.once('error', reject);
52
+ server.listen(port, '127.0.0.1', () => resolve(server));
53
+ });
54
+ }
55
+
56
+ async function freePort() {
57
+ const server = await listen(0);
58
+ const { port } = server.address();
59
+ await new Promise((resolve) => server.close(resolve));
60
+ return port;
61
+ }
62
+
63
+ async function freeEmulatorPort() {
64
+ for (let port = 5554; port <= 5584; port += 2) {
65
+ const held = [];
66
+ try {
67
+ held.push(await listen(port), await listen(port + 1));
68
+ return port;
69
+ } catch {
70
+ // taken; try the next pair
71
+ } finally {
72
+ await Promise.all(held.map((server) => new Promise((resolve) => server.close(resolve))));
73
+ }
74
+ }
75
+ throw new Error('no free emulator port pair in 5554-5584');
76
+ }
77
+
78
+ async function hostPorts() {
79
+ return {
80
+ EMULATOR_PORT: String(await freeEmulatorPort()),
81
+ ANDROID_BACKEND_PORT: String(await freePort()),
82
+ ANDROID_METRO_PORT: String(await freePort()),
83
+ };
84
+ }
85
+
86
+ function run(host, { journey = ['bash', '-c', 'exit 0'], env = {} } = {}) {
87
+ const drop = ['bash', '-c', 'echo "drop $SHARD_DB_NAME $SHARD_ADMIN_URL" >> "$FAKE_LOG"'];
88
+ const result = spawnSync('bash', [SCRIPT, '--drop', ...drop, '--', ...journey], {
89
+ cwd: host.root,
90
+ encoding: 'utf8',
91
+ timeout: 60_000,
92
+ env: {
93
+ PATH: `${host.bin}:${process.env.PATH}`,
94
+ TMPDIR: host.root,
95
+ FAKE_LOG: host.log,
96
+ ANDROID_HOME: host.sdk,
97
+ SETUP_AVD: 'Test_Phone',
98
+ ...host.ports,
99
+ DB_NAME_PREFIX: 'app_e2e_',
100
+ KILL_GRACE_SECONDS: '2',
101
+ BOUNDED_SECONDS: '5',
102
+ ...env,
103
+ },
104
+ });
105
+ return { ...result, calls: readFileSync(host.log, 'utf8') };
106
+ }
107
+
108
+ test('a passing journey cleans up everything it started and exits 0', async () => {
109
+ const host = await fakeHost();
110
+ const marker = join(host.root, 'journey ran.txt');
111
+ const r = run(host, { journey: ['bash', '-c', 'echo "$ANDROID_EMULATOR_SERIAL $SHARD_DB_NAME" > "$1"', 'journey', marker] });
112
+ assert.equal(r.status, 0, r.stderr);
113
+ assert.match(r.stdout, /original_stage_exit=0 cleanup_exit=0\n$/);
114
+ const port = host.ports.EMULATOR_PORT;
115
+ assert.match(readFileSync(marker, 'utf8'), new RegExp(`^emulator-${port} app_e2e_\\d+_\\d+\\n$`));
116
+ assert.match(r.calls, /^adb start-server$/m);
117
+ assert.ok(r.calls.indexOf('adb start-server') < r.calls.indexOf(`emulator -avd Test_Phone -port ${port}`));
118
+ assert.match(r.calls, new RegExp(`^emulator -avd Test_Phone -port ${port} -memory 4096 `, 'm'));
119
+ assert.match(r.calls, /^drop app_e2e_\d+_\d+ postgresql:\/\/postgres:postgres@127\.0\.0\.1:55432\/postgres$/m);
120
+ assert.match(r.calls, /^docker rm --force fakecid42$/m);
121
+ });
122
+
123
+ test('a failing journey keeps its status and still cleans up', async () => {
124
+ const host = await fakeHost();
125
+ const r = run(host, { journey: ['bash', '-c', 'exit 42'] });
126
+ assert.equal(r.status, 42);
127
+ assert.match(r.stdout, /original_stage_exit=42 cleanup_exit=0/);
128
+ assert.match(r.calls, /^drop app_e2e_/m);
129
+ assert.match(r.calls, /^docker rm --force fakecid42$/m);
130
+ });
131
+
132
+ test('an emulator that ignores TERM is killed and reported as a cleanup failure', async () => {
133
+ const host = await fakeHost();
134
+ const r = run(host, { env: { FAKE_EMULATOR_IGNORES_TERM: '1' } });
135
+ assert.equal(r.status, 1);
136
+ assert.match(r.stdout, /original_stage_exit=0 cleanup_exit=1/);
137
+ assert.match(r.calls, /^docker rm --force fakecid42$/m);
138
+ });
139
+
140
+ test('a stalled readiness probe ends the run with 124 and no journey', async () => {
141
+ const host = await fakeHost();
142
+ const marker = join(host.root, 'journey-ran');
143
+ const started = Date.now();
144
+ const r = run(host, { journey: ['touch', marker], env: { FAKE_ADB_HANG: '1', BOUNDED_SECONDS: '1' } });
145
+ assert.equal(r.status, 124);
146
+ assert.ok(Date.now() - started < 15_000, 'the deadline must not wait for the stalled command\'s children');
147
+ assert.match(r.stdout, /original_stage_exit=124 cleanup_exit=0/);
148
+ assert.equal(existsSync(marker), false);
149
+ assert.doesNotMatch(r.calls, /^drop /m, 'no database was handed to the harness, so none is dropped');
150
+ assert.match(r.calls, /^docker rm --force fakecid42$/m);
151
+ });
152
+
153
+ test('a busy port stops the run before anything starts', async () => {
154
+ const host = await fakeHost();
155
+ const server = await listen(Number(host.ports.ANDROID_BACKEND_PORT));
156
+ try {
157
+ const r = run(host);
158
+ assert.notEqual(r.status, 0);
159
+ assert.match(r.stdout, /cleanup_exit=0/);
160
+ assert.doesNotMatch(r.calls, /emulator -avd|docker run/);
161
+ } finally {
162
+ server.close();
163
+ }
164
+ });
165
+
166
+ test('an emulator port outside the range adb scans is refused', async () => {
167
+ const host = await fakeHost();
168
+ const r = run(host, { env: { EMULATOR_PORT: '5588' } });
169
+ assert.equal(r.status, 2);
170
+ assert.match(r.stderr, /even port in 5554-5584/);
171
+ assert.equal(r.calls, '');
172
+ });
@@ -0,0 +1,3 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 1AboveIO