Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 提前检查模拟器构建工具并改善诊断流程
Dashc414c879fd54
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.mdindex 0ed28755f3..e8088e5098 100644--- a/apps/mobile/docs/simulator-debugging.md+++ b/apps/mobile/docs/simulator-debugging.md@@ -63,6 +63,45 @@ Use `mobile:sim:whoami -- --viewer --json` when handing off an external window.explicitly leaves visible-window acceptance to a screenshot/manual check. Without`--viewer`, a missing external viewer does not fail embedded/headless identity checks.+## 截图与当前版本测试++“给我看这次手机改动的截图”与启动当前版本测试共用此流程。设备选择、接管和系统工具安装的+授权来自用户及个人工作流;本节只定义通用操作和证据,不指定某个开发者的区域、手机或账号。++1. 固定本任务的 worktree,读取 `git status --short --branch`。使用任务明确指定的机型,+ 未指定时才使用个人选择。先枚举设备,选择精确 UDID;已有设备必须符合本次机型要求,不能+ 因另一型号已经启动就把它当作目标。后续命令保持相同 region、UDID、模拟器后端和 mock 开关。+2. 先运行 `mobile:sim:whoami`,再决定是否需要启动设备、接管 Metro 或准备原生包。+ 只检查 UI 时对 `whoami/start/rebuild` 都加 `--mock`。命令保留退出码;`pnpm` 的前后日志+ 不属于 JSON,解析时从 stdout 末尾向前找最后一行合法 JSON 对象,不用 `grep | tail` 吞掉失败。+3. 若 `native-matched`,复用已安装包;缺包、不兼容或包本身无可验证指纹时运行普通+ `mobile:sim:rebuild`。它先查询 `~/Library/Caches/xdt-maker/sim-app-cache` 中的匹配条目,+ 校验 bundle ID、架构和嵌入指纹,未命中才检查构建工具并编译。`SIM_CACHE` 给出查询位置与+ `cache-entry-missing`、`cache-bundle-mismatch`、`cache-architecture-mismatch`、+ `cache-native-mismatch` 等原因;有旧产物不等于兼容,未安装也不等于必须完整编译。+ 不从任意目录捡 `.app` 绕过校验,日常不传 `--clean` 或 `--force-build`。+4. `SIM_BUILD_PREFLIGHT` 失败时按 [环境说明](../../../docs/dev-rules/environment-setup.md#macosios-模拟器构建工具链)+ 修复具体工具。`whoami` 的 `probeErrors`、阶段失败或 `native.reason` 指向探测/计算故障时,+ 先处理该故障,不能把“检查失败”当作“需要重建”。后台构建保留日志和退出码,用宿主的进程+ 完成通知/状态查看推进,不用固定数分钟的 `sleep` 判断完成,不因等待较久重复启动构建。+5. 复用匹配的 Metro;需要接管且已获授权时只用 `mobile:sim:start -- --takeover`,不手工+ `kill`、不清登录态、不改端口来规避身份检查。Metro 持续运行并保留日志。安装和启动是独立+ 结果:`rebuild` 可能已经安装成功但因 Metro 未就绪而以非零退出;此时准备 Metro 后启动正确+ App,不必再次编译。只有 Metro 属于目标 worktree 后才 launch/reload App。+6. 按下方身份合同确认 `whoami healthy: true`、`native-matched` 和本次新的 `iOS Bundled …`,+ 再进入真实目标页面。Cindy 模拟器用插件查看器(确认 `previewOpened`),系统外部窗口用+ `mobile:sim:open` 并以 `whoami --viewer` 检查;两者都需要实际截图/目检页面,窗口进程不等于画面。++截图和 `mobile-identity.json`、本次 bundle 日志放进同一任务产物目录,记录页面/场景、设备+UDID、方向、主题及未验证项。布局问题按本次要求覆盖横竖屏与深浅色;截图必须来自目标+版本的实际界面。身份未通过就报告未完成;仅缺目检则报告“版本及 bundle 已验证,画面未目检”。+本节不授权上传截图到公开平台。++`whoami` 会向 stderr 输出阶段开始与耗时,JSON 的 `checks` / `elapsedMs` 可定位慢在+配置、Git 源码身份、设备、原生指纹、Metro 还是查看器。Expo config 的单次检查上限 30s,+simctl/安装信息查询 15s,Git 子命令 30s,Metro 的主要进程查询 5s,原生指纹 120s;+这些是单步上限,不是总运行时间承诺。失败后按阶段排查,不降低原生/源码身份要求。+## Current Source Verification ContractBefore anyone claims "the simulator is already showing the new version", they@@ -84,7 +123,7 @@ apply". Treat the following as a contract, not optional steps:fingerprint is **your current worktree**. (Injected by `mobile:sim:start`; see below.)2. `pnpm mobile:sim:whoami` exits nonzero unless a booted development client,the current worktree's `8081` Metro, and the exact source fingerprint all- agree; the label's port must map to your worktree.+ agree, including `native.healthy: true` / `native-matched`; the label's port must map to your worktree.3. The Metro terminal printed a fresh `iOS Bundled …` after your edit.### Tools (use these instead of ad-hoc `lsof`/`PlistBuddy`/deep-link dances)@@ -96,7 +135,7 @@ pnpm mobile:sim:start:cn # Mainland China; on Windows also starts cindy-api36pnpm mobile:sim:start -- --region=cn # 中国大陆版 JS region;先 rebuild 对应 native apppnpm mobile:sim:whoami # doctor: booted install + which port = which worktreepnpm mobile:sim:whoami -- --region=cn # inspect the cn native app + Metro ownership-pnpm mobile:sim:rebuild # rebuild + reinstall the Global native dev app (native changes only)+pnpm mobile:sim:rebuild # install a compatible cached dev app, or build it on a cache miss````mobile:sim:start` and `mobile:sim:rebuild` default to `global`; the China@@ -141,14 +180,14 @@ input — adding a script there would bump the mobile runtime version.its compiled default packager port (`8081`) — a `xdmaker://expo-development-client/?url=…`deep link or a `--dev-client` "No apps connected" state will NOT switch it.Starting Metro on any other port leaves the app loading a stale `8081` bundle.-- Therefore `mobile:sim:start` **insists on `8081`** (never auto-bumps): if `8081`- is held by *another* worktree it refuses and tells you to stop that Metro first- (you can only run one mobile dev session at a time); if it's this worktree's own- Metro it just says "already running". Use `mobile:sim:whoami` to see who owns- each port. Override with `-- --port <p>` only if you'll point the app there yourself.+- Therefore `mobile:sim:start` defaults to `8081` and never auto-bumps. It reuses a+ Metro only when worktree, source, region and environment all match. An authorized+ `--takeover` stops only a confirmed Cindy Metro; unknown/non-Metro owners are refused.+ Use `mobile:sim:whoami` to inspect ownership. An explicit `--port` is for callers+ that can actually point their app there, not a workaround for this debug app.- If `8081` belongs to this worktree but its injected fingerprint no longer equalsthe current worktree, `mobile:sim:start` refuses instead of claiming Metro is- reusable. Stop it and start Metro again after the amend/rebase/reset or edit.+ reusable. An authorized `--takeover` refreshes its identity after the amend/rebase/reset or edit.### Native build gotchadiff --git a/apps/mobile/scripts/lib/sim-native-identity.mjs b/apps/mobile/scripts/lib/sim-native-identity.mjsindex f09b32e880..e63fedd4b4 100644--- a/apps/mobile/scripts/lib/sim-native-identity.mjs+++ b/apps/mobile/scripts/lib/sim-native-identity.mjs@@ -31,14 +31,17 @@ export function computeSimulatorNativeFingerprint(encoding: "utf8",maxBuffer: 64 * 1024 * 1024,timeout: 120_000,+ killSignal: "SIGKILL",stdio: ["ignore", "pipe", "pipe"],},);const hash = fingerprint(JSON.parse(output).hash);if (!hash) throw new Error("Invalid fingerprint");return hash;- } catch {- throw new Error("Expo Updates native fingerprint calculation failed");+ } catch (error) {+ throw Object.assign(new Error("Expo Updates native fingerprint calculation failed"), {+ code: error.code === "ETIMEDOUT" ? "NATIVE_FINGERPRINT_TIMEOUT" : "NATIVE_FINGERPRINT_FAILED",+ });}}@@ -66,17 +69,23 @@ export function inspectSimulatorNativeIdentity({result.installedFingerprint = fingerprint(read(join(appPath, "EXUpdates.bundle", "fingerprint")),);+ } catch {+ return { ...result, reason: "installed-fingerprint-unreadable" };+ }+ if (!result.installedFingerprint) return { ...result, reason: "installed-fingerprint-missing" };+ try {result.expectedFingerprint = fingerprint(expectedFingerprint ?? compute(projectDir, env),);- if (!result.installedFingerprint || !result.expectedFingerprint)- return result;+ if (!result.expectedFingerprint)+ return { ...result, reason: "native-fingerprint-unavailable" };result.healthy = result.installedFingerprint === result.expectedFingerprint;result.code = result.healthy ? "native-matched" : "native-mismatch";return result;- } catch {+ } catch (error) {// Unknown is never compatibility evidence. Keep CLI output free of config// contents or child-process diagnostics that may contain local secrets.- return result;+ return { ...result, reason: error.code === "NATIVE_FINGERPRINT_TIMEOUT"+ ? "native-fingerprint-timeout" : "native-fingerprint-unavailable" };}}diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjsindex a900bd535c..303eeda07a 100644--- a/apps/mobile/scripts/lib/sim-whoami.mjs+++ b/apps/mobile/scripts/lib/sim-whoami.mjs@@ -394,9 +394,14 @@ export function resolveMobileSimulatorBundleId(region, options = {}) {env: { ...(options.env ?? process.env), ...buildEnv },encoding: "utf8",stdio: ["ignore", "pipe", "pipe"],+ timeout: 30_000,+ killSignal: "SIGKILL",},);} catch (error) {+ if (error?.code === "ETIMEDOUT") {+ throw Object.assign(new Error(`Expo config 解析 ${region} Simulator bundle id 超时(30s);检查当前 worktree 依赖和 Expo 配置后重试。`), { code: "EXPO_CONFIG_TIMEOUT" });+ }const detail = String(error?.stderr ?? error?.message ?? error).trim();throw new Error(`无法解析 ${region} Simulator bundle id${detail ? `: ${detail}` : ""}`,diff --git a/apps/mobile/scripts/sim-metro.mjs b/apps/mobile/scripts/sim-metro.mjsindex 7d2291ee5d..5e5b48d4fc 100644--- a/apps/mobile/scripts/sim-metro.mjs+++ b/apps/mobile/scripts/sim-metro.mjs@@ -31,24 +31,50 @@ export function parseWindowsNetstatListener(output, port) {return null;}-export function listenerPid(port) {- if (process.platform === 'win32') {- try {- const output = execFileSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8' });- return parseWindowsNetstatListener(output, port);- } catch {- // Fall through to the platform-neutral unknown-owner result.- }- return null;- }+/**+ * One bounded socket snapshot for whoami; a failed probe is not an empty port.+ * @param {number[]} ports+ * @param {{ platform?: NodeJS.Platform, run?: (command: string, args: string[], options: import('node:child_process').ExecFileSyncOptionsWithStringEncoding) => string }} options+ */+export function inspectMetroListeners(ports, { platform = process.platform, run = execFileSync } = {}) {+ const pids = {};try {- return execFileSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], { encoding: 'utf8' })- .trim().split('\n')[0] || null;- } catch {- return null;+ // Socket names do not need filesystem stat/readlink. -b avoids blocked mounts;+ // -w suppresses the expected filesystem warnings from that mode.+ const output = String(run(platform === 'win32' ? 'netstat' : 'lsof',+ platform === 'win32' ? ['-ano', '-p', 'tcp']+ : ['-b', '-w', '-nP', `-iTCP:${ports.join(',')}`, '-sTCP:LISTEN', '-Fpn'],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 5000, killSignal: 'SIGKILL' }));+ if (platform === 'win32') {+ for (const port of ports) {+ const pid = parseWindowsNetstatListener(output, port);+ if (pid) pids[port] = pid;+ }+ } else {+ let pid = null;+ for (const line of output.split(/\r?\n/)) {+ if (/^p\d+$/.test(line)) pid = line.slice(1);+ const match = line.match(/^n.*:(\d+)$/);+ const port = match ? Number(match[1]) : null;+ if (pid && ports.includes(port) && !pids[port]) pids[port] = pid;+ }+ }+ return { healthy: true, code: 'ready', pids };+ } catch (error) {+ // lsof exits 1 when the requested ports have no listeners.+ if (platform !== 'win32' && error.status === 1 && !error.signal && !error.code+ && !String(error.stderr ?? '').trim() && !String(error.stdout ?? '').trim()) {+ return { healthy: true, code: 'ready', pids };+ }+ return { healthy: false, code: error.code === 'ETIMEDOUT'+ ? 'METRO_LISTENERS_TIMEOUT' : 'METRO_LISTENERS_UNAVAILABLE', pids };}}+export function listenerPid(port) {+ return inspectMetroListeners([port]).pids[port] ?? null;+}+const metroOwnerDir = join(tmpdir(), 'cindy-metro-owners');/**@@ -201,7 +227,7 @@ export function probeMetroOwnership(port, options = {}) {// worktree,且各 checkout 目录名不同)。macOS:lsof -a -p <pid> -d cwd -Fn。export function cwdOfPid(pid) {try {- const out = execFileSync('lsof', ['-a', '-p', pid, '-d', 'cwd', '-Fn'], { encoding: 'utf8' });+ const out = execFileSync('lsof', ['-b', '-w', '-a', '-p', pid, '-d', 'cwd', '-Fn'], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });const line = out.split('\n').find((l) => l.startsWith('n'));return line ? line.slice(1) : null;} catch {@@ -211,7 +237,7 @@ export function cwdOfPid(pid) {export function commandOfPid(pid) {try {- return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' }).trim();+ return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' }).trim();} catch {return '';}@@ -330,7 +356,7 @@ export async function terminateMetro(pid, options = {}) {/** Read the exact source token injected by sim:start from a running Metro. */export function gitSourceOfPid(pid) {try {- const out = execFileSync('ps', ['-ww', '-E', '-p', pid], { encoding: 'utf8' });+ const out = execFileSync('ps', ['-ww', '-E', '-p', pid], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });const match = out.match(/EXPO_PUBLIC_XDT_GIT_SOURCE=(\S*)/);return match ? match[1] : null;} catch {@@ -349,6 +375,8 @@ export function gitSourceIdentity(worktreeRoot, options = {}) {encoding: 'utf8',stdio: ['ignore', 'pipe', 'pipe'],maxBuffer: 64 * 1024 * 1024,+ timeout: 30_000,+ killSignal: 'SIGKILL',...extra,})).trim();diff --git a/apps/mobile/scripts/sim-pod-install.mjs b/apps/mobile/scripts/sim-pod-install.mjsindex 1e041b5ee2..c4e895e1b0 100644--- a/apps/mobile/scripts/sim-pod-install.mjs+++ b/apps/mobile/scripts/sim-pod-install.mjs@@ -6,7 +6,34 @@// 特征是"没有任何输出":curl 下载、CocoaPods 安装日志都会持续产生 stdout/stderr。// 所以这里用**输出空转看门狗**——连续 idleTimeoutMs 无任何输出才 SIGKILL,// 把"无限等"变成"分钟级失败",同时不影响慢速但健康的下载。-import { spawn } from 'node:child_process';+import { execFileSync, spawn } from 'node:child_process';++export const COCOAPODS_SETUP_HINT = '请按 docs/dev-rules/environment-setup.md 的 iOS 工具链说明准备 CocoaPods,并在当前 Agent 环境验证 pod --version;已有 Homebrew 可用 brew install cocoapods,否则使用独立 Ruby 的 gem install cocoapods --user-install 并配置 PATH。';++// Only call after a cache miss: installing a compatible cached app does not need CocoaPods.+// Version/SDK probes are read-only; never install tools or accept Xcode licenses here.+/** @param {{ env?: NodeJS.ProcessEnv, run?: (command: string, args: string[], options: import('node:child_process').ExecFileSyncOptionsWithStringEncoding) => string }} options */+export function inspectIOSBuildTools({ env = process.env, run = execFileSync } = {}) {+ const checks = [+ ['xcodebuild', ['-version']],+ ['xcrun', ['--sdk', 'iphonesimulator', '--show-sdk-path']],+ ['pod', ['--version']],+ ].map(([tool, args]) => {+ try {+ run(tool, args, {+ env: { ...env, LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' },+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,+ killSignal: 'SIGKILL',+ });+ return { tool, healthy: true, code: 'ready' };+ } catch (error) {+ // Do not return arbitrary child output or environment values in the receipt.+ return { tool, healthy: false, code: error.code === 'ENOENT' ? 'missing'+ : error.code === 'ETIMEDOUT' ? 'timeout' : 'failed' };+ }+ });+ return { healthy: checks.every((check) => check.healthy), checks };+}// 连续无输出判挂死的窗口。CocoaPods 有静默阶段(依赖解析、Generating Pods// project),实测在分钟级以内;5 分钟静默基本只剩死连接一种解释。@@ -130,7 +157,7 @@ export async function podInstallBounded({ iosDir, env = process.env, idleTimeoutreturn;} catch (error) {if (error.code === 'ENOENT') {- const missing = new Error('找不到 `pod`(CocoaPods)。先 `brew install cocoapods` 再重试。');+ const missing = new Error(`找不到 pod(CocoaPods)。${COCOAPODS_SETUP_HINT}`);missing.podMissing = true;missing.cause = error;throw missing;diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjsindex 02ac12fbf8..007d725802 100644--- a/apps/mobile/scripts/sim-rebuild.mjs+++ b/apps/mobile/scripts/sim-rebuild.mjs@@ -69,7 +69,7 @@ import {ensureMobileLocalRegionConfig,formatMobileLocalConfigStatus,} from './lib/mobile-local-config.mjs';-import { podInstallBounded } from './sim-pod-install.mjs';+import { podInstallBounded, inspectIOSBuildTools, COCOAPODS_SETUP_HINT } from './sim-pod-install.mjs';import { computeSimulatorNativeFingerprint, inspectSimulatorNativeIdentity } from './lib/sim-native-identity.mjs';import { ensureWindowsAndroidEmulator, resolveAndroidSdkTools } from './lib/android-simulator.mjs';import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';@@ -261,7 +261,10 @@ async function rebuildAndroidSimulator() {// 宿主机架构只参与缓存隔离;真实构建架构由 Xcode 与各 Pod 的支持矩阵决定。const simArch = process.arch === 'arm64' ? 'arm64' : 'x86_64';+console.log('› 解析目标 App 身份…');const expectedBundleId = resolveMobileSimulatorBundleId(region);+console.log(`==> Worktree: ${worktreeRoot}; region=${region}; bundleId=${expectedBundleId}; arch=${simArch}`);+console.log('› 计算原生兼容指纹(最长 120s)…');let expectedNativeFingerprint = computeSimulatorNativeFingerprint(mobileDir, devProcessEnv);function assertNativeIdentity(appPath) {@@ -275,7 +278,7 @@ function assertNativeIdentity(appPath) {// 覆盖掉——否则逃生舱跑完一次,坏条目还在,下次普通 rebuild 又命中它。let fingerprintHash = null;try {- console.log('› 计算 native fingerprint(产物缓存键)…');+ console.log('› 计算 native fingerprint(产物缓存键,最长 120s)…');fingerprintHash = computeFingerprintReport(mobileDir, {platforms: ['ios'],run: runFingerprintWithCurrentEnv,@@ -286,17 +289,28 @@ try {const cacheDir = fingerprintHash ? join(appCacheRoot, `ios-${simArch}-${fingerprintHash}`) : null;let app = null;+let cache = { code: forceBuild ? 'cache-bypassed' : 'cache-fingerprint-unavailable', app: null };if (cacheDir && !forceBuild) {- const cached = readAppCacheEntry(cacheDir, simArch);- if (cached && inspectSimulatorNativeIdentity({ appPath: cached, expectedFingerprint: expectedNativeFingerprint }).healthy) {+ cache = readAppCacheEntry(cacheDir, simArch);+ if (cache.app) {console.log(`✓ fingerprint 命中产物缓存(${fingerprintHash.slice(0, 12)}…),跳过 prebuild / pod / xcodebuild。`);console.log(' (改了原生层但怀疑缓存不对时,用 --force-build 强制重编。)');utimesSync(cacheDir, new Date(), new Date());- app = cached;+ app = cache.app;}}+console.log(`SIM_CACHE=${JSON.stringify({ ...cache, directory: cacheDir, root: appCacheRoot, fingerprint: fingerprintHash })}`);if (!app) {+ console.log(`› 缓存不可复用(${cache.code}),检查 iOS 构建工具链…`);+ const preflight = inspectIOSBuildTools({ env: devProcessEnv });+ console.log(`SIM_BUILD_PREFLIGHT=${JSON.stringify(preflight)}`);+ if (!preflight.healthy) {+ console.error(`✗ IOS_BUILD_TOOLS_UNAVAILABLE: ${preflight.checks.filter((check) => !check.healthy).map((check) => `${check.tool}=${check.code}`).join(', ')};尚未执行 prebuild / pod install / xcodebuild。`);+ if (preflight.checks.some((check) => check.tool === 'pod' && !check.healthy)) console.error(COCOAPODS_SETUP_HINT);+ console.error('先按 docs/dev-rules/environment-setup.md 修复上述工具,再用相同 region / UDID / --mock 参数重试;不要改用其他 App 身份。');+ process.exit(1);+ }// 总是先 prebuild,再 xcodebuild。本脚本是 native 变更的验证路径 —— 若只在 ios/ 缺失时// prebuild,那么"改了 app.json / Expo plugins / Pods 但 ios/ 已存在"时会构建到 stale 的// native 工程还报成功。prebuild 不带 --clean 是增量的,无 native 改动时很快。@@ -398,31 +412,37 @@ function runFingerprintWithCurrentEnv({ binPath, projectDir, platform }) {encoding: 'utf8',// 输出含全部 sources(>1MB),必须调大 maxBuffer(与 ci-fingerprint 同款)。maxBuffer: 64 * 1024 * 1024,+ timeout: 120_000,+ killSignal: 'SIGKILL',});if (result.status !== 0) {- throw new Error(`fingerprint:generate --platform ${platform} failed: ${result.stderr || result.error?.message || `exit ${result.status}`}`);+ throw new Error(`fingerprint:generate --platform ${platform} failed: ${result.error?.code ?? `exit ${result.status}`}`);}return parseFingerprintCliOutput(result.stdout);}/** 读产物缓存条目;结构不完整(半份缓存)时视为未命中。 */function readAppCacheEntry(dir, expectedArch) {+ const miss = (code) => ({ code, app: null });+ if (!existsSync(join(dir, 'meta.json'))) return miss('cache-entry-missing');try {const meta = JSON.parse(readFileSync(join(dir, 'meta.json'), 'utf8'));- if (typeof meta.scheme !== 'string' || !meta.scheme) return null;+ if (typeof meta.scheme !== 'string' || !meta.scheme) return miss('cache-metadata-invalid');const cachedApp = join(dir, `${meta.scheme}.app`);- if (!existsSync(cachedApp)) return null;- if (readAppBundleIdentifier(cachedApp) !== expectedBundleId) return null;+ if (!existsSync(cachedApp)) return miss('cache-app-missing');+ if (readAppBundleIdentifier(cachedApp) !== expectedBundleId) return miss('cache-bundle-mismatch');const architectures = readAppArchitectures(cachedApp);if (!architectures.includes(expectedArch)) {console.warn(` 缓存产物架构不匹配(实际=${architectures.join(',') || '未知'},当前 Simulator 需要=${expectedArch}),忽略并重新构建。`,);- return null;+ return miss('cache-architecture-mismatch');}- return cachedApp;+ const native = inspectSimulatorNativeIdentity({ appPath: cachedApp, expectedFingerprint: expectedNativeFingerprint });+ if (!native.healthy) return miss(`cache-${native.code}`);+ return { code: 'cache-hit', app: cachedApp };} catch {- return null;+ return miss('cache-read-failed');}}diff --git a/apps/mobile/scripts/sim-whoami.mjs b/apps/mobile/scripts/sim-whoami.mjsindex fba5e872e2..63ae89269a 100644--- a/apps/mobile/scripts/sim-whoami.mjs+++ b/apps/mobile/scripts/sim-whoami.mjs@@ -43,6 +43,7 @@ import {} from "./lib/sim-whoami.mjs";import {gitSourceIdentity,+ inspectMetroListeners,probeMetroOwnership,} from "./sim-metro.mjs";@@ -53,6 +54,30 @@ const worktreeRoot = resolve(mobileDir, "../..");const cliArgs = applySimMockArg(process.argv.slice(2));const jsonOutput = cliArgs.includes("--json");const requireViewer = cliArgs.includes("--viewer");+const startedAt = Date.now();+const checks = [];+const probeErrors = [];++// Progress goes to stderr even in --json mode; stdout keeps one result object.+function timedCheck(stage, run) {+ const start = Date.now();+ console.error(`[whoami] ${stage}…`);+ try {+ const result = run();+ const elapsedMs = Date.now() - start;+ checks.push({ stage, elapsedMs });+ console.error(`[whoami] ${stage}: ${elapsedMs}ms`);+ return result;+ } catch (error) {+ checks.push({ stage, elapsedMs: Date.now() - start });+ const failure = { healthy: false, pageVerified: false, stage,+ code: error.code ?? 'CHECK_FAILED', checks, elapsedMs: Date.now() - startedAt,+ error: `${stage} 检查失败:${error.message ?? 'unknown error'};检查该阶段的工具/当前 worktree 依赖后重试,不要将检查失败当作未安装 App。` };+ if (jsonOutput) console.log(JSON.stringify(failure));+ else console.error(`✗ ${failure.code}: ${failure.error}`);+ process.exit(1);+ }+}function resolveTarget() {const { region, passthrough } = extractMobileDevRegionArgs(@@ -74,8 +99,7 @@ function resolveTarget() {};}-let target;-try {+const target = timedCheck('configuration', () => {const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });if (!jsonOutput) {const localConfigStatus = formatMobileLocalConfigStatus(@@ -84,15 +108,13 @@ try {);if (localConfigStatus) console.log(localConfigStatus);}- target = resolveTarget();-} catch (error) {- const message = error instanceof Error ? error.message : String(error);- console.error(jsonOutput ? JSON.stringify({ healthy: false, error: message }) : `✗ ${message}`);- process.exit(1);-}+ return resolveTarget();+});const { region, port: expectedPort, simulatorUdid, bundleId, deviceSets } = target;+const { envFingerprint, uiMock } = timedCheck('environment', () => readSimEnvironment(mobileDir,+ withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region }))));const ports = [...new Set([...PORTS, expectedPort])].sort((a, b) => a - b);-const expectedSource = gitSourceIdentity(worktreeRoot);+const expectedSource = timedCheck('source-identity', () => gitSourceIdentity(worktreeRoot));let healthy = true;function shFile(command, args) {@@ -100,8 +122,14 @@ function shFile(command, args) {return execFileSync(command, args, {encoding: "utf8",stdio: ["ignore", "pipe", "ignore"],+ timeout: 15_000,+ killSignal: "SIGKILL",}).trim();- } catch {+ } catch (error) {+ if (error.code === 'ETIMEDOUT') {+ probeErrors.push({ command, code: 'PROBE_TIMEOUT', timeoutMs: 15_000 });+ console.error(`[whoami] ${command}: PROBE_TIMEOUT (15s)`);+ }return "";}}@@ -109,11 +137,11 @@ function shFile(command, args) {if (!jsonOutput) {console.log(`==> Mobile dev region: ${region}`);}-const { deviceSet, booted, targetBooted } = selectBootedSimulator(+const { deviceSet, booted, targetBooted } = timedCheck('simulator', () => selectBootedSimulator(deviceSets,(set) => shFile("xcrun", simctlArgs(set, ["list", "devices", "booted"])),simulatorUdid,-);+));if (!jsonOutput) console.log(`==== booted 模拟器(${deviceSet.name})====`);if (booted.length === 0) {if (!jsonOutput) console.log(" (没有 booted 模拟器)");@@ -125,7 +153,7 @@ if (targetBooted.length !== 1) {}if (!jsonOutput) console.log(`\n==== 模拟器里装的 ${bundleId}(native 安装包版本)====`);-const container = targetBooted.length === 1 ? getSimulatorAppContainer(shFile, simulatorUdid, bundleId, deviceSet) : "";+const container = timedCheck('installed-app', () => targetBooted.length === 1 ? getSimulatorAppContainer(shFile, simulatorUdid, bundleId, deviceSet) : "");let installed = null;if (!container) {if (!jsonOutput) {@@ -153,24 +181,37 @@ if (!container) {}}-const native = inspectSimulatorNativeIdentity({+const native = timedCheck('native-fingerprint', () => probeErrors.length > 0+ ? { healthy: false, code: 'native-unknown', reason: 'probe-timeout', installedFingerprint: null, expectedFingerprint: null }+ : inspectSimulatorNativeIdentity({appPath: container, projectDir: mobileDir,env: { ...process.env, ...withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region })) },-});+}));if (!native.healthy) healthy = false;if (!jsonOutput) {console.log(` native: ${native.code}`);- if (!native.healthy) console.log(` 请运行 pnpm mobile:sim:rebuild -- --region=${region}${simulatorUdid ? ` --udid ${simulatorUdid}` : ''},再检查原生兼容性。`);+ if (!native.healthy) {+ if (probeErrors.length > 0 || native.reason === 'native-fingerprint-timeout' || native.reason === 'native-fingerprint-unavailable') {+ console.log(` 原生身份检查未完成(${native.reason});先修复探测/指纹计算,再决定是否需要 rebuild。`);+ } else {+ const mock = uiMock ? ' --mock' : '';+ console.log(` 请运行 pnpm mobile:sim:rebuild -- --region=${region}${simulatorUdid ? ` --udid ${simulatorUdid}` : ''}${mock},先查询匹配缓存,再检查原生兼容性。`);+ }+ }}if (!jsonOutput) console.log("\n==== Metro 端口归属(哪个端口 = 哪个 worktree)====");let anyMetro = false;let currentSourceOnExpectedPort = false;const metros = [];-const { envFingerprint, uiMock } = readSimEnvironment(mobileDir,- withLocalMobileRegionConfig(mobileClientBundleEnv({ authRegion: region })));+const listeners = timedCheck('metro-listeners', () => inspectMetroListeners(ports));+if (!listeners.healthy) {+ probeErrors.push({ stage: 'metro-listeners', code: listeners.code });+ console.error(`[whoami] ${listeners.code};端口归属尚未确认,不能当作没有 Metro。`);+}for (const port of ports) {- const ownership = probeMetroOwnership(port);+ if (!listeners.pids[port]) continue;+ const ownership = timedCheck(`metro-${port}`, () => probeMetroOwnership(port, { listenerPid: () => listeners.pids[port] }));if (!ownership) continue;const listener = classifySimMetroListener({cwd: ownership.cwd, source: ownership.source, targetWorktree: worktreeRoot,@@ -187,18 +228,23 @@ for (const port of ports) {if (port === expectedPort) currentSourceOnExpectedPort = verdict.healthy;}-if (!anyMetro && !jsonOutput)+if (listeners.healthy && !anyMetro && !jsonOutput)console.log(` (检查的端口上没发现 Metro;用 \`pnpm mobile:sim:start -- --port ${expectedPort}\` 启一个)`,);if (!currentSourceOnExpectedPort) healthy = false;// Devices outside the system set are not shown by Device Hub; Cindy's appear in its sidebar.+const viewerStartedAt = Date.now();+console.error('[whoami] viewer…');const viewer = deviceSet.path? { available: false, running: false, status: `${deviceSet.name}-managed`, windowVerified: false,error: "该设备不在系统模拟器中,没有外部窗口;Cindy 模拟器请在 Cindy 侧边栏查看" }: await inspectSimulatorViewer();+checks.push({ stage: 'viewer', elapsedMs: Date.now() - viewerStartedAt });+console.error(`[whoami] viewer: ${Date.now() - viewerStartedAt}ms`);if (requireViewer && !viewer.running) healthy = false;+if (probeErrors.length > 0) healthy = false;if (!jsonOutput) {console.log(`\nSimulator viewer: ${viewer.status} (${viewer.appPath ?? viewer.error ?? 'not available'})`);console.log('Viewer process status does not verify a visible device window.');@@ -222,6 +268,9 @@ if (!jsonOutput) {console.log(JSON.stringify({healthy,+ checks,+ probeErrors,+ elapsedMs: Date.now() - startedAt,pageVerified: false,viewerRequired: requireViewer,viewer,diff --git a/apps/mobile/src/__tests__/mobileSimSource.test.ts b/apps/mobile/src/__tests__/mobileSimSource.test.tsindex 06213b8f53..8b5c0b890f 100644--- a/apps/mobile/src/__tests__/mobileSimSource.test.ts+++ b/apps/mobile/src/__tests__/mobileSimSource.test.ts@@ -6,10 +6,38 @@ import {gitSourceIdentity,isDedicatedMetroProcessGroup,isInside,+ inspectMetroListeners,parseWindowsNetstatListener,terminateMetro,} from '../../scripts/sim-metro.mjs';+// Regression 2026-10-29: whoami ran six slow lsof processes and treated timeout+// as no Metro. Unit fixtures exercise the real discovery/parser without sockets.+describe('mobile simulator listener discovery', () => {+ it('reads all requested ports from one socket snapshot, including IPv6', () => {+ const run = vi.fn(() => 'p101\nf12\nn127.0.0.1:8081\nf13\nn[::1]:8082\np202\nf14\nn*:8084\nn*:9090\n');+ expect(inspectMetroListeners([8081, 8082, 8083, 8084], { platform: 'darwin', run }))+ .toEqual({ healthy: true, code: 'ready', pids: { 8081: '101', 8082: '101', 8084: '202' } });+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('uses the same snapshot contract on Windows', () => {+ const run = () => 'TCP 0.0.0.0:8081 0.0.0.0:0 LISTENING 42\nTCP 127.0.0.1:8082 0.0.0.0:0 ESTABLISHED 99';+ expect(inspectMetroListeners([8081, 8082], { platform: 'win32', run }))+ .toEqual({ healthy: true, code: 'ready', pids: { 8081: '42' } });+ });++ it.each([+ [{ status: 1, stderr: '', stdout: '' }, true, 'ready'],+ [{ code: 'ETIMEDOUT', stderr: 'private' }, false, 'METRO_LISTENERS_TIMEOUT'],+ [{ code: 'ENOENT' }, false, 'METRO_LISTENERS_UNAVAILABLE'],+ [{ status: 1, stderr: 'private failure' }, false, 'METRO_LISTENERS_UNAVAILABLE'],+ ])('distinguishes no listeners from failed discovery: %j', (error, healthy, code) => {+ expect(inspectMetroListeners([8081], { platform: 'darwin', run: () => { throw error; } }))+ .toEqual({ healthy, code, pids: {} });+ });+});+describe('mobile simulator source identity', () => {it('uses branch and commit for a clean worktree', () => {expect(gitSourceIdentity('/repo', {diff --git a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts b/apps/mobile/src/__tests__/mobileSimWhoami.test.tsindex fedd12829a..b2af4ea229 100644--- a/apps/mobile/src/__tests__/mobileSimWhoami.test.ts+++ b/apps/mobile/src/__tests__/mobileSimWhoami.test.ts@@ -353,6 +353,14 @@ describe('mobile:sim simulator choice', () => {});describe('mobile:sim:whoami bundle identity', () => {+ // 2026-10-29: identity checks stalled for minutes with no actionable phase.+ // Unit: a timed-out Expo config must remain an explicit error, never a guessed bundle ID.+ it('reports the bounded Expo config timeout without leaking child output', () => {+ const execFile = vi.fn(() => { throw Object.assign(new Error('private output'), { code: 'ETIMEDOUT', stderr: 'private output' }); });+ expect(() => resolveMobileSimulatorBundleId('global', { execFile })).toThrow(/Expo config.*超时/);+ expect(execFile).toHaveBeenCalledWith('pnpm', expect.any(Array), expect.objectContaining({ timeout: 30_000, killSignal: 'SIGKILL' }));+ });+it.each([['cn', 'com.local.cindycn'],['global', 'com.local.cindy'],diff --git a/apps/mobile/src/__tests__/simNativeIdentity.test.ts b/apps/mobile/src/__tests__/simNativeIdentity.test.tsindex 8161fc95fe..dea12f17f6 100644--- a/apps/mobile/src/__tests__/simNativeIdentity.test.ts+++ b/apps/mobile/src/__tests__/simNativeIdentity.test.ts@@ -6,6 +6,22 @@ const current = "a".repeat(40);const previous = "b".repeat(40);describe("simulator native compatibility", () => {+ // 2026-10-29: avoid expensive calculation when no installed fingerprint can be+ // compared, and distinguish a calculator timeout from an incompatible app (unit).+ it("skips calculation when the installed fingerprint is missing", () => {+ const compute = vi.fn(() => current);+ expect(inspectSimulatorNativeIdentity({ appPath: '/app', read: () => '', compute }))+ .toMatchObject({ healthy: false, code: 'native-unknown', reason: 'installed-fingerprint-missing' });+ expect(compute).not.toHaveBeenCalled();+ });++ it("reports calculation timeout without claiming the app needs a rebuild", () => {+ const result = inspectSimulatorNativeIdentity({ appPath: '/app', read: () => current,+ compute: () => { throw Object.assign(new Error('private child output'), { code: 'NATIVE_FINGERPRINT_TIMEOUT' }); } });+ expect(result).toMatchObject({ healthy: false, code: 'native-unknown', reason: 'native-fingerprint-timeout' });+ expect(JSON.stringify(result)).not.toContain('private');+ });+it.each([[current, current, true, "native-matched"],[previous, current, false, "native-mismatch"],diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.tsindex 209f4217e7..425573443a 100644--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts@@ -6,6 +6,7 @@ import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoinimport { resolvePnpmInvocation, usablePnpmExecPath } from '../../../../scripts/shared/pnpm-invocation.mjs';import { extractMobileDevRegionArgs, withLocalMobileRegionConfig } from '../../scripts/lib/mobile-dev-region.mjs';import { extractSimWhoamiUdidArgs, resolveMobileSimulatorBundleId, selectBootedSimulator, findSimulatorDeviceSet, simctlArgs } from '../../scripts/lib/sim-whoami.mjs';+import { inspectIOSBuildTools, COCOAPODS_SETUP_HINT } from '../../scripts/sim-pod-install.mjs';const source = readFileSync(resolve(process.cwd(), 'scripts/sim-rebuild.mjs'), 'utf8');const start = source.indexOf('const iosDir =');@@ -21,6 +22,7 @@ const udid = '11111111-1111-1111-1111-111111111111';async function rebuild(options: {args?: string[]; platform?: 'darwin' | 'win32'; cached?: boolean; cachedArch?: string;fingerprintFailure?: boolean; metroHealthy?: boolean; builtArch?: string; cindyBooted?: boolean;+ unavailableTool?: string; toolFailure?: string; nativeMismatch?: boolean;} = {}) {const cindySet = { name: 'cindy', path: '/home/test/Library/Application Support/BaguetteCindy/devices' };const env = { EXPO_PUBLIC_APP_VARIANT: 'beta', npm_execpath: '/tools/pnpm.cjs' };@@ -30,6 +32,8 @@ async function rebuild(options: {exit(code: number) { throw new Error(`exit:${code}`); },};const execFileSync = vi.fn((command: string, args: string[], _opts: object) => {+ if (command === options.unavailableTool) throw Object.assign(new Error('private child output'), { code: options.toolFailure ?? 'ENOENT' });+ if (command === 'pod') return '1.16.2';if (command === 'plutil') return args[1] === 'CFBundleIdentifier' ? 'com.xd.cindy' : 'Cindy';if (command === 'lipo') return args[1].startsWith(cacheRoot) ? (options.cachedArch ?? 'arm64') : (options.builtArch ?? 'arm64');if (command === '/node' && args.includes('config')) return JSON.stringify({ android: { package: 'com.xd.cindy' } });@@ -65,13 +69,14 @@ async function rebuild(options: {resolvePnpmInvocation: (args: string[], opts: object) => resolvePnpmInvocation(args, { ...opts, platform: processStub.platform, execPath: '/node' }),usablePnpmExecPath, ensureMobileLocalRegionConfig: () => ({}), formatMobileLocalConfigStatus: () => '',ensureMobileEnv: () => ({ created: false, addedKeys: [] }), formatMobileEnvStatus: () => '',- computeSimulatorNativeFingerprint: () => 'native-fingerprint', inspectSimulatorNativeIdentity: () => ({ healthy: true }),+ computeSimulatorNativeFingerprint: () => 'native-fingerprint', inspectSimulatorNativeIdentity: ({ appPath }: { appPath: string }) => ({ healthy: !(options.nativeMismatch && appPath.startsWith(cacheRoot)), code: 'native-mismatch' }),+ inspectIOSBuildTools: (opts: object) => inspectIOSBuildTools({ ...opts, run: execFileSync }), COCOAPODS_SETUP_HINT,computeFingerprintReport: (_dir: string, opts: { run: (input: object) => { hash: string } }) => {if (options.fingerprintFailure) throw new Error('fingerprint unavailable');return { platforms: { ios: opts.run({ binPath: '/fingerprint/cli.js', projectDir: mobileDir, platform: 'ios' }).hash } };},parseFingerprintCliOutput: JSON.parse, podInstallBounded,- existsSync: () => true, mkdirSync: vi.fn(), rmSync, cpSync, writeFileSync, utimesSync,+ existsSync: (path: string) => path === `${cacheDir}/meta.json` ? Boolean(options.cached) : true, mkdirSync: vi.fn(), rmSync, cpSync, writeFileSync, utimesSync,readFileSync: (path: string) => {if (!options.cached || path !== `${cacheDir}/meta.json`) throw new Error('cache miss');return JSON.stringify({ scheme: 'Cindy' });@@ -90,6 +95,39 @@ async function rebuild(options: {}describe('sim-rebuild workflow', () => {+ // Regression 2026-10-29: missing CocoaPods was discovered only after writing ios/.+ // The real CLI runs with in-memory process/filesystem boundaries (unit); existing+ // cache tests did not cover unavailable tools or cache rejection diagnostics.+ it.each(['ENOENT', 'ETIMEDOUT', 'EACCES'])('stops before prebuild when CocoaPods is unavailable (%s)', async (toolFailure) => {+ const result = await rebuild({ args: ['--build-only'], unavailableTool: 'pod', toolFailure });+ expect(result.error).toEqual(new Error('exit:1'));+ expect(result.execFileSync.mock.calls.some(([, args]) => args.includes('prebuild'))).toBe(false);+ expect(result.podInstallBounded).not.toHaveBeenCalled();+ expect(result.cpSync).not.toHaveBeenCalled();+ const receipt = result.log.mock.calls.flat().join('\n');+ expect(receipt).toContain('IOS_BUILD_TOOLS_UNAVAILABLE');+ expect(receipt).toContain('environment-setup.md');+ expect(receipt).not.toContain('private child output');+ });++ it('installs a compatible cache without requiring CocoaPods', async () => {+ const result = await rebuild({ cached: true, unavailableTool: 'pod', args: ['--udid', udid] });+ expect(result.error).toBeUndefined();+ expect(result.execFileSync).toHaveBeenCalledWith('xcrun', ['simctl', 'install', udid, `${cacheDir}/Cindy.app`], expect.any(Object));+ expect(result.execFileSync.mock.calls.some(([cmd]) => cmd === 'pod' || cmd === 'xcodebuild')).toBe(false);+ });++ it.each([+ [{ cached: false }, 'cache-entry-missing'],+ [{ cached: true, cachedArch: 'x86_64' }, 'cache-architecture-mismatch'],+ [{ cached: true, nativeMismatch: true }, 'cache-native-mismatch'],+ ])('explains why an existing artifact cannot be reused: %j', async (options, code) => {+ const result = await rebuild({ ...options, args: ['--build-only'], unavailableTool: 'pod' });+ expect(result.error).toEqual(new Error('exit:1'));+ expect(result.log.mock.calls.flat().join('\n')).toContain(code);+ expect(result.execFileSync.mock.calls.some(([, args]) => args.includes('prebuild'))).toBe(false);+ });+it.each([false, true])('reuses valid cache and writes force-built artifacts back (force=%s)', async (force) => {const result = await rebuild({ cached: true, args: ['--build-only', ...(force ? ['--force-build', '--udid', udid] : [])] });expect(result.error).toEqual(new Error('exit:0'));diff --git a/docs/dev-rules/environment-setup.md b/docs/dev-rules/environment-setup.mdindex 87f3a7398d..54b81a51cb 100644--- a/docs/dev-rules/environment-setup.md+++ b/docs/dev-rules/environment-setup.md@@ -66,6 +66,45 @@ Cindy Make 的设置入口和指令前置弹窗共用源码准备流程:切到准备阶段填充的 pnpm store 缓存,并执行必要的安装脚本;各 worktree 仍保留独立的 `node_modules`,不复制或链接个人分支的依赖目录。安装失败或取消可在现有 checkout 上重试,不重置个人分支。+## macOS:iOS 模拟器构建工具链++首次安装开发包不等于首次完整编译。先按 [Mobile 模拟器流程](../../apps/mobile/docs/simulator-debugging.md#截图与当前版本测试)+检查已安装包;需要安装或更新原生包时,`mobile:sim:rebuild` 会先检查跨 worktree 的+fingerprint 缓存。命中兼容产物就直接安装,不要求 CocoaPods;只有缓存不可复用时才编译。++完整编译需要选中的完整 Xcode、iOS Simulator SDK、目标设备所需的已安装 runtime,+以及当前 Agent 的 `PATH` 中可运行的 CocoaPods。仅安装 Command Line Tools 不够。+在实际运行任务的终端核对(终端 App 可用不代表 Agent 子进程也可用):++```bash+xcode-select -p+xcodebuild -version+xcrun --sdk iphonesimulator --show-sdk-path+xcrun simctl list runtimes+pod --version+```++Xcode 选择由本机 `xcode-select` 或本次进程的 `DEVELOPER_DIR` 决定;首次启动设置、许可和+runtime 下载在 Xcode 完成。机器上的实际安装位置、选中的设备和工具是否可用应现场检测,+不写成仓库默认值。模拟器的 SDK/runtime 不等于 CocoaPods,也不等于可复用 App。++CocoaPods 使用开发者已有的工具管理方式:++- 已安装 Homebrew:`brew install cocoapods`,随后确认当前 Agent 的 `PATH` 能找到它。+- 已有独立 Ruby(例如 rbenv/RVM 管理):先核对 `ruby --version` 和 `gem --version`,+ 然后 `gem install cocoapods --user-install`;将 `ruby -r rubygems -e 'puts Gem.user_dir'`+ 输出目录下的 `bin` 加到该工具环境的 `PATH`,再验证 `pod --version`。+- 两者都没有:先按开发者选定的方式准备独立 Ruby 或 Homebrew,再安装 CocoaPods。+ 不因系统带有 Ruby 2.6 就假定当前 CocoaPods 及其依赖可安装,也不自动替换系统 Ruby。++这遵循 [CocoaPods 官方安装说明](https://guides.cocoapods.org/using/getting-started.html)+推荐的独立 Ruby 与用户目录安装方式;安装命令成功仍须通过上面的本机检查。工具链安装、+系统路径调整与许可证接受遵循当前用户授权,不由仓库脚本静默执行。++缓存未命中时,`rebuild` 在生成 `ios/` 前运行只读工具检查,输出 `SIM_BUILD_PREFLIGHT`;+缺失、执行失败或超时以 `IOS_BUILD_TOOLS_UNAVAILABLE` 结束。先修复回执中失败的工具,+用原来的 region / UDID / `--mock` 参数重试,不通过换区域、清缓存或换真机掩盖环境故障。+## Linux:Electron SUID sandbox 权限较新的 Ubuntu(23.10+ 默认用 AppArmor 限制非特权 user namespace)上,Electron 会退回diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.mdindex 38e8ab1ddf..a9b1491d5b 100644--- a/docs/dev-rules/mobile-development.md+++ b/docs/dev-rules/mobile-development.md@@ -47,9 +47,15 @@ pnpm mobile:sim:start:cn修改原生依赖、Expo 原生配置,或切换到尚未安装对应开发包的区域时,重新构建:+这里的 `rebuild` 是“准备兼容原生包”的入口:先复用匹配缓存,未命中才完整编译。+未安装 App 不等于必须编译;纯 JS/TS 改动且 `native-matched` 时直接复用已安装包。+截图和交付测试的完整流程见 [截图与当前版本测试](../../apps/mobile/docs/simulator-debugging.md#截图与当前版本测试),+缺少工具时见 [iOS 工具链](environment-setup.md#macosios-模拟器构建工具链)。+`whoami` 还会比较已安装 `.app/EXUpdates.bundle/fingerprint` 与当前 worktree 的Expo Updates 开发指纹。`native-mismatch` 或 `native-unknown` 不能作为可测试状态,-即使版本号、Metro 和页面都正常也要先普通重建。重建入口同样检查缓存、构建产物和安装后+即使版本号、Metro 和页面都正常也不能交付。若未知源于工具探测或指纹计算失败,先修复检查;+确认包缺失、不匹配或缺少兼容性证据时走普通重建。重建入口同样检查缓存、构建产物和安装后的真实指纹,避免跨 worktree 复用不兼容的原生包;不匹配的缓存会跳过。不要通过临时修改JS 参数协议来适配另一版本原生依赖。此检查不修改 App 配置或发布指纹。@@ -86,6 +92,15 @@ JSON 已包含 `worktree` / `expectedSource`、`region` / `bundleId`、目标设`pageVerified: false` 明确保留这个边界。页面/bundle 验证与截图按模拟器调试手册另外完成,证据放在同一任务目录。+### 仓库与个人配置的边界++- 仓库维护工具要求、脚本参数、缓存与身份校验、mock 场景和验收合同;个人 Skill 调用这些入口,+ 不再实现第二套指纹、bundle ID 或缓存解析。+- 默认区域、设备偏好、模拟器后端、接管时机与工具管理方式属于开发者的本地 profile/工作流。+ 本次明确指定的设备或区域高于个人默认;本次覆盖不自动写回 profile。+- 自定义 bundle ID、签名团队与私有端点留在本地配置;仓库提供模板和校验,凭证进入凭证存储。+- 设备在线状态、已安装包、Metro 占用、工具位置和缓存命中是现场事实,每次探测,不作为长期偏好。+不要用临时 Metro、端口探测或手工修改 `.env` 代替这些脚本。多 worktree、原生构建、登录态和日志排查见 `apps/mobile/docs/simulator-debugging.md`。