AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(release): start Xcode Cloud and submit iOS App Review automatically
tianma-if6173721c146a
diff --git a/.github/workflows/ios-xcode-cloud.yml b/.github/workflows/ios-xcode-cloud.ymlindex cc02fa4e..2f77734d 100644--- a/.github/workflows/ios-xcode-cloud.yml+++ b/.github/workflows/ios-xcode-cloud.yml@@ -12,7 +12,6 @@ on:- start- monitor- store-status- - submit-reviewdefault: inspectworkflow_id:description: Optional Xcode Cloud workflow ID; auto-selects a single enabled Archive workflow when empty@@ -26,7 +25,6 @@ on:description: App Store marketing version to inspectrequired: falsetype: string- default: "1.74.0"app_store_build_id:description: App Store Connect build resource ID to inspectrequired: false@@ -37,14 +35,17 @@ permissions:jobs:xcode-cloud:- if: github.repository == 'tianma-if/edgeever' && inputs.mode != 'submit-review'+ if: github.repository == 'tianma-if/edgeever'runs-on: ubuntu-latesttimeout-minutes: 90steps:+ - name: Check out Xcode Cloud tooling+ uses: actions/checkout@v5+- name: Install App Store Connect client dependenciesrun: python3 -m pip install --quiet PyJWT cryptography- - name: Inspect or start Xcode Cloud+ - name: Inspect, start, or monitor Xcode Cloudenv:ASC_APP_ID: "6792625631"ASC_API_ISSUER: ${{ secrets.EDGEEVER_APPLE_API_ISSUER }}@@ -56,320 +57,37 @@ jobs:APP_STORE_VERSION: ${{ inputs.app_store_version }}APP_STORE_BUILD_ID: ${{ inputs.app_store_build_id }}run: |- python3 - <<'PY'- import base64- import json- import os- import re- import time- import urllib.error- import urllib.parse- import urllib.request-- import jwt-- app_id = os.environ["ASC_APP_ID"]- issuer = os.environ["ASC_API_ISSUER"]- key_id = os.environ["ASC_API_KEY_ID"]- private_key = base64.b64decode(os.environ["ASC_API_KEY_BASE64"]).decode()- mode = os.environ["XCODE_CLOUD_MODE"]- requested_workflow_id = os.environ.get("XCODE_CLOUD_WORKFLOW_ID", "").strip()- build_run_id = os.environ.get("XCODE_CLOUD_BUILD_RUN_ID", "").strip()- store_version = os.environ.get("APP_STORE_VERSION", "").strip()- store_build_id = os.environ.get("APP_STORE_BUILD_ID", "").strip()-- token = None- token_exp = 0-- def ensure_token():- global token, token_exp- now = int(time.time())- if token and now < token_exp - 60:- return token- token_exp = now + 20 * 60- encoded = jwt.encode(- {"iss": issuer, "iat": now, "exp": token_exp, "aud": "appstoreconnect-v1"},- private_key,- algorithm="ES256",- headers={"kid": key_id, "typ": "JWT"},- )- token = encoded.decode() if isinstance(encoded, bytes) else encoded- return token-- def invalidate_token():- global token, token_exp- token = None- token_exp = 0-- def api(method, path, body=None, attempts=5):- last_error = None- for attempt in range(1, attempts + 1):- request = urllib.request.Request(- "https://api.appstoreconnect.apple.com" + path,- data=None if body is None else json.dumps(body).encode(),- method=method,- )- request.add_header("Authorization", f"Bearer {ensure_token()}")- if body is not None:- request.add_header("Content-Type", "application/json")- try:- with urllib.request.urlopen(request) as response:- payload = response.read().decode()- return json.loads(payload) if payload else {}- except urllib.error.HTTPError as error:- details = error.read().decode()- last_error = f"App Store Connect API {method} {path} failed ({error.code}): {details}"- if error.code in (401, 429, 500, 502, 503, 504) and attempt < attempts:- if error.code == 401:- invalidate_token()- print(f"{last_error} retrying {attempt}/{attempts - 1}", flush=True)- time.sleep(min(30, 2 ** attempt))- continue- raise SystemExit(last_error)- raise SystemExit(last_error or f"App Store Connect API {method} {path} failed")-- if mode == "monitor":- if not build_run_id:- raise SystemExit("build_run_id is required in monitor mode")- deadline = time.time() + 85 * 60- while True:- run = api("GET", f"/v1/ciBuildRuns/{build_run_id}")["data"]- attributes = run.get("attributes") or {}- progress = attributes.get("executionProgress")- completion = attributes.get("completionStatus")- print(- f"Xcode Cloud build #{attributes.get('number')} "- f"progress={progress} completion={completion}",- flush=True,- )- if progress == "COMPLETE":- actions = api(- "GET",- f"/v1/ciBuildRuns/{build_run_id}/actions?limit=200&"- "fields[ciBuildActions]=name,actionType,executionProgress,completionStatus,issueCounts",- )- for action in actions.get("data", []):- action_attributes = action.get("attributes") or {}- print(- f"- action={action_attributes.get('name')} "- f"type={action_attributes.get('actionType')} "- f"completion={action_attributes.get('completionStatus')} "- f"issues={action_attributes.get('issueCounts')}"- )- issues = api(- "GET",- f"/v1/ciBuildActions/{action['id']}/issues?limit=200&"- "fields%5BciIssues%5D=issueType,message,fileSource,category",- )- for issue in issues.get("data", []):- issue_attributes = issue.get("attributes") or {}- source = issue_attributes.get("fileSource") or {}- location = source.get("path") or ""- if source.get("lineNumber"):- location += f":{source['lineNumber']}"- print(- f" - issue={issue_attributes.get('issueType')} "- f"category={issue_attributes.get('category')} "- f"location={location} "- f"message={issue_attributes.get('message')}"- )- artifacts = api(- "GET",- f"/v1/ciBuildActions/{action['id']}/artifacts?limit=200&"- "fields%5BciArtifacts%5D=fileType,fileName,fileSize,downloadUrl",- )- for artifact in artifacts.get("data", []):- artifact_attributes = artifact.get("attributes") or {}- file_type = artifact_attributes.get("fileType")- file_name = artifact_attributes.get("fileName") or artifact["id"]- print(- f" - artifact={file_type} name={file_name} "- f"size={artifact_attributes.get('fileSize')}"- )- if file_type == "LOG_BUNDLE" and artifact_attributes.get("downloadUrl"):- output_directory = os.path.join(- os.environ["RUNNER_TEMP"], "xcode-cloud-logs"- )- os.makedirs(output_directory, exist_ok=True)- output_path = os.path.join(- output_directory, os.path.basename(file_name)- )- urllib.request.urlretrieve(- artifact_attributes["downloadUrl"], output_path- )- print(f" - downloaded log bundle to {output_path}")- builds = api(- "GET",- f"/v1/ciBuildRuns/{build_run_id}/builds?limit=50&"- "fields[builds]=version,processingState,uploadedDate",- )- for build in builds.get("data", []):- build_attributes = build.get("attributes") or {}- print(- f"- App Store build id={build.get('id')} "- f"version={build_attributes.get('version')} "- f"processing={build_attributes.get('processingState')} "- f"uploaded={build_attributes.get('uploadedDate')}"- )- if completion != "SUCCEEDED":- raise SystemExit(f"Xcode Cloud build completed with {completion}")- raise SystemExit(0)- if time.time() >= deadline:- raise SystemExit("Timed out waiting for Xcode Cloud build")- time.sleep(30)-- if mode == "store-status":- if not store_version or not store_build_id:- raise SystemExit("app_store_version and app_store_build_id are required in store-status mode")- version_query = urllib.parse.urlencode({- "filter[platform]": "IOS",- "filter[versionString]": store_version,- "fields[appStoreVersions]": "platform,versionString,appStoreState,releaseType,build",- "limit": 10,- })- versions = api("GET", f"/v1/apps/{app_id}/appStoreVersions?{version_query}")- print(f"App Store version records for {store_version}: {len(versions.get('data', []))}")- for version in versions.get("data", []):- attributes = version.get("attributes") or {}- print(- f"- version id={version.get('id')} state={attributes.get('appStoreState')} "- f"releaseType={attributes.get('releaseType')}"- )- try:- attached = api(- "GET",- f"/v1/appStoreVersions/{version['id']}/build?fields[builds]=version,processingState",- )- except SystemExit:- attached = {"data": None}- attached_data = attached.get("data") or {}- attached_attributes = attached_data.get("attributes") or {}- print(- f"- attached build id={attached_data.get('id')} "- f"version={attached_attributes.get('version')} "- f"processing={attached_attributes.get('processingState')}"- )- build = api(- "GET",- f"/v1/builds/{store_build_id}?fields[builds]=version,processingState,uploadedDate",- )["data"]- build_attributes = build.get("attributes") or {}- print(- f"Requested build id={build.get('id')} version={build_attributes.get('version')} "- f"processing={build_attributes.get('processingState')} "- f"uploaded={build_attributes.get('uploadedDate')}"- )- raise SystemExit(0)-- product = api("GET", f"/v1/apps/{app_id}/ciProduct").get("data")- workflows = []- for product in [product] if product else []:- product_id = product["id"]- query = urllib.parse.urlencode({- "limit": 50,- "fields[ciWorkflows]": "name,isEnabled,lastModifiedDate",- })- response = api("GET", f"/v1/ciProducts/{product_id}/workflows?{query}")- workflows.extend(response.get("data", []))-- if not workflows:- raise SystemExit("No Xcode Cloud workflows found for EdgeEver")-- print("Available Xcode Cloud workflows:")- for workflow in workflows:- attributes = workflow.get("attributes") or {}- print(- f"- id={workflow['id']} name={attributes.get('name')} "- f"enabled={attributes.get('isEnabled')} modified={attributes.get('lastModifiedDate')}"- )-- if mode == "inspect":- raise SystemExit(0)-- if requested_workflow_id:- matches = [workflow for workflow in workflows if workflow["id"] == requested_workflow_id]- else:- matches = [- workflow- for workflow in workflows- if (workflow.get("attributes") or {}).get("isEnabled")- and re.search(- r"archive|app\s*store|release",- str((workflow.get("attributes") or {}).get("name", "")),- re.IGNORECASE,- )- ]-- if len(matches) != 1:- raise SystemExit(- f"Expected exactly one matching enabled Archive workflow, found {len(matches)}; "- "rerun with workflow_id from the list above"- )-- workflow = matches[0]- result = api(- "POST",- "/v1/ciBuildRuns",- {- "data": {- "type": "ciBuildRuns",- "attributes": {},- "relationships": {- "workflow": {- "data": {"type": "ciWorkflows", "id": workflow["id"]}- }- },- }- },- )- build = result["data"]- attributes = build.get("attributes") or {}- print(- f"Started Xcode Cloud build id={build['id']} number={attributes.get('number')} "- f"status={attributes.get('executionProgress')}"- )- PY-- - name: Upload failed Xcode Cloud logs- if: failure() && inputs.mode == 'monitor'- uses: actions/upload-artifact@v4- with:- name: xcode-cloud-logs-${{ inputs.build_run_id }}- path: ${{ runner.temp }}/xcode-cloud-logs- if-no-files-found: warn- retention-days: 7-- submit-review:- if: github.repository == 'tianma-if/edgeever' && inputs.mode == 'submit-review'- runs-on: ubuntu-latest- timeout-minutes: 30- steps:- - name: Check out the submission source- uses: actions/checkout@v4-- - name: Set up Ruby- uses: ruby/setup-ruby@v1- with:- ruby-version: "3.3"-- - name: Install fastlane- run: gem install fastlane --no-document-- - name: Submit App Store build for review- env:- APP_STORE_BUILD_NUMBER: "49"- APP_STORE_CONNECT_API_ISSUER_ID: ${{ secrets.EDGEEVER_APPLE_API_ISSUER }}- APP_STORE_CONNECT_API_KEY_ID: ${{ secrets.EDGEEVER_APPLE_API_KEY_ID }}- APP_STORE_CONNECT_API_KEY_P8_BASE64: ${{ secrets.EDGEEVER_APPLE_API_KEY_BASE64 }}- APP_STORE_RELEASE_NOTES_ZH: |-- iOS 的数学公式、图片画廊和分隔线与网页编辑器对齐,笔记 Markdown 往返一致,货币金额中的美元符号也不会被误当成公式。- 应用内界面支持日文。- APP_STORE_RELEASE_NOTES_EN: |-- Keep iOS math formulas, image galleries, and merge dividers aligned with the Web editor so notes round-trip the same Markdown, including currency dollar signs.- Add Japanese as an in-app language.- APP_STORE_RELEASE_NOTES_JA: |-- iOS の数式、画像ギャラリー、区切り線を Web エディタと同じ文書構造に揃え、Markdown の往復を一致させ、通貨のドル記号も数式と誤認しません。- アプリ内の表示言語に日本語を追加しました。- APP_STORE_VERSION: ${{ inputs.app_store_version }}- run: fastlane ios submit_review- working-directory: apps/ios+ case "$XCODE_CLOUD_MODE" in+ inspect)+ python3 scripts/xcode-cloud-control.py inspect+ ;;+ start)+ args=(start --wait)+ if [[ -n "$XCODE_CLOUD_WORKFLOW_ID" ]]; then+ args+=(--workflow-id "$XCODE_CLOUD_WORKFLOW_ID")+ fi+ python3 scripts/xcode-cloud-control.py "${args[@]}"+ ;;+ monitor)+ if [[ -z "$XCODE_CLOUD_BUILD_RUN_ID" ]]; then+ echo "::error::build_run_id is required in monitor mode"+ exit 1+ fi+ python3 scripts/xcode-cloud-control.py wait \+ --build-run-id "$XCODE_CLOUD_BUILD_RUN_ID" \+ --wait-valid+ ;;+ store-status)+ if [[ -z "$APP_STORE_VERSION" || -z "$APP_STORE_BUILD_ID" ]]; then+ echo "::error::app_store_version and app_store_build_id are required in store-status mode"+ exit 1+ fi+ python3 scripts/xcode-cloud-control.py store-status \+ --version "$APP_STORE_VERSION" \+ --build-id "$APP_STORE_BUILD_ID"+ ;;+ *)+ echo "::error::Unsupported Xcode Cloud mode: $XCODE_CLOUD_MODE"+ exit 1+ ;;+ esacdiff --git a/.github/workflows/store-delivery.yml b/.github/workflows/store-delivery.ymlindex 7d3c7908..7c12e54e 100644--- a/.github/workflows/store-delivery.yml+++ b/.github/workflows/store-delivery.yml@@ -41,7 +41,7 @@ permissions:contents: writeconcurrency:- group: edgeever-store-delivery-${{ inputs.release_tag }}+ group: edgeever-store-delivery-${{ inputs.release_tag }}-${{ inputs.platform }}cancel-in-progress: falsejobs:@@ -275,7 +275,7 @@ jobs:}}name: Deliver App Store Connectruns-on: ubuntu-latest- timeout-minutes: 90+ timeout-minutes: 120environment: store-deliverysteps:- name: Check out the immutable Release target@@ -283,12 +283,64 @@ jobs:with:ref: ${{ needs.plan.outputs.release_target }}- - name: Require an Xcode Cloud build number+ - name: Check out current store-delivery tooling+ uses: actions/checkout@v5+ with:+ ref: ${{ github.sha }}+ path: .edgeever-ci++ - name: Resolve the App Store build+ id: ios_build+ env:+ ASC_APP_ID: "6792625631"+ ASC_API_ISSUER: ${{ secrets.EDGEEVER_APPLE_API_ISSUER }}+ ASC_API_KEY_ID: ${{ secrets.EDGEEVER_APPLE_API_KEY_ID }}+ ASC_API_KEY_BASE64: ${{ secrets.EDGEEVER_APPLE_API_KEY_BASE64 }}+ RELEASE_TAG: ${{ inputs.release_tag }}+ REQUESTED_BUILD_NUMBER: ${{ inputs.ios_build_number }}run: |- if [[ -z "${{ inputs.ios_build_number }}" ]]; then- echo "::error::iOS store delivery uses apps/ios via Xcode Cloud. Pass ios_build_number; do not build from apps/mobile or EAS."- exit 1+ if [[ -n "$REQUESTED_BUILD_NUMBER" ]]; then+ echo "build_number=$REQUESTED_BUILD_NUMBER" >> "$GITHUB_OUTPUT"+ echo "Using existing App Store Connect build $REQUESTED_BUILD_NUMBER"+ exit 0fi+ test -n "$ASC_API_ISSUER"+ test -n "$ASC_API_KEY_ID"+ test -n "$ASC_API_KEY_BASE64"+ python3 -m pip install --quiet PyJWT cryptography+ log_file="$RUNNER_TEMP/xcode-cloud-control.log"+ python3 .edgeever-ci/scripts/xcode-cloud-control.py start \+ --git-ref "refs/tags/${RELEASE_TAG}" \+ --require-sha "$(git rev-parse HEAD)" \+ --wait \+ --wait-valid |+ tee "$log_file"+ grep -E '^(build_number|app_store_build_id|build_run_id|source_sha|processing_state)=' \+ "$log_file" >> "$GITHUB_OUTPUT"+ test -n "$(grep -E '^build_number=' "$log_file")"++ - name: Load App Store release notes+ id: notes+ run: |+ node --input-type=module <<'NODE'+ import { appendFileSync, readFileSync } from "node:fs";++ const summary = JSON.parse(readFileSync("release-summary.json", "utf8"));+ const join = (items) =>+ (Array.isArray(items) ? items : [])+ .map((item) => String(item).trim())+ .filter(Boolean)+ .join("\n");+ const write = (key, value) => {+ appendFileSync(process.env.GITHUB_OUTPUT, `${key}<<EOF\n${value}\nEOF\n`);+ };+ write("notes_en", join(summary.changes?.["en-US"]));+ write("notes_zh", join(summary.changes?.["zh-CN"]));+ write(+ "notes_ja",+ join(summary.changes?.ja || summary.changes?.["ja-JP"]),+ );+ NODE- name: Set up Ruby and fastlaneuses: ruby/setup-ruby@v1@@ -299,16 +351,20 @@ jobs:- name: Submit the uploaded build to App Reviewenv:- APP_STORE_BUILD_NUMBER: ${{ inputs.ios_build_number }}+ APP_STORE_BUILD_NUMBER: ${{ steps.ios_build.outputs.build_number }}APP_STORE_CONNECT_API_ISSUER_ID: ${{ secrets.EDGEEVER_APPLE_API_ISSUER }}APP_STORE_CONNECT_API_KEY_ID: ${{ secrets.EDGEEVER_APPLE_API_KEY_ID }}APP_STORE_CONNECT_API_KEY_P8_BASE64: ${{ secrets.EDGEEVER_APPLE_API_KEY_BASE64 }}APP_STORE_VERSION: ${{ needs.plan.outputs.version }}+ APP_STORE_RELEASE_NOTES_EN: ${{ steps.notes.outputs.notes_en }}+ APP_STORE_RELEASE_NOTES_ZH: ${{ steps.notes.outputs.notes_zh }}+ APP_STORE_RELEASE_NOTES_JA: ${{ steps.notes.outputs.notes_ja }}PRECHECK_INCLUDE_IN_APP_PURCHASES: "false"run: |test -n "$APP_STORE_CONNECT_API_ISSUER_ID"test -n "$APP_STORE_CONNECT_API_KEY_ID"test -n "$APP_STORE_CONNECT_API_KEY_P8_BASE64"+ test -n "$APP_STORE_BUILD_NUMBER"log_file="$RUNNER_TEMP/edgeever-app-store-review.log"for attempt in {1..20}; doset +ediff --git a/.gitignore b/.gitignoreindex f1ef6a69..5df28a67 100644--- a/.gitignore+++ b/.gitignore@@ -7,6 +7,8 @@!.env.local-dev.examplenode_modules/+__pycache__/+*.py[cod].idea/dist/!packages/plugin-api/dist/diff --git a/apps/ios/README.md b/apps/ios/README.mdindex b68cca69..0f2d18c2 100644--- a/apps/ios/README.md+++ b/apps/ios/README.md@@ -2,7 +2,7 @@Native SwiftUI client for EdgeEver. This replaces the React Native / Expo iOS target.-**App Store binaries on macOS beta:** use **Xcode Cloud (manual)** — [`docs/ios-xcode-cloud.md`](../../docs/ios-xcode-cloud.md).+**App Store binaries on macOS beta:** use **Xcode Cloud** — [`docs/ios-xcode-cloud.md`](../../docs/ios-xcode-cloud.md). Formal Releases start Cloud through store-delivery.## Status@@ -87,9 +87,9 @@ xcrun simctl launch booted org.edgeever.mobile \## App Store archive-### Preferred: Xcode Cloud (manual only)+### Preferred: Xcode Cloud-If the Mac runs **macOS beta**, local archives are rejected by App Store Connect (**ITMS-90111**) even with release Xcode. Day-to-day development stays local; **only store / TestFlight binaries** should use **Xcode Cloud** (25 compute hours/month with Apple Developer Program).+If the Mac runs **macOS beta**, local archives are rejected by App Store Connect (**ITMS-90111**) even with release Xcode. Day-to-day development stays local; **only store / TestFlight binaries** should use **Xcode Cloud** (25 compute hours/month with Apple Developer Program). Formal Releases start Cloud through store-delivery; keep the Cloud workflow start condition **Manual** so git pushes do not consume hours.- Setup and workflow: **[`docs/ios-xcode-cloud.md`](../../docs/ios-xcode-cloud.md)**- Cloud hooks: `ci_scripts/ci_post_clone.sh` → `ci_pre_xcodebuild.sh` → `ci_post_xcodebuild.sh`diff --git a/docs/ios-xcode-cloud.md b/docs/ios-xcode-cloud.mdindex 15546514..95206cd0 100644--- a/docs/ios-xcode-cloud.md+++ b/docs/ios-xcode-cloud.md@@ -9,9 +9,9 @@ Local Macs on **macOS beta** stamp binaries with `BuildMachineOSBuild` from the| Work | Where || --- | --- || Day-to-day coding, Simulator, device debug | **Local Mac** (beta OS OK) |-| Archive / TestFlight / App Store binary | **Xcode Cloud only** (manual start) |+| Archive / TestFlight / App Store binary | **Xcode Cloud only** (started by store-delivery or a manual control workflow) |-Xcode Cloud is billed as **25 compute hours per month** with the Apple Developer Program. Start workflows **manually** so hours go only to real store submissions.+Xcode Cloud is billed as **25 compute hours per month** with the Apple Developer Program. Keep the Cloud workflow start condition **Manual** so git pushes do not consume hours; formal Releases start it through the App Store Connect API.Native store target: **`apps/ios`** (SwiftUI). Expo `apps/mobile` is not the iOS store path.@@ -29,7 +29,7 @@ Native store target: **`apps/ios`** (SwiftUI). Expo `apps/mobile` is not the iOS3. Product: **EdgeEver** (`org.edgeever.mobile`), repository `tianma-if/edgeever`.4. When asked for the project path in a monorepo, select **`apps/ios/EdgeEver.xcodeproj`**.5. **Workflow settings (important):**- - **Start condition:** **Manual** only — do **not** start on every git push / PR (saves the 25h quota).+ - **Start condition:** **Manual** only — do **not** start on every git push / PR (saves the 25h quota). Formal Releases start this workflow through the App Store Connect API.- **Actions:** **Archive** (scheme `EdgeEver`, platform iOS).- **Deployment preparation:** App Store Connect / App Store eligible (or TestFlight Internal Only).- **Xcode / macOS:** latest **release** — not a beta toolchain.@@ -80,6 +80,7 @@ Rules:| Path | Role || --- | --- |+| `scripts/xcode-cloud-control.py` | Start/monitor Cloud and wait until the App Store build is Valid || `apps/ios/ci_scripts/ci_post_clone.sh` | bun + XcodeGen + EditorBundle + `xcodegen generate` || `apps/ios/ci_scripts/ci_pre_xcodebuild.sh` | Stamp `CI_BUILD_NUMBER`; force Automatic signing || `apps/ios/ci_scripts/ci_post_xcodebuild.sh` | Upload App Store IPA via `altool` when secrets are set |@@ -89,22 +90,23 @@ Rules:## Routine: ship a store binary-1. Land the code on the branch Cloud tracks (usually `main`).-2. Bump `MARKETING_VERSION` when the user-facing version changes; ensure Cloud **next build number** > latest ASC build (`ensure-xcode-cloud-build-number.sh`).-3. Start the **manual** Archive workflow (Xcode or ASC → Xcode Cloud → Start Build).-4. Wait for Archive. Prefer a green run; if the run is red only because Development/Ad Hoc export failed, check that `ci_post_xcodebuild` still uploaded the App Store IPA (or download `ARCHIVE_EXPORT` and run `upload-app-store-ipa.sh`).-5. In ASC: wait until the build is **Valid**, attach it to the version, **Submit for Review**.+Formal Releases do this automatically when `apps/ios` or the shared editor+runtime changed: `bun run release` bumps `MARKETING_VERSION`, starts Xcode Cloud+for the Release tag, waits until the build is **Valid**, and submits App Review.- Optional (metadata already on ASC, binary already uploaded):+To retry or ship iOS without a new GitHub Release:- ```sh- cd apps/ios- APP_STORE_VERSION=X.Y.Z APP_STORE_BUILD_NUMBER=N \- APP_STORE_CONNECT_API_KEY_ID=... \- APP_STORE_CONNECT_API_ISSUER_ID=... \- APP_STORE_CONNECT_API_KEY_P8_BASE64=... \- fastlane ios submit_review- ```+```sh+bun run publish:stores -- --release vX.Y.Z --platform ios+```++Pass `--ios-build-number N` only when the IPA is already on App Store Connect.++Manual Cloud controls remain available from+`.github/workflows/ios-xcode-cloud.yml` (`inspect` / `start` / `monitor`). Keep+Cloud **next build number** above the latest ASC build+(`ensure-xcode-cloud-build-number.sh`) if a Cloud run stamps a too-low+`CFBundleVersion`.## Local archive (release macOS only)diff --git a/docs/mobile-build.md b/docs/mobile-build.mdindex 41c2a890..88d6c166 100644--- a/docs/mobile-build.md+++ b/docs/mobile-build.md@@ -141,7 +141,9 @@ repository.iOS is a SwiftUI app in `apps/ios`, using the same bundle identifier`org.edgeever.mobile`. Do not build or submit iOS from `apps/mobile` or EAS.-On macOS beta hosts, archives must go through Xcode Cloud. See+On macOS beta hosts, archives must go through Xcode Cloud. Formal Releases+start that Archive and submit App Review automatically when iOS runtime+changes are in the audited range. See[iOS Xcode Cloud](ios-xcode-cloud.md) and [Mobile Store Delivery](store-delivery.md).## EASdiff --git a/docs/release.md b/docs/release.mdindex 4a0221a3..3590c6e3 100644--- a/docs/release.md+++ b/docs/release.md@@ -73,12 +73,15 @@ actually needed.audits the public Tencent TCR image inside Tencent Cloud after the formalRelease is published. Its duration or failure does not block the GitHubRelease or return a published version to Draft.-- This command does not authorize or run mobile store delivery itself. After- Draft native assets are prepared, publication is blocked unless the Android- APK uses the Google Play app-signing certificate. If that gate fails, the- Release remains a Draft. Run+- After Draft native assets are prepared, publication is blocked unless the+ Android APK uses the Google Play app-signing certificate. If that gate fails,+ the Release remains a Draft. Run`bun run publish:stores -- --release vX.Y.Z --platform android --android-track production`- for that Draft, then rerun the original release command to resume. See+ for that Draft, then rerun the original release command to resume. When the+ audited range includes iOS runtime changes, the same command starts Xcode+ Cloud and submits App Review after GitHub publication. An iOS failure leaves+ the GitHub Release published; retry with+ `bun run publish:stores -- --release vX.Y.Z --platform ios`. See[Mobile Store Delivery](store-delivery.md).- After rebuilt desktop assets are uploaded to the Draft, the local releasecommand signs only `latest-windows.json`; the private key never enters GitHubdiff --git a/docs/release.zh-CN.md b/docs/release.zh-CN.mdindex e60a346c..62c6e458 100644--- a/docs/release.zh-CN.md+++ b/docs/release.zh-CN.md@@ -62,11 +62,14 @@ bun run release -- \- 独立工作流会把同一个已验证 Git 提交发送到 CNB;正式 Release 发布后,CNB在腾讯云侧异步构建并审计 TCR 公共镜像。其耗时或失败不会阻塞 GitHubRelease,也不会把已发布版本恢复为 Draft。-- 此命令不会自行授权或执行移动端商店交付。Draft 原生资产准备完成后,发布- 命令会强制核验 Android APK 是否使用 Google Play 应用签名证书;未通过时- 保持 Draft 并停止。此时先针对同一 Draft 执行+- Draft 原生资产准备完成后,发布命令会强制核验 Android APK 是否使用+ Google Play 应用签名证书;未通过时保持 Draft 并停止。此时先针对同一 Draft+ 执行`bun run publish:stores -- --release vX.Y.Z --platform android --android-track production`,- 再重新执行原发布命令续跑。详见+ 再重新执行原发布命令续跑。当审计范围内包含 iOS 运行时变化时,同一条命令+ 会在 GitHub 公开发布之后启动 Xcode Cloud 并提交 App Review。iOS 失败不会+ 把已经公开的 GitHub Release 恢复为 Draft;用+ `bun run publish:stores -- --release vX.Y.Z --platform ios` 重试即可。详见[移动端商店交付](store-delivery.zh-CN.md)。- 重建后的桌面资产上传到 Draft 后,本地发布命令只签署`latest-windows.json`,私钥不会进入 GitHub Actions。第二次桌面工作流会重新diff --git a/docs/store-delivery.md b/docs/store-delivery.mdindex f410c451..6cf35e7f 100644--- a/docs/store-delivery.md+++ b/docs/store-delivery.md@@ -2,13 +2,16 @@GitHub Releases and mobile store delivery are separate operations:-- `bun run release` creates and audits the GitHub Release, but does not itself- authorize access to Google Play or App Store Connect. Android assets cannot- be published until they pass the Play app-signing gate.-- `bun run publish:stores` dispatches a manual store-delivery workflow for a- matching Draft or an existing formal Release tag. When Android is rebuilt,- run it against the Draft so the Play-signed APK replaces the temporary- locally signed APK before publication.+- `bun run release` creates and audits the GitHub Release. Android assets cannot+ be published until they pass the Play app-signing gate. When the audited+ range includes iOS runtime changes, the same command also starts Xcode Cloud+ and submits the resulting build to App Review. An iOS failure leaves the+ GitHub Release published; retry with `bun run publish:stores`.+- `bun run publish:stores` dispatches a store-delivery workflow for a matching+ Draft or an existing formal Release tag. When Android is rebuilt, run it+ against the Draft so the Play-signed APK replaces the temporary locally+ signed APK before publication. Omit `--ios-build-number` to start Xcode Cloud;+ pass it only to submit an already uploaded App Store Connect build.- Store delivery is the authorization to submit. By default, Google Play usesthe Production track, while iOS continues from App Store Connect upload intoApp Review. Approved builds are released automatically.@@ -25,8 +28,11 @@ store build starts, it verifies that:- root and mobile app versions both match the Release tag;- Android `versionCode` increased.-A Release that reused the previous mobile binary is intentionally rejected. It-does not represent a new store binary and should not be uploaded again.+A Release that reused the previous store binary for the selected platform is+intentionally rejected. It does not represent a new store binary and should not+be uploaded again. Android delivery requires `apps/mobile` runtime changes and+an increased `versionCode`. iOS delivery requires `apps/ios` or shared editor+runtime changes and `MARKETING_VERSION` equal to the Release tag.The publication gate accepts only `ANDROID_PLAY_APP_SIGNER_SHA256`. An APKsigned by the local upload certificate may temporarily exist in a Draft for@@ -71,12 +77,19 @@ Follow the official## Commands-Submit both platforms to Google Play Production and Apple App Review:+Submit both platforms to Google Play Production and Apple App Review when+both runtimes changed:```shbun run publish:stores -- --release v1.7.0```+Deliver only iOS, starting Xcode Cloud for the Release tag:++```sh+bun run publish:stores -- --release v1.7.0 --platform ios+```+Prepare the Android Play-signed asset for a Draft before formal publication:```sh@@ -124,15 +137,15 @@ explicitly requested.### App Store ConnectNative iOS store binaries come from **`apps/ios`** (SwiftUI), not Expo EAS.-On macOS beta hosts, archives must go through **Xcode Cloud** (manual Archive-workflow) so `BuildMachineOSBuild` is a release OS image — see-[iOS Xcode Cloud](ios-xcode-cloud.md). Cloud stamps `CFBundleVersion` from the-product’s next build number; `ci_post_xcodebuild.sh` uploads the App Store IPA-with an App Store Connect API key when shared environment secrets are set.-Fastlane (`apps/ios` `submit_review`) then selects the exact app version and-build number, submits App Review, and configures automatic release after-approval. Missing metadata, agreements, review information, or credentials-cause the workflow to fail without submitting a different build.+On macOS beta hosts, archives must go through **Xcode Cloud** so+`BuildMachineOSBuild` is a release OS image — see+[iOS Xcode Cloud](ios-xcode-cloud.md). The store-delivery workflow starts that+Archive workflow for the Release tag, waits until App Store Connect marks the+build Valid, then Fastlane (`apps/ios` `submit_review`) submits App Review and+configures automatic release after approval. Pass `--ios-build-number` only to+reuse an already uploaded build. Missing metadata, agreements, review+information, or credentials cause the workflow to fail without submitting a+different build.Store listing localizations (including Japanese) live in`apps/mobile/store-assets/` and are pasted in App Store Connect and Playdiff --git a/docs/store-delivery.zh-CN.md b/docs/store-delivery.zh-CN.mdindex 73204dce..cbcd1c68 100644--- a/docs/store-delivery.zh-CN.md+++ b/docs/store-delivery.zh-CN.md@@ -2,11 +2,14 @@GitHub Release 与移动端商店交付是两个独立操作:-- `bun run release` 创建并审计 GitHub Release,但不会自行授权访问 Google Play- 或 App Store Connect。Android 资产只有通过 Play 应用签名门禁后才能正式发布。+- `bun run release` 创建并审计 GitHub Release。Android 资产只有通过 Play+ 应用签名门禁后才能正式发布。当审计范围内包含 iOS 运行时变化时,同一条命令+ 还会启动 Xcode Cloud,并把得到的构建提交 App Review。iOS 失败不会把已经+ 公开的 GitHub Release 恢复为 Draft;用 `bun run publish:stores` 重试即可。- `bun run publish:stores` 针对一个匹配的 Draft 或已经存在的正式 Release tag,- 触发手动商店交付工作流。Android 重建时应在 Draft 阶段执行,以便正式发布前- 用 Play 签名 APK 替换临时的本地签名 APK。+ 触发商店交付工作流。Android 重建时应在 Draft 阶段执行,以便正式发布前用+ Play 签名 APK 替换临时的本地签名 APK。省略 `--ios-build-number` 会启动+ Xcode Cloud;只有提交已经上传到 App Store Connect 的构建时才传入该参数。- 触发商店交付就代表已经授权正式提交。默认情况下,Google Play 使用Production 轨道;iOS 在上传 App Store Connect 后继续提交 App Review。审核通过后自动发布。@@ -21,8 +24,10 @@ GitHub Release 与移动端商店交付是两个独立操作:- 根版本和移动端 App 版本都与 Release tag 一致;- Android `versionCode` 已递增。-如果某个 Release 复用了上一版移动端二进制,工作流会主动拒绝。它不代表新的-商店二进制,不应重复上传。+如果某个 Release 对所选平台复用了上一版商店二进制,工作流会主动拒绝。它不+代表新的商店二进制,不应重复上传。Android 交付要求 `apps/mobile` 运行时变化+且 `versionCode` 递增;iOS 交付要求 `apps/ios` 或共享编辑器运行时变化,且+`MARKETING_VERSION` 与 Release tag 一致。正式发布门禁只接受 `ANDROID_PLAY_APP_SIGNER_SHA256`。本地上传证书签名的 APK可以暂存在 Draft 中供商店处理,但不能成为正式 Release 的最终 Android 资产;@@ -62,12 +67,18 @@ EAS Submit 要求应用已经在对应商店中创建;Google Play API 提交## 命令-同时提交 Google Play Production 和 Apple App Review:+当两个运行时都有变化时,同时提交 Google Play Production 和 Apple App Review:```shbun run publish:stores -- --release v1.7.0```+只交付 iOS,并为该 Release tag 启动 Xcode Cloud:++```sh+bun run publish:stores -- --release v1.7.0 --platform ios+```+在正式发布前为 Draft 准备 Android Play 签名资产:```sh@@ -111,14 +122,13 @@ Release。默认命令直接使用 Production;只有明确要求测试交付### App Store Connect原生 iOS 商店二进制来自 **`apps/ios`**(SwiftUI),不再走 Expo EAS。-在 macOS beta 本机上,Archive 必须通过 **Xcode Cloud**(仅手动触发的 Archive-工作流),保证 `BuildMachineOSBuild` 来自正式系统镜像——见-[iOS Xcode Cloud](ios-xcode-cloud.md)。Cloud 用产品「下一个构建版本编号」写入-`CFBundleVersion`;配置共享环境变量后,`ci_post_xcodebuild.sh` 会用-App Store Connect API Key 上传 App Store IPA。随后 Fastlane(`apps/ios` 的-`submit_review`)精确选择相同的 App Version 与 Build Number,提交 App Review,-并设置为审核通过后自动发布。元数据、协议、审核信息或凭据不完整时工作流会失败,-不会改为提交其他构建。+在 macOS beta 本机上,Archive 必须通过 **Xcode Cloud**,保证+`BuildMachineOSBuild` 来自正式系统镜像——见+[iOS Xcode Cloud](ios-xcode-cloud.md)。商店交付工作流会针对 Release tag 启动+该 Archive,等到 App Store Connect 将构建标为 Valid,再用 Fastlane(`apps/ios`+的 `submit_review`)提交 App Review,并设置为审核通过后自动发布。只有复用已经+上传的构建时才传入 `--ios-build-number`。元数据、协议、审核信息或凭据不完整时+工作流会失败,不会改为提交其他构建。商店列表本地化(含日文)存放在 `apps/mobile/store-assets/`,需在 App StoreConnect 和 Play Console 中粘贴发布。在控制台补齐该语言的必填字段之前,不要把diff --git a/package.json b/package.jsonindex 96bbefb1..2a1e8424 100644--- a/package.json+++ b/package.json@@ -59,7 +59,7 @@"build:desktop": "EDGE_EVER_DESKTOP_BUILD=1 bun run prepare:desktop:icons && bun run build:web && bun run build:desktop:sidecar && bun run --cwd apps/desktop dist","benchmark:desktop:sidecar": "bun scripts/benchmark-desktop-sidecar.mjs","verify:web-performance": "bun scripts/verify-web-performance.mjs",- "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/create-mac-update-metadata.test.mjs scripts/windows-update-metadata.test.mjs scripts/linux-update-release.test.mjs scripts/desktop-build-workflow.test.mjs scripts/pe-imports.test.mjs scripts/report-native-build-timings.test.mjs scripts/release.test.mjs scripts/validate-store-delivery.test.mjs scripts/store-delivery.test.mjs scripts/download-play-universal-apk.test.mjs scripts/verify-android-apk-signature.test.mjs scripts/desktop-icns.test.mjs scripts/verify-desktop-cross-version-startup.test.mjs scripts/preview-macos-dock-icon.test.mjs apps/web/src/lib/version-check.test.mjs apps/mobile/src/lib/mobile-release.test.ts",+ "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/create-mac-update-metadata.test.mjs scripts/windows-update-metadata.test.mjs scripts/linux-update-release.test.mjs scripts/desktop-build-workflow.test.mjs scripts/pe-imports.test.mjs scripts/report-native-build-timings.test.mjs scripts/release.test.mjs scripts/validate-store-delivery.test.mjs scripts/store-delivery.test.mjs scripts/xcode-cloud-control.test.mjs scripts/download-play-universal-apk.test.mjs scripts/verify-android-apk-signature.test.mjs scripts/desktop-icns.test.mjs scripts/verify-desktop-cross-version-startup.test.mjs scripts/preview-macos-dock-icon.test.mjs apps/web/src/lib/version-check.test.mjs apps/mobile/src/lib/mobile-release.test.ts","release": "bun scripts/release.mjs","publish:stores": "bun scripts/store-delivery.mjs","test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs",diff --git a/scripts/plan-native-release.mjs b/scripts/plan-native-release.mjsindex 4225b051..457f4cd3 100644--- a/scripts/plan-native-release.mjs+++ b/scripts/plan-native-release.mjs@@ -3,7 +3,7 @@ import { resolve } from "node:path";import { fileURLToPath } from "node:url";export const planNativeRelease = (platform, changedFiles) => {- if (!["mobile", "desktop"].includes(platform)) {+ if (!["mobile", "desktop", "ios"].includes(platform)) {throw new Error(`Unsupported native release platform: ${platform}`);}@@ -27,14 +27,16 @@ export const planNativeRelease = (platform, changedFiles) => {const relevantPrefixes =platform === "mobile"? ["apps/mobile/", "packages/client/", "packages/shared/"]- : [- "apps/desktop/",- "apps/web/",- "crates/desktop-sidecar/",- "migrations/",- "packages/client/",- "packages/shared/",- ];+ : platform === "ios"+ ? ["apps/ios/", "packages/shared/"]+ : [+ "apps/desktop/",+ "apps/web/",+ "crates/desktop-sidecar/",+ "migrations/",+ "packages/client/",+ "packages/shared/",+ ];const relevantFiles =platform === "mobile"@@ -48,6 +50,8 @@ export const planNativeRelease = (platform, changedFiles) => {"scripts/verify-android-apk-signature.mjs",...mobileOnlyDependencyPatches,])+ : platform === "ios"+ ? new Set(): new Set([".cargo/config.toml",".github/workflows/desktop-build.yml",@@ -85,9 +89,9 @@ export const planNativeRelease = (platform, changedFiles) => {const run = () => {const [platform, baseRef, headRef] = process.argv.slice(2);- if (!["mobile", "desktop"].includes(platform) || !baseRef || !headRef) {+ if (!["mobile", "desktop", "ios"].includes(platform) || !baseRef || !headRef) {console.error(- "Usage: node scripts/plan-native-release.mjs <mobile|desktop> <base-ref> <head-ref>",+ "Usage: node scripts/plan-native-release.mjs <mobile|desktop|ios> <base-ref> <head-ref>",);process.exit(1);}diff --git a/scripts/plan-native-release.test.mjs b/scripts/plan-native-release.test.mjsindex f9df009a..981cde1e 100644--- a/scripts/plan-native-release.test.mjs+++ b/scripts/plan-native-release.test.mjs@@ -95,6 +95,32 @@ describe("native release planning", () => {).toEqual({ rebuild: false, relevantChanges: [] });});+ test("rebuilds iOS for the native client or shared editor runtime", () => {+ expect(+ planNativeRelease("ios", [+ "apps/ios/EdgeEver/App/RootView.swift",+ "packages/shared/src/index.ts",+ "apps/mobile/src/screens/LoginScreen.tsx",+ ]),+ ).toEqual({+ rebuild: true,+ relevantChanges: [+ "apps/ios/EdgeEver/App/RootView.swift",+ "packages/shared/src/index.ts",+ ],+ });+ });++ test("does not rebuild iOS for Android-only or documentation changes", () => {+ expect(+ planNativeRelease("ios", [+ "apps/mobile/src/screens/LoginScreen.tsx",+ "apps/ios/README.md",+ "package.json",+ ]),+ ).toEqual({ rebuild: false, relevantChanges: [] });+ });+test("rebuilds desktop when bundled sidecar migrations change", () => {expect(planNativeRelease("desktop", [diff --git a/scripts/release.mjs b/scripts/release.mjsindex f01a633a..8bb1a272 100644--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -50,6 +50,7 @@ export const RELEASE_VALIDATIONS = ["scripts/release.test.mjs","scripts/validate-store-delivery.test.mjs","scripts/store-delivery.test.mjs",+ "scripts/xcode-cloud-control.test.mjs","scripts/download-play-universal-apk.test.mjs","scripts/desktop-icns.test.mjs","scripts/verify-desktop-cross-version-startup.test.mjs",@@ -532,7 +533,26 @@ const assertReleasePreconditions = ({ repository, previousTag }) => {}};-const updateReleaseVersions = ({ nextVersion, desktopRebuild, mobileRebuild, changesEn, changesZh, localizedChanges }) => {+export const updateIosMarketingVersion = (contents, nextVersion) => {+ const updated = String(contents).replace(+ /^MARKETING_VERSION\s*=\s*.+$/m,+ `MARKETING_VERSION = ${nextVersion}`,+ );+ if (!new RegExp(`^MARKETING_VERSION\\s*=\\s*${nextVersion}$`, "m").test(updated)) {+ throw new Error("Unable to update apps/ios/Config/Version.xcconfig MARKETING_VERSION.");+ }+ return updated;+};++const updateReleaseVersions = ({+ nextVersion,+ desktopRebuild,+ mobileRebuild,+ iosRebuild,+ changesEn,+ changesZh,+ localizedChanges,+}) => {const changedPaths = ["package.json", "release-summary.json"];const rootPackage = readJson("package.json");rootPackage.version = nextVersion;@@ -558,6 +578,15 @@ const updateReleaseVersions = ({ nextVersion, desktopRebuild, mobileRebuild, chawriteJson("apps/mobile/app.json", mobileConfig);changedPaths.push("apps/mobile/app.json");}++ if (iosRebuild) {+ const iosVersionPath = "apps/ios/Config/Version.xcconfig";+ writeFileSync(+ iosVersionPath,+ updateIosMarketingVersion(readFileSync(iosVersionPath, "utf8"), nextVersion),+ );+ changedPaths.push(iosVersionPath);+ }return changedPaths;};@@ -639,6 +668,7 @@ const CHECKPOINT_RUN_FIELDS = ["dockerRunId","storeRunId","storeRecoveryRunId",+ "iosStoreRunId","androidPlaySignatureRunId","windowsUpdateAuditRunId",];@@ -646,6 +676,7 @@ const CANCELLABLE_CHECKPOINT_RUN_FIELDS = new Set(["desktopRunId","mobileRunId","dockerRunId",+ "iosStoreRunId","androidPlaySignatureRunId","windowsUpdateAuditRunId",]);@@ -917,7 +948,10 @@ const dispatchStoreDeliveryWorkflow = ({repository,tag,headSha,- recoverPlayApk,+ recoverPlayApk = false,+ platform = "android",+ androidTrack = "production",+ iosBuildNumber = "",}) => dispatchReleaseWorkflow({repository,workflow: RELEASE_WORKFLOWS.storeDelivery,@@ -925,9 +959,10 @@ const dispatchStoreDeliveryWorkflow = ({headSha,inputs: {release_tag: tag,- platform: "android",- android_track: "production",+ platform,+ android_track: androidTrack,recover_play_apk: recoverPlayApk,+ ios_build_number: iosBuildNumber,},});@@ -1041,6 +1076,51 @@ const ensurePlayDelivery = async ({}};+const startIosStoreDelivery = async ({+ repository,+ tag,+ headSha,+ checkpoint,+ persistCheckpoint,+}) => {+ let iosStoreRunId = checkpoint.iosStoreRunId;+ if (iosStoreRunId) {+ const existing = viewWorkflowRun({ repository, runId: iosStoreRunId });+ if (existing.headSha === headSha) {+ if (existing.status !== "completed") {+ console.log(`[release] reusing App Store delivery: ${existing.url}`);+ return iosStoreRunId;+ }+ if (existing.conclusion === "success") {+ console.log(`[release] App Store delivery already succeeded: ${existing.url}`);+ return iosStoreRunId;+ }+ console.log(`[release] rerunning failed App Store delivery: ${existing.url}`);+ run("gh", [+ "run",+ "rerun",+ String(iosStoreRunId),+ "--repo",+ repository,+ "--failed",+ ]);+ await waitForRerunStart({ repository, runId: iosStoreRunId });+ return iosStoreRunId;+ }+ }++ iosStoreRunId = await dispatchStoreDeliveryWorkflow({+ repository,+ tag,+ headSha,+ platform: "ios",+ });+ recordCheckpointRun(checkpoint, "iosStoreRunId", iosStoreRunId);+ persistCheckpoint();+ console.log("[release] started App Store delivery");+ return iosStoreRunId;+};+const requirePlaySignedDraftApk = async ({repository,tag,@@ -1390,10 +1470,12 @@ const releaseMain = async (options) => {printReleaseCoverageAudit({ audit: commitCoverageAudit, changesEn: options.changesEn });const desktopPlan = planNativeRelease("desktop", changedFiles);const mobilePlan = planNativeRelease("mobile", changedFiles);+ const iosPlan = planNativeRelease("ios", changedFiles);console.log(`[release] ${releaseBaseTag} -> ${tag}`);console.log(`[release] desktop: ${desktopPlan.rebuild ? "rebuild" : "reuse"}`);console.log(`[release] Android: ${mobilePlan.rebuild ? "rebuild" : "reuse"}`);+ console.log(`[release] iOS: ${iosPlan.rebuild ? "rebuild" : "reuse"}`);if (options.dryRun) {console.log(buildReleaseNotes({@@ -1447,6 +1529,7 @@ const releaseMain = async (options) => {nextVersion: releaseVersion,desktopRebuild: desktopPlan.rebuild,mobileRebuild: mobilePlan.rebuild,+ iosRebuild: iosPlan.rebuild,changesEn: options.changesEn,changesZh: options.changesZh,localizedChanges: options.localizedChanges,@@ -1561,6 +1644,16 @@ const releaseMain = async (options) => {resolveDraftRun("dockerRunId", RELEASE_WORKFLOWS.docker, "Draft Docker image"),]);+ if (iosPlan.rebuild) {+ await startIosStoreDelivery({+ repository: options.repository,+ tag,+ headSha: releaseSha,+ checkpoint,+ persistCheckpoint,+ });+ }+const androidReleaseReady = (async () => {await waitForRun({repository: options.repository,@@ -1735,6 +1828,22 @@ const releaseMain = async (options) => {throw error;}+ if (iosPlan.rebuild) {+ try {+ await waitForRun({+ repository: options.repository,+ runId: checkpoint.iosStoreRunId,+ label: "App Store delivery",+ });+ } catch (error) {+ console.error(+ "[release] GitHub Release is published; App Store delivery failed and must be retried with bun run publish:stores -- --release "+ + `${tag} --platform ios`,+ );+ throw error;+ }+ }+run("gh", ["issue","comment",diff --git a/scripts/release.test.mjs b/scripts/release.test.mjsindex c6d89604..91824b65 100644--- a/scripts/release.test.mjs+++ b/scripts/release.test.mjs@@ -10,6 +10,7 @@ import {draftRunResumeAction,nextVersion,parseReleaseCheckpoint,+ updateIosMarketingVersion,parseReleaseArgs,playDeliveryResumeAction,playDeliveryFailureStrategy,@@ -95,6 +96,33 @@ describe("release automation", () => {expect(playDelivery).toBeLessThan(allDraftGates);});+ test("starts App Store delivery from the native iOS tree without blocking GitHub publication", () => {+ const releaseSource = readFileSync(new URL("./release.mjs", import.meta.url), "utf8");+ const iosPlan = releaseSource.indexOf('planNativeRelease("ios"');+ const iosDispatch = releaseSource.indexOf("startIosStoreDelivery(");+ const publication = releaseSource.indexOf('"--draft=false"');+ const iosWait = releaseSource.indexOf('label: "App Store delivery"');+ const restoreDraft = releaseSource.lastIndexOf('"--draft=true"');++ expect(iosPlan).toBeGreaterThan(0);+ expect(iosDispatch).toBeGreaterThan(iosPlan);+ expect(iosDispatch).toBeLessThan(publication);+ expect(iosWait).toBeGreaterThan(publication);+ expect(iosWait).toBeGreaterThan(restoreDraft);+ expect(releaseSource).toContain('platform: "ios"');+ expect(releaseSource).toContain("iosRebuild: iosPlan.rebuild");+ expect(releaseSource).toContain("updateIosMarketingVersion");+ });++ test("rewrites the iOS marketing version onto the Release tag", () => {+ expect(+ updateIosMarketingVersion(+ "// comment\nMARKETING_VERSION = 1.74.0\nCURRENT_PROJECT_VERSION = 49\n",+ "1.79.0",+ ),+ ).toContain("MARKETING_VERSION = 1.79.0");+ });+test("restores an exact Draft checkpoint without exposing it in Issue text", () => {const checkpoint = { releaseSha: "abc", desktopRunId: 123 };const body = `<!-- edgeever-release-checkpoint:v1.42.0\n${JSON.stringify(checkpoint)}\n-->`;diff --git a/scripts/store-delivery.mjs b/scripts/store-delivery.mjsindex 810bb43a..a924108b 100644--- a/scripts/store-delivery.mjs+++ b/scripts/store-delivery.mjs@@ -14,7 +14,7 @@ Options:--platform <target> android, ios, or both (default: both)--android-track <track> production, alpha, beta, or internal (default: production)--recover-play-apk Skip Play upload and recover its already signed APK- --ios-build-number <number> Submit an existing App Store Connect build without rebuilding+ --ios-build-number <number> Submit an existing App Store Connect build; omit to start Xcode Cloud--repository <owner/name> GitHub repository (default: ${DEFAULT_REPOSITORY})--dry-run Print the workflow dispatch plan--help Show this helpdiff --git a/scripts/store-delivery.test.mjs b/scripts/store-delivery.test.mjsindex 1ab618f0..48fbe36c 100644--- a/scripts/store-delivery.test.mjs+++ b/scripts/store-delivery.test.mjs@@ -72,7 +72,18 @@ describe("store delivery command", () => {expect(workflow).not.toContain("--platform ios");expect(workflow).toContain("working-directory: apps/ios");expect(workflow).toContain(- "APP_STORE_BUILD_NUMBER: ${{ inputs.ios_build_number }}",+ "group: edgeever-store-delivery-${{ inputs.release_tag }}-${{ inputs.platform }}",+ );+ expect(workflow).toContain(".edgeever-ci/scripts/xcode-cloud-control.py");+ expect(workflow).toContain("--wait-valid");+ expect(workflow).toContain("grep -E '^(build_number|app_store_build_id|build_run_id|source_sha|processing_state)='");+ expect(workflow).toContain('refs/tags/${RELEASE_TAG}');+ expect(workflow).toContain(+ "APP_STORE_BUILD_NUMBER: ${{ steps.ios_build.outputs.build_number }}",+ );+ expect(workflow).toContain("APP_STORE_RELEASE_NOTES_EN:");+ expect(workflow).not.toContain(+ "Pass ios_build_number; do not build from apps/mobile or EAS.",);expect(workflow).toContain("APP_STORE_CONNECT_API_ISSUER_ID: ${{ secrets.EDGEEVER_APPLE_API_ISSUER }}",diff --git a/scripts/validate-store-delivery.mjs b/scripts/validate-store-delivery.mjsindex 65ced9eb..8fc73ce7 100644--- a/scripts/validate-store-delivery.mjs+++ b/scripts/validate-store-delivery.mjs@@ -8,10 +8,19 @@ const STABLE_RELEASE_TAG = /^v(\d+\.\d+\.\d+)$/;const PLATFORMS = new Set(["android", "ios", "both"]);const ANDROID_TRACKS = new Set(["internal", "alpha", "beta", "production"]);+export const readIosMarketingVersion = (text) => {+ const match = String(text).match(/^MARKETING_VERSION\s*=\s*(\S+)/m);+ if (!match) {+ throw new Error("apps/ios/Config/Version.xcconfig is missing MARKETING_VERSION.");+ }+ return match[1];+};+export const validateStoreDelivery = ({releaseTag,rootVersion,mobileVersion,+ iosVersion,currentVersionCode,previousVersionCode,changedFiles,@@ -28,31 +37,57 @@ export const validateStoreDelivery = ({if (!PLATFORMS.has(platform)) {throw new Error(`Unsupported store platform: ${platform}`);}-- const mobilePlan = planNativeRelease("mobile", changedFiles);- if (!mobilePlan.rebuild) {- throw new Error(- `${releaseTag} contains no mobile runtime changes; keep the existing store binary.`,- );+ if (rootVersion !== version) {+ throw new Error(`${releaseTag} requires package.json version to equal ${version}.`);}- if (rootVersion !== version || mobileVersion !== version) {- throw new Error(- `${releaseTag} requires package.json and apps/mobile/app.json versions to both equal ${version}.`,- );++ const relevantChanges = [];+ const deliverAndroid = platform === "android" || platform === "both";+ const deliverIos = platform === "ios" || platform === "both";++ if (deliverAndroid) {+ const mobilePlan = planNativeRelease("mobile", changedFiles);+ if (!mobilePlan.rebuild) {+ throw new Error(+ `${releaseTag} contains no Android runtime changes; keep the existing store binary.`,+ );+ }+ if (mobileVersion !== version) {+ throw new Error(+ `${releaseTag} requires apps/mobile/app.json version to equal ${version}.`,+ );+ }+ if (+ !Number.isInteger(currentVersionCode) ||+ !Number.isInteger(previousVersionCode) ||+ currentVersionCode <= previousVersionCode+ ) {+ throw new Error(+ `Android versionCode must increase beyond ${previousVersionCode}; received ${currentVersionCode}.`,+ );+ }+ relevantChanges.push(...mobilePlan.relevantChanges);}- if (- !Number.isInteger(currentVersionCode) ||- !Number.isInteger(previousVersionCode) ||- currentVersionCode <= previousVersionCode- ) {- throw new Error(- `Android versionCode must increase beyond ${previousVersionCode}; received ${currentVersionCode}.`,- );++ if (deliverIos) {+ const iosPlan = planNativeRelease("ios", changedFiles);+ if (!iosPlan.rebuild) {+ throw new Error(+ `${releaseTag} contains no iOS runtime changes; keep the existing App Store binary.`,+ );+ }+ if (iosVersion !== version) {+ throw new Error(+ `${releaseTag} requires apps/ios/Config/Version.xcconfig MARKETING_VERSION to equal ${version}.`,+ );+ }+ relevantChanges.push(...iosPlan.relevantChanges);}+return {version,- versionCode: currentVersionCode,- relevantChanges: mobilePlan.relevantChanges,+ versionCode: deliverAndroid ? currentVersionCode : previousVersionCode,+ relevantChanges,};};@@ -84,10 +119,14 @@ const run = () => {const previousMobileConfig = JSON.parse(git("show", `${previousTag}:apps/mobile/app.json`),);+ const iosVersion = readIosMarketingVersion(+ readFileSync("apps/ios/Config/Version.xcconfig", "utf8"),+ );const result = validateStoreDelivery({releaseTag,rootVersion: rootPackage.version,mobileVersion: mobileConfig.expo.version,+ iosVersion,currentVersionCode: mobileConfig.expo.android.versionCode,previousVersionCode: previousMobileConfig.expo.android.versionCode,changedFiles,diff --git a/scripts/validate-store-delivery.test.mjs b/scripts/validate-store-delivery.test.mjsindex da4c7c18..27e13717 100644--- a/scripts/validate-store-delivery.test.mjs+++ b/scripts/validate-store-delivery.test.mjs@@ -5,15 +5,16 @@ const validInput = {releaseTag: "v1.7.0",rootVersion: "1.7.0",mobileVersion: "1.7.0",+ iosVersion: "1.7.0",currentVersionCode: 57,previousVersionCode: 56,changedFiles: ["apps/mobile/src/screens/WorkspaceScreen.tsx"],- platform: "both",+ platform: "android",androidTrack: "production",};describe("store delivery validation", () => {- test("accepts a mobile release with increasing versions", () => {+ test("accepts an Android release with increasing versions", () => {expect(validateStoreDelivery(validInput)).toEqual({version: "1.7.0",versionCode: 57,@@ -21,19 +22,74 @@ describe("store delivery validation", () => {});});- test("rejects releases that reuse the existing mobile binary", () => {+ test("accepts an iOS release when the native client changed", () => {+ expect(+ validateStoreDelivery({+ ...validInput,+ platform: "ios",+ changedFiles: ["apps/ios/EdgeEver/App/RootView.swift"],+ }),+ ).toEqual({+ version: "1.7.0",+ versionCode: 56,+ relevantChanges: ["apps/ios/EdgeEver/App/RootView.swift"],+ });+ });++ test("accepts a combined delivery when both runtimes changed", () => {+ expect(+ validateStoreDelivery({+ ...validInput,+ platform: "both",+ changedFiles: [+ "apps/mobile/src/screens/WorkspaceScreen.tsx",+ "apps/ios/EdgeEver/App/RootView.swift",+ ],+ }),+ ).toEqual({+ version: "1.7.0",+ versionCode: 57,+ relevantChanges: [+ "apps/mobile/src/screens/WorkspaceScreen.tsx",+ "apps/ios/EdgeEver/App/RootView.swift",+ ],+ });+ });++ test("rejects Android delivery that reuses the existing mobile binary", () => {expect(() =>validateStoreDelivery({...validInput,changedFiles: ["apps/web/src/app/App.tsx"],})- ).toThrow("contains no mobile runtime changes");+ ).toThrow("contains no Android runtime changes");});- test("requires release and mobile versions to match", () => {+ test("rejects iOS delivery that reuses the existing App Store binary", () => {+ expect(() =>+ validateStoreDelivery({+ ...validInput,+ platform: "ios",+ changedFiles: ["apps/mobile/src/screens/WorkspaceScreen.tsx"],+ })+ ).toThrow("contains no iOS runtime changes");+ });++ test("requires the Android app version to match the Release tag", () => {expect(() =>validateStoreDelivery({ ...validInput, mobileVersion: "1.6.99" })- ).toThrow("versions to both equal 1.7.0");+ ).toThrow("apps/mobile/app.json version to equal 1.7.0");+ });++ test("requires the iOS marketing version to match the Release tag", () => {+ expect(() =>+ validateStoreDelivery({+ ...validInput,+ platform: "ios",+ iosVersion: "1.6.99",+ changedFiles: ["apps/ios/EdgeEver/App/RootView.swift"],+ })+ ).toThrow("MARKETING_VERSION to equal 1.7.0");});test("requires Android versionCode to increase", () => {diff --git a/scripts/xcode-cloud-control.py b/scripts/xcode-cloud-control.pynew file mode 100644index 00000000..b4ad8b08--- /dev/null+++ b/scripts/xcode-cloud-control.py@@ -0,0 +1,539 @@+#!/usr/bin/env python3+"""Start, monitor, and resolve Xcode Cloud App Store builds."""++from __future__ import annotations++import argparse+import base64+import json+import os+import re+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+++DEFAULT_APP_ID = "6792625631"+API_ROOT = "https://api.appstoreconnect.apple.com"+++def emit(key: str, value) -> None:+ if value is None or value == "":+ return+ print(f"{key}={value}", flush=True)+++def load_jwt():+ try:+ import jwt # type: ignore+ return jwt+ except ImportError:+ import subprocess++ subprocess.check_call(+ [sys.executable, "-m", "pip", "install", "PyJWT", "cryptography", "-q"],+ stdout=subprocess.DEVNULL,+ )+ import jwt # type: ignore++ return jwt+++class AppStoreConnect:+ def __init__(self) -> None:+ self.app_id = os.environ.get("ASC_APP_ID", DEFAULT_APP_ID).strip()+ self.issuer = os.environ["ASC_API_ISSUER"]+ self.key_id = os.environ["ASC_API_KEY_ID"]+ raw_key = os.environ.get("ASC_API_KEY_BASE64", "").strip()+ if not raw_key:+ raise SystemExit("ASC_API_KEY_BASE64 is required")+ self.private_key = base64.b64decode(raw_key).decode()+ self.jwt = load_jwt()+ self.token = None+ self.token_exp = 0++ def ensure_token(self) -> str:+ now = int(time.time())+ if self.token and now < self.token_exp - 60:+ return self.token+ self.token_exp = now + 20 * 60+ encoded = self.jwt.encode(+ {+ "iss": self.issuer,+ "iat": now,+ "exp": self.token_exp,+ "aud": "appstoreconnect-v1",+ },+ self.private_key,+ algorithm="ES256",+ headers={"kid": self.key_id, "typ": "JWT"},+ )+ self.token = encoded.decode() if isinstance(encoded, bytes) else encoded+ return self.token++ def invalidate_token(self) -> None:+ self.token = None+ self.token_exp = 0++ def request(self, method: str, path_or_url: str, body=None, attempts: int = 5):+ url = (+ path_or_url+ if path_or_url.startswith("http")+ else API_ROOT + path_or_url+ )+ last_error = None+ for attempt in range(1, attempts + 1):+ request = urllib.request.Request(+ url,+ data=None if body is None else json.dumps(body).encode(),+ method=method,+ )+ request.add_header("Authorization", f"Bearer {self.ensure_token()}")+ if body is not None:+ request.add_header("Content-Type", "application/json")+ try:+ with urllib.request.urlopen(request) as response:+ payload = response.read().decode()+ return json.loads(payload) if payload else {}+ except urllib.error.HTTPError as error:+ details = error.read().decode()+ last_error = (+ f"App Store Connect API {method} {path_or_url} "+ f"failed ({error.code}): {details}"+ )+ if error.code in (401, 429, 500, 502, 503, 504) and attempt < attempts:+ if error.code == 401:+ self.invalidate_token()+ print(+ f"{last_error} retrying {attempt}/{attempts - 1}",+ flush=True,+ )+ time.sleep(min(30, 2 ** attempt))+ continue+ raise SystemExit(last_error)+ raise SystemExit(last_error or f"App Store Connect API {method} {path_or_url} failed")++ def collect(self, path: str) -> list:+ items = []+ next_path = path+ while next_path:+ payload = self.request("GET", next_path)+ items.extend(payload.get("data") or [])+ next_path = (payload.get("links") or {}).get("next")+ return items+++def source_sha(run: dict) -> str:+ attributes = run.get("attributes") or {}+ commit = attributes.get("sourceCommit") or {}+ if isinstance(commit, dict):+ return str(commit.get("commitSha") or "")+ return ""+++def select_archive_workflow(client: AppStoreConnect, workflow_id: str = "") -> dict:+ product = client.request("GET", f"/v1/apps/{client.app_id}/ciProduct").get("data")+ if not product:+ raise SystemExit("No Xcode Cloud product found for EdgeEver")+ workflows = client.collect(+ f"/v1/ciProducts/{product['id']}/workflows?"+ + urllib.parse.urlencode(+ {"limit": 50, "fields[ciWorkflows]": "name,isEnabled,lastModifiedDate"}+ )+ )+ if not workflows:+ raise SystemExit("No Xcode Cloud workflows found for EdgeEver")+ if workflow_id:+ matches = [workflow for workflow in workflows if workflow["id"] == workflow_id]+ else:+ matches = [+ workflow+ for workflow in workflows+ if (workflow.get("attributes") or {}).get("isEnabled")+ and re.search(+ r"archive|app\s*store|release",+ str((workflow.get("attributes") or {}).get("name", "")),+ re.IGNORECASE,+ )+ ]+ if len(matches) != 1:+ listing = "\n".join(+ f"- id={workflow['id']} name={(workflow.get('attributes') or {}).get('name')} "+ f"enabled={(workflow.get('attributes') or {}).get('isEnabled')}"+ for workflow in workflows+ )+ raise SystemExit(+ f"Expected exactly one matching enabled Archive workflow, found {len(matches)}.\n"+ f"{listing}"+ )+ return matches[0]+++def list_git_references(client: AppStoreConnect, workflow_id: str) -> list:+ repository = client.request(+ "GET",+ f"/v1/ciWorkflows/{workflow_id}/repository",+ ).get("data")+ if not repository:+ raise SystemExit(f"Xcode Cloud workflow {workflow_id} has no repository")+ return client.collect(+ f"/v1/scmRepositories/{repository['id']}/gitReferences?limit=200"+ )+++def canonical_git_ref(value: str) -> str:+ value = value.strip()+ if value.startswith("refs/"):+ return value+ if re.fullmatch(r"v\d+\.\d+\.\d+", value):+ return f"refs/tags/{value}"+ return f"refs/heads/{value}"+++def find_git_reference(references: list, git_ref: str) -> dict | None:+ wanted = canonical_git_ref(git_ref)+ for reference in references:+ attributes = reference.get("attributes") or {}+ if attributes.get("isDeleted"):+ continue+ canonical = str(attributes.get("canonicalName") or "")+ name = str(attributes.get("name") or "")+ if canonical == wanted or name == git_ref or f"refs/tags/{name}" == wanted:+ return reference+ if f"refs/heads/{name}" == wanted:+ return reference+ return None+++def resolve_git_reference(+ client: AppStoreConnect,+ workflow_id: str,+ git_ref: str,+ retries: int = 8,+) -> dict:+ last_names = []+ for attempt in range(1, retries + 1):+ references = list_git_references(client, workflow_id)+ last_names = [+ str((item.get("attributes") or {}).get("canonicalName") or "")+ for item in references+ ]+ match = find_git_reference(references, git_ref)+ if match:+ return match+ if attempt < retries:+ print(+ f"Xcode Cloud does not yet list {git_ref}; retrying {attempt}/{retries - 1}",+ flush=True,+ )+ time.sleep(min(30, 5 * attempt))+ sample = ", ".join(name for name in last_names[:12] if name)+ raise SystemExit(+ f"Xcode Cloud git reference {git_ref} was not found. Known refs: {sample}"+ )+++def start_build(client: AppStoreConnect, workflow_id: str, git_reference_id: str | None) -> dict:+ relationships = {+ "workflow": {"data": {"type": "ciWorkflows", "id": workflow_id}},+ }+ if git_reference_id:+ relationships["sourceBranchOrTag"] = {+ "data": {"type": "scmGitReferences", "id": git_reference_id}+ }+ result = client.request(+ "POST",+ "/v1/ciBuildRuns",+ {+ "data": {+ "type": "ciBuildRuns",+ "attributes": {},+ "relationships": relationships,+ }+ },+ )+ build = result.get("data")+ if not build:+ raise SystemExit(f"Xcode Cloud did not return a build run: {result}")+ return build+++def read_build_run(client: AppStoreConnect, build_run_id: str) -> dict:+ return client.request(+ "GET",+ f"/v1/ciBuildRuns/{build_run_id}?"+ + urllib.parse.urlencode(+ {+ "fields[ciBuildRuns]": (+ "number,executionProgress,completionStatus,sourceCommit,"+ "isPullRequestBuild,startReason"+ )+ }+ ),+ )["data"]+++def wait_for_cloud_build(+ client: AppStoreConnect,+ build_run_id: str,+ require_sha: str,+ timeout_seconds: int,+) -> dict:+ deadline = time.time() + timeout_seconds+ sha_checked = False+ while True:+ run = read_build_run(client, build_run_id)+ attributes = run.get("attributes") or {}+ progress = attributes.get("executionProgress")+ completion = attributes.get("completionStatus")+ sha = source_sha(run)+ print(+ f"Xcode Cloud build #{attributes.get('number')} "+ f"progress={progress} completion={completion} sha={sha or 'pending'}",+ flush=True,+ )+ if require_sha and sha:+ if sha != require_sha:+ raise SystemExit(+ f"Xcode Cloud source commit {sha} does not match required {require_sha}."+ )+ sha_checked = True+ if progress == "COMPLETE":+ if require_sha and not sha_checked:+ raise SystemExit(+ f"Xcode Cloud build finished without a source commit; required {require_sha}."+ )+ if completion != "SUCCEEDED":+ describe_failed_run(client, build_run_id)+ raise SystemExit(f"Xcode Cloud build completed with {completion}")+ return run+ if time.time() >= deadline:+ raise SystemExit("Timed out waiting for Xcode Cloud build")+ time.sleep(30)+++def describe_failed_run(client: AppStoreConnect, build_run_id: str) -> None:+ actions = client.request(+ "GET",+ f"/v1/ciBuildRuns/{build_run_id}/actions?limit=200&"+ "fields[ciBuildActions]=name,actionType,executionProgress,completionStatus,issueCounts",+ )+ for action in actions.get("data", []):+ action_attributes = action.get("attributes") or {}+ print(+ f"- action={action_attributes.get('name')} "+ f"type={action_attributes.get('actionType')} "+ f"completion={action_attributes.get('completionStatus')} "+ f"issues={action_attributes.get('issueCounts')}",+ flush=True,+ )+++def wait_for_app_store_build(+ client: AppStoreConnect,+ build_run_id: str,+ timeout_seconds: int,+) -> dict:+ deadline = time.time() + timeout_seconds+ while True:+ payload = client.request(+ "GET",+ f"/v1/ciBuildRuns/{build_run_id}/builds?limit=50&"+ "fields[builds]=version,processingState,uploadedDate",+ )+ builds = payload.get("data") or []+ if builds:+ build = builds[0]+ attributes = build.get("attributes") or {}+ state = attributes.get("processingState")+ print(+ f"App Store build id={build.get('id')} version={attributes.get('version')} "+ f"processing={state} uploaded={attributes.get('uploadedDate')}",+ flush=True,+ )+ if state == "VALID":+ return build+ if state in {"INVALID", "FAILED"}:+ raise SystemExit(+ f"App Store Connect rejected build {attributes.get('version')} ({state})."+ )+ else:+ print(+ "App Store Connect has not attached a build to the Xcode Cloud run yet.",+ flush=True,+ )+ if time.time() >= deadline:+ raise SystemExit(+ "Timed out waiting for a VALID App Store Connect build. "+ "Confirm Xcode Cloud shared ASC API secrets so ci_post_xcodebuild can upload the IPA."+ )+ time.sleep(30)+++def print_run_outputs(run: dict, store_build: dict | None = None) -> None:+ attributes = run.get("attributes") or {}+ emit("build_run_id", run.get("id"))+ emit("cloud_number", attributes.get("number"))+ emit("source_sha", source_sha(run))+ if store_build:+ store_attributes = store_build.get("attributes") or {}+ emit("app_store_build_id", store_build.get("id"))+ emit("build_number", store_attributes.get("version"))+ emit("processing_state", store_attributes.get("processingState"))+++def command_inspect(client: AppStoreConnect) -> None:+ product = client.request("GET", f"/v1/apps/{client.app_id}/ciProduct").get("data")+ if not product:+ raise SystemExit("No Xcode Cloud product found for EdgeEver")+ workflows = client.collect(+ f"/v1/ciProducts/{product['id']}/workflows?"+ + urllib.parse.urlencode(+ {"limit": 50, "fields[ciWorkflows]": "name,isEnabled,lastModifiedDate"}+ )+ )+ print("Available Xcode Cloud workflows:")+ for workflow in workflows:+ attributes = workflow.get("attributes") or {}+ print(+ f"- id={workflow['id']} name={attributes.get('name')} "+ f"enabled={attributes.get('isEnabled')} modified={attributes.get('lastModifiedDate')}"+ )+++def command_start(args: argparse.Namespace, client: AppStoreConnect) -> None:+ workflow = select_archive_workflow(client, args.workflow_id)+ workflow_id = workflow["id"]+ emit("workflow_id", workflow_id)+ emit("workflow_name", (workflow.get("attributes") or {}).get("name"))+ git_reference_id = None+ if args.git_ref:+ reference = resolve_git_reference(client, workflow_id, args.git_ref)+ git_reference_id = reference["id"]+ emit(+ "git_ref",+ (reference.get("attributes") or {}).get("canonicalName"),+ )+ run = start_build(client, workflow_id, git_reference_id)+ attributes = run.get("attributes") or {}+ print(+ f"Started Xcode Cloud build id={run['id']} number={attributes.get('number')} "+ f"status={attributes.get('executionProgress')}",+ flush=True,+ )+ emit("build_run_id", run["id"])+ if args.wait or args.wait_valid:+ run = wait_for_cloud_build(+ client,+ run["id"],+ args.require_sha,+ args.timeout_seconds,+ )+ store_build = None+ if args.wait_valid:+ store_build = wait_for_app_store_build(+ client,+ run["id"],+ args.valid_timeout_seconds,+ )+ print_run_outputs(run, store_build)+++def command_wait(args: argparse.Namespace, client: AppStoreConnect) -> None:+ run = wait_for_cloud_build(+ client,+ args.build_run_id,+ args.require_sha,+ args.timeout_seconds,+ )+ store_build = None+ if args.wait_valid:+ store_build = wait_for_app_store_build(+ client,+ args.build_run_id,+ args.valid_timeout_seconds,+ )+ print_run_outputs(run, store_build)+++def command_store_status(args: argparse.Namespace, client: AppStoreConnect) -> None:+ if not args.version or not args.build_id:+ raise SystemExit("store-status requires --version and --build-id")+ version_query = urllib.parse.urlencode(+ {+ "filter[platform]": "IOS",+ "filter[versionString]": args.version,+ "fields[appStoreVersions]": "platform,versionString,appStoreState,releaseType,build",+ "limit": 10,+ }+ )+ versions = client.request("GET", f"/v1/apps/{client.app_id}/appStoreVersions?{version_query}")+ print(f"App Store version records for {args.version}: {len(versions.get('data', []))}")+ for version in versions.get("data", []):+ attributes = version.get("attributes") or {}+ print(+ f"- version id={version.get('id')} state={attributes.get('appStoreState')} "+ f"releaseType={attributes.get('releaseType')}"+ )+ build = client.request(+ "GET",+ f"/v1/builds/{args.build_id}?fields[builds]=version,processingState,uploadedDate",+ )["data"]+ attributes = build.get("attributes") or {}+ print(+ f"Requested build id={build.get('id')} version={attributes.get('version')} "+ f"processing={attributes.get('processingState')} "+ f"uploaded={attributes.get('uploadedDate')}"+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="command", required=True)++ sub.add_parser("inspect", help="List Xcode Cloud workflows")++ start = sub.add_parser("start", help="Start the Archive workflow")+ start.add_argument("--workflow-id", default="")+ start.add_argument("--git-ref", default="", help="Tag, branch, or refs/* name")+ start.add_argument("--require-sha", default="")+ start.add_argument("--wait", action="store_true")+ start.add_argument("--wait-valid", action="store_true")+ start.add_argument("--timeout-seconds", type=int, default=85 * 60)+ start.add_argument("--valid-timeout-seconds", type=int, default=25 * 60)++ wait = sub.add_parser("wait", help="Monitor an existing Xcode Cloud build")+ wait.add_argument("--build-run-id", required=True)+ wait.add_argument("--require-sha", default="")+ wait.add_argument("--wait-valid", action="store_true")+ wait.add_argument("--timeout-seconds", type=int, default=85 * 60)+ wait.add_argument("--valid-timeout-seconds", type=int, default=25 * 60)++ status = sub.add_parser("store-status", help="Inspect an App Store version/build")+ status.add_argument("--version", required=True)+ status.add_argument("--build-id", required=True)+ return parser+++def main(argv: list[str] | None = None) -> None:+ args = build_parser().parse_args(argv)+ client = AppStoreConnect()+ if args.command == "inspect":+ command_inspect(client)+ return+ if args.command == "start":+ command_start(args, client)+ return+ if args.command == "wait":+ command_wait(args, client)+ return+ if args.command == "store-status":+ command_store_status(args, client)+ return+ raise SystemExit(f"Unsupported command: {args.command}")+++if __name__ == "__main__":+ main()diff --git a/scripts/xcode-cloud-control.test.mjs b/scripts/xcode-cloud-control.test.mjsnew file mode 100644index 00000000..76bc6ef8--- /dev/null+++ b/scripts/xcode-cloud-control.test.mjs@@ -0,0 +1,36 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";++describe("Xcode Cloud control", () => {+ test("exposes start, wait, and VALID-build resolution for store delivery", () => {+ const script = readFileSync(+ new URL("./xcode-cloud-control.py", import.meta.url),+ "utf8",+ );+ const workflow = readFileSync(+ new URL("../.github/workflows/store-delivery.yml", import.meta.url),+ "utf8",+ );+ const cloudWorkflow = readFileSync(+ new URL("../.github/workflows/ios-xcode-cloud.yml", import.meta.url),+ "utf8",+ );++ expect(script).toContain('sub.add_parser("start"');+ expect(script).toContain('sub.add_parser("wait"');+ expect(script).toContain("--wait-valid");+ expect(script).toContain("--require-sha");+ expect(script).toContain("sourceBranchOrTag");+ expect(script).toContain("processingState");+ expect(script).toContain('emit("build_number"');+ expect(script).not.toContain("APP_STORE_BUILD_NUMBER: \"49\"");++ expect(workflow).toContain(".edgeever-ci/scripts/xcode-cloud-control.py");+ expect(workflow).toContain("--wait-valid");+ expect(workflow).toContain("--require-sha");++ expect(cloudWorkflow).toContain("scripts/xcode-cloud-control.py");+ expect(cloudWorkflow).not.toContain("submit-review");+ expect(cloudWorkflow).not.toContain('APP_STORE_BUILD_NUMBER: "49"');+ });+});