Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: universal Xcode deploy.sh template with scheme auto-detection and build-number rollback
Adam Eivy9e0b06be8186
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e716f55691..27ace182a5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,7 @@## Added+- **Universal Xcode `deploy.sh` template — auto-detects schemes, defaults to every available platform** — the deploy script generator PortOS installs into Xcode projects (`generateDeployScript` in `server/services/xcodeScripts.js`) now produces a single universal template that auto-detects available schemes (trying both `TargetName`/`TargetName macOS`/`TargetName_Watch` and `TargetName_iOS`/`TargetName_macOS`/`TargetName_watchOS` candidates) so one template works across all naming conventions. The default (`./deploy.sh` with no flags) now fans out to every platform the project has a scheme for, keeping iOS + macOS + watchOS build numbers in lockstep on App Store Connect — previously it defaulted to iOS only and required `--all` to ship every platform. Serial uploads with a 60s inter-upload delay (via a shared helper that correctly sleeps between every successful upload in iOS↔macOS↔watchOS chains, not just before macOS). New **build-number rollback trap**: if any step after the build-number bump fails, the trap restores `project.yml` and `project.pbxproj` to their byte-exact pre-bump state, so a failed upload doesn't permanently consume a build number committed to main. `--transport DAV` on iOS/watchOS uploads for more reliable multipart handling. Shared `exportOptions.plist` across platforms (was duplicated three times). Explicit `--ios`/`--macos`/`--watch` flags hard-error on missing schemes; `--all` and the default silently skip missing ones. Existing per-project deploy.sh files are NEVER overwritten by `installScripts` — this new template only lands when installing into projects that don't already have one. `scaffoldXcode.js` README snippet updated to reflect the new defaults.+- **Opt-in HTTPS for managed apps via PortOS "Upgrade to TLS" action** — PortOS's own HTTPS+loopback-HTTP setup (previously inlined in `server/index.js`) is now a zero-dep helper module at `lib/tailscale-https.js` exporting `createTailscaleServers`, `watchCertReload`, and `hasTailscaleCert`. PortOS itself now uses the helper (dogfood). App schema gains an optional `tlsPort` field — when set, the Launch button on the app grid and detail view opens `https://<host>:<tlsPort>/` as the primary action (with plain HTTP demoted to a muted secondary button, and Dev UI still reachable when `devUiPort` is set). The PortOS baseline app auto-reflects `tlsPort: PORTS.API` whenever a cert is present on disk, so the Launch button targets the correct scheme out of the box. New app-manager action **Edit → Upgrade to TLS**: pick a TLS port (defaults to `uiPort + 1000`), PortOS copies `lib/tailscale-https.js` into the target app's repo at `<repoPath>/lib/tailscale-https.js` and records the `tlsPort` in `apps.json`; backend refuses overwrite unless the user clicks the "Overwrite existing" button that surfaces on collision. The response returns a preformatted snippet (with a copy button) showing how to wire the helper into the app's server entry — the wire-up is deliberately left to the user to avoid mis-patching arbitrary server files. The helper is zero-dep by design: apps that adopt it stay self-contained and runnable without PortOS. To share the single Tailscale Let's Encrypt cert across apps, each app points `CERT_DIR` at (or symlinks) `data/certs` in the PortOS install. New backend route `POST /api/apps/:id/upgrade-tls { tlsPort, force }` (409 `ALREADY_EXISTS` when a helper already lives in the target). Client launch URLs consolidated into `client/src/services/appUrls.js` (`getLaunchUrls`, `getPrimaryLaunchUrl`) so tile and detail views build URLs through one function. `apiCore.request()` now enriches thrown errors with `err.code` + `err.status` so callers can branch on server error codes.- **Cyber Muse CoS avatar — GLB-backed holographic head** — new `muse` option in Settings → CoS → Appearance. Rather than assembling sphere primitives into a face (uncanny) or displacing a sphere point cloud (unreadable silhouette), the avatar loads a user-supplied `data/avatar/model.glb` through a new `/api/avatar/model.glb` route (`server/routes/avatar.js`, HEAD + GET, 404 when missing, `model/gltf-binary` when present) and renders it with a holographic material treatment: dark base + state-colored emissive glow that pulses per CoS state (sleeping/thinking/coding/investigating/ideating) and sync-bobs when the CoS is speaking. Bounding-box auto-fit means any model scale/origin works — drop in a ~4MB Ready Player Me export, a Sketchfab head bust, or a Mixamo-rigged character and it centers + sizes itself. When no GLB is present, renders a clean empty-state card pointing at the target path. Piggybacks on `useGLTF` (drei) and reuses the existing Sparkles/halo/ground-glow chrome. Zod enum for `avatarStyle` gained `'muse'` in `server/routes/cosStatusRoutes.js`.diff --git a/server/routes/scaffoldXcode.js b/server/routes/scaffoldXcode.jsindex 5082653d4c..fda628f3fa 100644--- a/server/routes/scaffoldXcode.js+++ b/server/routes/scaffoldXcode.js@@ -422,10 +422,11 @@ xcodebuild test -project ${targetName}.xcodeproj -scheme ${targetName} \\Local deploy via \`./deploy.sh\`:\`\`\`bash-./deploy.sh # iOS only (default)+./deploy.sh # every platform the project has a scheme for (default)+./deploy.sh --ios # iOS only./deploy.sh --macos # macOS only-./deploy.sh --watch # watchOS only-./deploy.sh --all # all platforms+./deploy.sh --watch # watchOS only (standalone watch apps)+./deploy.sh --all # explicit "all available" (same as default)./deploy.sh --skip-tests # skip tests for faster iteration\`\`\`diff --git a/server/services/xcodeScripts.js b/server/services/xcodeScripts.jsindex 176890e550..bd594bcb92 100644--- a/server/services/xcodeScripts.js+++ b/server/services/xcodeScripts.js@@ -43,16 +43,34 @@ APPSTORE_API_PRIVATE_KEY_PATH="~/Library/Mobile Documents/com~apple~CloudDocs/Ap/*** Generate the generic deploy.sh script content.- * Supports --ios, --macos, --watch, --all, --skip-tests flags.- * Works with both XcodeGen (project.yml) and raw .xcodeproj projects.+ *+ * Produces a self-contained, universal TestFlight deployment script that:+ * - Supports --ios, --macos, --watch, --all, --skip-tests flags+ * - Defaults to every platform the project has a scheme for ("all available")+ * - Auto-detects scheme naming conventions (TargetName vs TargetName_iOS,+ * "TargetName macOS" vs TargetName_macOS, etc.)+ * - Works with both XcodeGen (project.yml) and raw .xcodeproj projects+ * - Rolls back the build-number bump if deploy fails, so a failed upload+ * doesn't permanently consume a build number+ * - Runs uploads serially with a 60s gap between each to avoid Apple's CDN+ * rejecting concurrent uploads from the same API key+ * - Greps altool output for DEFINITIVE failure banners only (never plain+ * "ERROR: " — altool emits normal multipart-retry events as ERROR lines)*/export function generateDeployScript(targetName, _bundleId) {return `#!/bin/bashset -euo pipefail# ${targetName} - Local TestFlight Deploy+## Usage: ./deploy.sh [--skip-tests] [--ios] [--macos] [--watch] [--all]-# Default (no platform flag): iOS only+#+# Default (no platform flag): every platform the project has a scheme for.+# --ios / --macos / --watch : single platform+# --all : explicit "all available" (same as default)+#+# Uploads are serial with a 60s gap between each to avoid Apple's CDN+# rejecting concurrent uploads from the same API key.SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd "$SCRIPT_DIR"@@ -76,7 +94,7 @@ if [ ! -f "$KEY_PATH" ]; thenexit 1fi-# Ensure altool can find the key (it only checks specific directories)+# altool only looks in ~/.private_keys/ for the API key — symlink it in.mkdir -p ~/.private_keysKEY_FILENAME="AuthKey_\${APPSTORE_API_KEY_ID}.p8"if [ ! -f ~/.private_keys/"$KEY_FILENAME" ]; then@@ -93,35 +111,99 @@ fiPROJECT="${targetName}.xcodeproj"BUILD_DIR="$SCRIPT_DIR/build"--# Parse flags+APP_NAME="${targetName}"++# Scheme name candidates. Auto-detected against \`xcodebuild -list\` so the+# same template works regardless of whether the project uses "TargetName" /+# "TargetName macOS" / "TargetName_Watch" (PortOS scaffold convention) or+# "TargetName_iOS" / "TargetName_macOS" / "TargetName_watchOS" (common+# hand-rolled convention).+SCHEME_IOS_CANDIDATES=("${targetName}" "${targetName}_iOS")+SCHEME_MACOS_CANDIDATES=("${targetName} macOS" "${targetName}_macOS")+SCHEME_WATCH_CANDIDATES=("${targetName}_Watch" "${targetName}_watchOS" "${targetName} watchOS")+TEST_BUNDLE_CANDIDATES=("${targetName}Tests" "${targetName}Tests_iOS")++AVAILABLE_SCHEMES=$(xcodebuild -project "$PROJECT" -list 2>/dev/null || true)+resolve_scheme() {+ local name+ for name in "$@"; do+ if echo "$AVAILABLE_SCHEMES" | grep -qxE "[[:space:]]*$name"; then+ echo "$name"+ return 0+ fi+ done+ return 1+}+SCHEME_IOS=$(resolve_scheme "\${SCHEME_IOS_CANDIDATES[@]}" || true)+SCHEME_MACOS=$(resolve_scheme "\${SCHEME_MACOS_CANDIDATES[@]}" || true)+SCHEME_WATCH=$(resolve_scheme "\${SCHEME_WATCH_CANDIDATES[@]}" || true)+SCHEME_TEST="$SCHEME_IOS" # tests always use iOS sim++HAS_IOS=false; [ -n "$SCHEME_IOS" ] && HAS_IOS=true+HAS_MACOS=false; [ -n "$SCHEME_MACOS" ] && HAS_MACOS=true+HAS_WATCH=false; [ -n "$SCHEME_WATCH" ] && HAS_WATCH=true++# Parse flags. Explicit per-platform flags are separate from the --all / default+# fan-out so we can hard-error on an explicit flag naming a missing scheme but+# silently skip missing schemes under --all.SKIP_TESTS=falseBUILD_IOS=falseBUILD_MACOS=falseBUILD_WATCH=false+EXPLICIT_IOS=false+EXPLICIT_MACOS=false+EXPLICIT_WATCH=false+FAN_OUT=falsefor arg in "$@"; docase "$arg" in--skip-tests) SKIP_TESTS=true ;;- --ios) BUILD_IOS=true ;;- --macos) BUILD_MACOS=true ;;- --watch) BUILD_WATCH=true ;;- --all) BUILD_IOS=true; BUILD_MACOS=true; BUILD_WATCH=true ;;+ --ios) EXPLICIT_IOS=true ;;+ --macos) EXPLICIT_MACOS=true ;;+ --watch) EXPLICIT_WATCH=true ;;+ --all) FAN_OUT=true ;;esacdone-# Default to iOS if no platform specified++if ! $EXPLICIT_IOS && ! $EXPLICIT_MACOS && ! $EXPLICIT_WATCH && ! $FAN_OUT; then+ FAN_OUT=true+fi+if $FAN_OUT; then+ $HAS_IOS && BUILD_IOS=true+ $HAS_MACOS && BUILD_MACOS=true+ $HAS_WATCH && BUILD_WATCH=true+fi+if $EXPLICIT_IOS; then $HAS_IOS || { echo "❌ No iOS scheme found (tried: \${SCHEME_IOS_CANDIDATES[*]})"; exit 1; }; BUILD_IOS=true; fi+if $EXPLICIT_MACOS; then $HAS_MACOS || { echo "❌ No macOS scheme found (tried: \${SCHEME_MACOS_CANDIDATES[*]})"; exit 1; }; BUILD_MACOS=true; fi+if $EXPLICIT_WATCH; then $HAS_WATCH || { echo "❌ No watchOS scheme found (tried: \${SCHEME_WATCH_CANDIDATES[*]})"; exit 1; }; BUILD_WATCH=true; fi+if ! $BUILD_IOS && ! $BUILD_MACOS && ! $BUILD_WATCH; then- BUILD_IOS=true+ echo "❌ No platforms to build — project has no recognized schemes."+ exit 1+fi++MSG="🎯 Deploying to:"+if $BUILD_IOS; then MSG="$MSG iOS"; fi+if $BUILD_MACOS; then MSG="$MSG macOS"; fi+if $BUILD_WATCH; then MSG="$MSG watchOS"; fi+echo "$MSG"++# Auto-increment build number. Snapshot the file(s) first so we can roll back+# on any failure and not permanently consume a build number that never shipped+# to TestFlight. Snapshot via cp rather than \`git checkout --\` so any+# pre-existing uncommitted edits in the operator's working tree are preserved.+ORIG_PBXPROJ=$(mktemp)+cp "$PROJECT/project.pbxproj" "$ORIG_PBXPROJ"+ORIG_PROJECT_YML=""+if [ "$PROJECT_MODE" = "xcodegen" ]; then+ ORIG_PROJECT_YML=$(mktemp)+ cp project.yml "$ORIG_PROJECT_YML"fi-# Auto-increment build numberif [ "$PROJECT_MODE" = "xcodegen" ]; thenCURRENT_BUILD=$(grep CURRENT_PROJECT_VERSION project.yml | head -1 | awk '{print $2}')NEW_BUILD=$((CURRENT_BUILD + 1))echo "📦 Build number: $CURRENT_BUILD → $NEW_BUILD"/usr/bin/sed -i '' "s/CURRENT_PROJECT_VERSION: \${CURRENT_BUILD}/CURRENT_PROJECT_VERSION: \${NEW_BUILD}/" project.yml-- echo "⚙️ Regenerating Xcode project..."- xcodegen generateelseCURRENT_BUILD=$(grep -m1 'CURRENT_PROJECT_VERSION = ' "$PROJECT/project.pbxproj" | awk '{print $3}' | tr -d ';')NEW_BUILD=$((CURRENT_BUILD + 1))@@ -129,66 +211,112 @@ else/usr/bin/sed -i '' "s/CURRENT_PROJECT_VERSION = \${CURRENT_BUILD};/CURRENT_PROJECT_VERSION = \${NEW_BUILD};/g" "$PROJECT/project.pbxproj"fi-# Run tests (unless skipped; only when building iOS since tests use iOS simulator)+DEPLOY_SUCCESS=false+rollback_build_bump() {+ if [ "$DEPLOY_SUCCESS" = "false" ]; then+ echo "↩️ Rolling back build number bump (deploy did not complete)..."+ cp "$ORIG_PBXPROJ" "$PROJECT/project.pbxproj" 2>/dev/null || true+ [ -n "$ORIG_PROJECT_YML" ] && cp "$ORIG_PROJECT_YML" project.yml 2>/dev/null || true+ fi+ rm -f "$ORIG_PBXPROJ"+ [ -n "$ORIG_PROJECT_YML" ] && rm -f "$ORIG_PROJECT_YML"+}+trap rollback_build_bump EXIT++if [ "$PROJECT_MODE" = "xcodegen" ]; then+ echo "⚙️ Regenerating Xcode project..."+ xcodegen generate+fi++# Tests run on iOS simulator, so only run them when we're actually building+# iOS. If the project is macOS-only or watch-only, skip tests.if ! $SKIP_TESTS && $BUILD_IOS; thenecho "🧪 Running tests..."- DESTINATION=$(- SIMINFO=$(xcrun simctl list devices available -j | python3 -c "+ DEVICE_ID=$(xcrun simctl list devices available -j | python3 -c "import json, sysdata = json.load(sys.stdin)+preferred = ['iPhone 17 Pro', 'iPhone 17', 'iPhone 16 Pro', 'iPhone 16', 'iPhone 15']+for name in preferred:+ for runtime, devices in data.get('devices', {}).items():+ for d in devices:+ if d['name'] == name and d.get('isAvailable', False):+ print(d['udid']); sys.exit(0)for runtime, devices in data.get('devices', {}).items():- if 'iOS' not in runtime:- continue- parts = runtime.replace('com.apple.CoreSimulator.SimRuntime.iOS-', '').split('-')- os_ver = '.'.join(parts)- for d in devices:- name = d.get('name', '')- if d.get('isAvailable') and 'iPhone 16' in name and 'Plus' not in name and 'Pro' not in name and 'e' != name[-1:]:- print(f'{name},{os_ver}')- sys.exit(0)-for runtime, devices in data.get('devices', {}).items():- if 'iOS' not in runtime:- continue- parts = runtime.replace('com.apple.CoreSimulator.SimRuntime.iOS-', '').split('-')- os_ver = '.'.join(parts)for d in devices:- if d.get('isAvailable') and 'iPhone' in d.get('name', ''):- print(f\\"{d['name']},{os_ver}\\")- sys.exit(0)+ if 'iPhone' in d['name'] and d.get('isAvailable', False):+ print(d['udid']); sys.exit(0)" 2>/dev/null)- SIM_NAME="\${SIMINFO%%,*}"- SIM_OS="\${SIMINFO##*,}"- if [ -n "$SIM_NAME" ] && [ -n "$SIM_OS" ]; then- echo "platform=iOS Simulator,name=$SIM_NAME,OS=$SIM_OS"- else- echo "platform=iOS Simulator,name=iPhone 16"+ if [ -z "$DEVICE_ID" ]; then+ echo "❌ No available iPhone simulator found for tests"+ exit 1+ fi+ DESTINATION="platform=iOS Simulator,id=$DEVICE_ID"+ echo "📱 Test destination: $DESTINATION"+ # Resolve test bundle name via xcodebuild -list targets, with candidate fallback+ TEST_BUNDLE=""+ AVAILABLE_TARGETS=$(xcodebuild -project "$PROJECT" -list 2>/dev/null || true)+ for candidate in "\${TEST_BUNDLE_CANDIDATES[@]}"; do+ if echo "$AVAILABLE_TARGETS" | grep -qxE "[[:space:]]*$candidate"; then+ TEST_BUNDLE="$candidate"; breakfi- )- xcodebuild test \\- -project "$PROJECT" \\- -scheme "${targetName}" \\- -only-testing:${targetName}Tests \\- -destination "$DESTINATION" \\- -configuration Debug \\- CODE_SIGNING_ALLOWED=NO \\- -quiet+ done+ TEST_ARGS=(-project "$PROJECT" -scheme "$SCHEME_TEST")+ [ -n "$TEST_BUNDLE" ] && TEST_ARGS+=(-only-testing:"$TEST_BUNDLE")+ TEST_ARGS+=(-destination "$DESTINATION" -configuration Debug CODE_SIGNING_ALLOWED=NO -quiet)+ xcodebuild test "\${TEST_ARGS[@]}"echo "✅ Tests passed"fi-# Clean build directoryrm -rf "$BUILD_DIR"+mkdir -p "$BUILD_DIR"-PLATFORMS_BUILT=0+# Shared export options plist (identical for all three platforms: automatic+# signing, app-store-connect method).+EXPORT_PLIST="$BUILD_DIR/exportOptions.plist"+cat > "$EXPORT_PLIST" <<EOF+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>method</key><string>app-store-connect</string>+ <key>teamID</key><string>$TEAM_ID</string>+ <key>signingStyle</key><string>automatic</string>+</dict>+</plist>+EOF++# altool exits 0 even when uploads fail — the failure is buried in its+# stdout XML-ish log. Grep the log for DEFINITIVE failure banners only.+#+# Do NOT grep plain "ERROR: " — altool emits normal multipart upload retry+# events as "ERROR: [ContentDelivery.Uploader...] WILL RETRY PART N" and+# "ERROR: The network connection was lost.", which Apple's uploader recovers+# from internally. Grepping those killed the script mid-recovery on good+# uploads. Use only Apple's terminal-failure banners:+# - "UPLOAD FAILED" : Apple's summary banner when retries exhausted+# - "Validation failed (" : server-side 4xx from App Store Connect+# - "ERROR ITMS-" : legacy Apple error code format+# - "product-errors" : Apple's structured error output+FAIL_MARKERS="UPLOAD FAILED|Validation failed \\(|ERROR ITMS-|product-errors"++UPLOADED_ONE=false+inter_upload_delay() {+ if $UPLOADED_ONE; then+ echo "⏳ Waiting 60s before next upload to avoid Apple CDN contention..."+ sleep 60+ fi+}# --- iOS Build & Upload ---if $BUILD_IOS; then- ARCHIVE_IOS="$BUILD_DIR/${targetName}_iOS.xcarchive"+ ARCHIVE_IOS="$BUILD_DIR/\${APP_NAME}_iOS.xcarchive"EXPORT_IOS="$BUILD_DIR/export_ios"echo "📦 Archiving iOS..."xcodebuild archive \\-project "$PROJECT" \\- -scheme "${targetName}" \\+ -scheme "$SCHEME_IOS" \\-configuration Release \\-destination 'generic/platform=iOS' \\-archivePath "$ARCHIVE_IOS" \\@@ -198,38 +326,25 @@ if $BUILD_IOS; then-quietecho "✅ iOS archive complete"- cat > "$BUILD_DIR/exportOptions_ios.plist" <<EOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>method</key><string>app-store-connect</string>- <key>teamID</key><string>$TEAM_ID</string>- <key>signingStyle</key><string>automatic</string>-</dict>-</plist>-EOF-echo "📤 Exporting iOS IPA..."xcodebuild -exportArchive \\-archivePath "$ARCHIVE_IOS" \\- -exportOptionsPlist "$BUILD_DIR/exportOptions_ios.plist" \\+ -exportOptionsPlist "$EXPORT_PLIST" \\-exportPath "$EXPORT_IOS" \\-allowProvisioningUpdates \\-authenticationKeyPath "$KEY_PATH" \\-authenticationKeyID "$APPSTORE_API_KEY_ID" \\-authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\-quiet- echo "✅ iOS IPA exported"- IPA_PATH="$EXPORT_IOS/${targetName}.ipa"- if [ ! -f "$IPA_PATH" ]; then- echo "❌ iOS IPA not found at $IPA_PATH"+ IPA_PATH=$(find "$EXPORT_IOS" -name "*.ipa" | head -1)+ if [ -z "$IPA_PATH" ]; then+ echo "❌ iOS IPA not found in $EXPORT_IOS"ls -la "$EXPORT_IOS/"exit 1fi+ inter_upload_delayecho "🚀 Uploading iOS to TestFlight..."IOS_UPLOAD_LOG="$BUILD_DIR/ios_upload.log"set +e@@ -241,31 +356,23 @@ EOF--transport DAV 2>&1 | tee "$IOS_UPLOAD_LOG"IOS_UPLOAD_STATUS=\${PIPESTATUS[0]}set -e- # Definitive failure markers only — plain "ERROR: " false-positives on- # altool's normal multipart retry events ("WILL RETRY PART N. Checksums- # do not match." / "The network connection was lost.").- if [ "$IOS_UPLOAD_STATUS" -ne 0 ] || grep -qE "UPLOAD FAILED|Validation failed \\(|ERROR ITMS-|product-errors" "$IOS_UPLOAD_LOG"; then+ if [ "$IOS_UPLOAD_STATUS" -ne 0 ] || grep -qE "$FAIL_MARKERS" "$IOS_UPLOAD_LOG"; thenecho "❌ iOS upload failed — see errors above"exit 1fiecho "✅ iOS upload complete!"- PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))-- if $BUILD_MACOS || $BUILD_WATCH; then- echo "⏳ Waiting 60s before next upload to avoid Apple CDN contention..."- sleep 60- fi+ UPLOADED_ONE=truefi# --- macOS Build & Upload ---if $BUILD_MACOS; then- ARCHIVE_MACOS="$BUILD_DIR/${targetName}_macOS.xcarchive"+ ARCHIVE_MACOS="$BUILD_DIR/\${APP_NAME}_macOS.xcarchive"EXPORT_MACOS="$BUILD_DIR/export_macos"echo "📦 Archiving macOS..."xcodebuild archive \\-project "$PROJECT" \\- -scheme "${targetName} macOS" \\+ -scheme "$SCHEME_MACOS" \\-configuration Release \\-destination 'generic/platform=macOS' \\-archivePath "$ARCHIVE_MACOS" \\@@ -276,30 +383,16 @@ if $BUILD_MACOS; then-quietecho "✅ macOS archive complete"- cat > "$BUILD_DIR/exportOptions_macos.plist" <<EOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>method</key><string>app-store-connect</string>- <key>teamID</key><string>$TEAM_ID</string>- <key>signingStyle</key><string>automatic</string>-</dict>-</plist>-EOF-echo "📤 Exporting macOS pkg..."xcodebuild -exportArchive \\-archivePath "$ARCHIVE_MACOS" \\- -exportOptionsPlist "$BUILD_DIR/exportOptions_macos.plist" \\+ -exportOptionsPlist "$EXPORT_PLIST" \\-exportPath "$EXPORT_MACOS" \\-allowProvisioningUpdates \\-authenticationKeyPath "$KEY_PATH" \\-authenticationKeyID "$APPSTORE_API_KEY_ID" \\-authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\-quiet- echo "✅ macOS pkg exported"PKG_PATH=$(find "$EXPORT_MACOS" -name "*.pkg" | head -1)if [ -z "$PKG_PATH" ]; then@@ -308,6 +401,7 @@ EOFexit 1fi+ inter_upload_delayecho "🚀 Uploading macOS to TestFlight..."MACOS_UPLOAD_LOG="$BUILD_DIR/macos_upload.log"set +e@@ -318,29 +412,25 @@ EOF--apiIssuer "$APPSTORE_ISSUER_ID" 2>&1 | tee "$MACOS_UPLOAD_LOG"MACOS_UPLOAD_STATUS=\${PIPESTATUS[0]}set -e- # See iOS section above for why we don't grep plain "ERROR: ".- if [ "$MACOS_UPLOAD_STATUS" -ne 0 ] || grep -qE "UPLOAD FAILED|Validation failed \\(|ERROR ITMS-|product-errors" "$MACOS_UPLOAD_LOG"; then+ if [ "$MACOS_UPLOAD_STATUS" -ne 0 ] || grep -qE "$FAIL_MARKERS" "$MACOS_UPLOAD_LOG"; thenecho "❌ macOS upload failed — see errors above"exit 1fiecho "✅ macOS upload complete!"- PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))-- if $BUILD_WATCH; then- echo "⏳ Waiting 60s before next upload to avoid Apple CDN contention..."- sleep 60- fi+ UPLOADED_ONE=truefi# --- watchOS Build & Upload ---+# Only applies to STANDALONE watch apps (no iOS companion). Watch extensions+# bundled with an iOS app ship inside the iOS IPA.if $BUILD_WATCH; then- ARCHIVE_WATCH="$BUILD_DIR/${targetName}_watchOS.xcarchive"+ ARCHIVE_WATCH="$BUILD_DIR/\${APP_NAME}_watchOS.xcarchive"EXPORT_WATCH="$BUILD_DIR/export_watchos"echo "📦 Archiving watchOS..."xcodebuild archive \\-project "$PROJECT" \\- -scheme "${targetName}_Watch" \\+ -scheme "$SCHEME_WATCH" \\-configuration Release \\-destination 'generic/platform=watchOS' \\-archivePath "$ARCHIVE_WATCH" \\@@ -351,71 +441,60 @@ if $BUILD_WATCH; then-quietecho "✅ watchOS archive complete"- cat > "$BUILD_DIR/exportOptions_watchos.plist" <<EOF-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>method</key><string>app-store-connect</string>- <key>teamID</key><string>$TEAM_ID</string>- <key>signingStyle</key><string>automatic</string>-</dict>-</plist>-EOF-echo "📤 Exporting watchOS..."xcodebuild -exportArchive \\-archivePath "$ARCHIVE_WATCH" \\- -exportOptionsPlist "$BUILD_DIR/exportOptions_watchos.plist" \\+ -exportOptionsPlist "$EXPORT_PLIST" \\-exportPath "$EXPORT_WATCH" \\-allowProvisioningUpdates \\-authenticationKeyPath "$KEY_PATH" \\-authenticationKeyID "$APPSTORE_API_KEY_ID" \\-authenticationKeyIssuerID "$APPSTORE_ISSUER_ID" \\-quiet- echo "✅ watchOS exported"- # watchOS is typically bundled with iOS, but standalone apps need separate upload- WCK_PATH=$(find "$EXPORT_WATCH" -name "*.ipa" | head -1)- if [ -n "$WCK_PATH" ]; then+ WATCH_IPA=$(find "$EXPORT_WATCH" -name "*.ipa" | head -1)+ if [ -z "$WATCH_IPA" ]; then+ echo "ℹ️ No standalone watchOS IPA (bundled with iOS app) — skipping upload"+ else+ inter_upload_delayecho "🚀 Uploading watchOS to TestFlight..."WATCH_UPLOAD_LOG="$BUILD_DIR/watchos_upload.log"set +e+ # altool --type for standalone watchOS is still "ios" (Apple types: ios, macos, appletvos, visionos)xcrun altool --upload-app \\- --file "$WCK_PATH" \\+ --file "$WATCH_IPA" \\--type ios \\--apiKey "$APPSTORE_API_KEY_ID" \\--apiIssuer "$APPSTORE_ISSUER_ID" \\--transport DAV 2>&1 | tee "$WATCH_UPLOAD_LOG"WATCH_UPLOAD_STATUS=\${PIPESTATUS[0]}set -e- # See iOS section above for why we don't grep plain "ERROR: ".- if [ "$WATCH_UPLOAD_STATUS" -ne 0 ] || grep -qE "UPLOAD FAILED|Validation failed \\(|ERROR ITMS-|product-errors" "$WATCH_UPLOAD_LOG"; then+ if [ "$WATCH_UPLOAD_STATUS" -ne 0 ] || grep -qE "$FAIL_MARKERS" "$WATCH_UPLOAD_LOG"; thenecho "❌ watchOS upload failed — see errors above"exit 1fiecho "✅ watchOS upload complete!"- else- echo "ℹ️ No standalone watchOS IPA (bundled with iOS app)"+ UPLOADED_ONE=truefi- PLATFORMS_BUILT=$((PLATFORMS_BUILT + 1))fi-echo "✅ Build $NEW_BUILD submitted to TestFlight ($PLATFORMS_BUILT platform(s))."+echo "✅ Build $NEW_BUILD submitted to TestFlight."-# Commit the build number bump (if in a git repo with changes)+# Commit the build-number bump only after every upload succeeds, so a failed+# deploy doesn't leave a consumed build number committed to main.if git rev-parse --is-inside-work-tree >/dev/null 2>&1; thenif [ "$PROJECT_MODE" = "xcodegen" ]; thengit add project.yml "$PROJECT/project.pbxproj" 2>/dev/null || trueelsegit add "$PROJECT/project.pbxproj" 2>/dev/null || truefi- git diff --cached --quiet || git commit -m "build: bump to build $NEW_BUILD"- echo "📝 Committed build number bump"+ if ! git diff --cached --quiet; then+ git commit -m "build: bump to build $NEW_BUILD"+ echo "📝 Committed build number bump"+ fifi+DEPLOY_SUCCESS=true-# Clean uprm -rf "$BUILD_DIR"echo "🧹 Cleaned build artifacts"`;