# ios-trace

Adopt this skill: https://proskills.md/skills/other/kmgcc-ios-trace

Page: https://proskills.md/skills/other/kmgcc-ios-trace
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 7975
sha: 51b66ffaca9163711f0e72ff007d3fe9631bd9b0
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/SKILL.md

```text
---
name: ios-trace
description: "Agent-native runbook for evidence-based profiling and optimization of native iOS and iPadOS apps with xctrace and Xcode Instruments on physical devices or simulators. Use for CPU or battery use, memory growth or Jetsam, UI hitches, slow launch, concurrency stalls, audio glitches, or network activity. Choose instruments and workload reproduction to fit the issue; bundled scripts are optional helpers."
compatibility: "macOS with Xcode or Command Line Tools providing xctrace; target support depends on the selected Xcode and device OS; Python 3.8+ only for optional helper scripts"
license: MIT
metadata:
  author: kmgcc
  version: "1.6.0"
---

# iOS-Trace

An agent-native runbook for investigating performance in native iOS and iPadOS apps. Choose tools and reproduction paths based on the reported symptom, device capabilities, and repository instructions. `xctrace` and Instruments provide the measurements; the GUI and CLI are both useful. Bundled scripts are optional helpers for repeatable exports and comparisons, not a required workflow.

## Runbook

1. **Understand the report.** Identify the affected app, user-visible symptom, reproduction steps, target OS/device class, and what evidence would show improvement. Ask only for missing details that materially affect the measurement. Do not impose generic numeric targets or assume every report needs code changes.
2. **Inspect the target and toolchain.** Read repository instructions. Check active Xcode and `xctrace` versions, installed templates, target OS, device/simulator availability, build configuration, app process/bundle identity, and permissions. Use `xcrun xctrace list devices` to distinguish available devices from offline ones. Follow repository device, signing, and test rules.
3. **Choose evidence that answers the question.** Use `references/templates.md` to select the smallest useful instrument or combination. Check the installed help for supported target types and options instead of assuming every Xcode/device pair exposes the same capability. Use Instruments UI when timelines or inspectors aid interpretation; use CLI capture/export when it is clearer and repeatable.
4. **Choose the right target.** Use a physical device for battery, energy, thermal, radio, and device-specific GPU conclusions. A simulator can help with CPU-hotspot, logic, and interaction triage; it cannot establish physical-device energy or thermal behavior. Explain the limit if only simulator evidence is available.
5. **Reproduce the real workload.** Read `references/workload-reproduction.md` when timing or interaction matters. Choose a trustworthy app hook, UI automation, test flow, or user-triggered interaction for the specific question. Verify that the action occurred and that the target app is in the recorded state. An idle trace is an optional control; it does not establish improvement to an active user scenario.
6. **Capture with comparable conditions.** Keep the app foregrounded and the device awake for UI or rendering work. For before/after runs, align device model, OS, build configuration, app content, screen brightness, power state, network conditions, interaction, and capture scope where they affect the result. Record differences and avoid conclusions broader than the evidence. A physical device or Simulator target does not move Instruments' host-side temporary files off the Mac; load `references/storage-and-recovery.md` before a capture when storage is constrained, and after a run if finalization or space recovery is abnormal.
7. **Interpret before editing.** Tie the user-visible symptom to the relevant process, interval, thread, task, allocation, frame, network event, or call tree. Cross-check a suspected hot path against source and call sites. Separate measured results from inference; avoid changes when the trace does not support a concrete hypothesis.
8. **Make a focused change and compare.** Follow repository instructions for code edits, device use, and validation. Re-run the same meaningful scenario with comparable conditions. If results are noisy, thermally constrained, or simulator-only, state that and refine the measurement before claiming success.
9. **Report and preserve.** Summarize the scenario, target/device/OS, instruments, observed bottleneck, change, measured result, and unverified layers. Treat traces and exports as potentially sensitive. Confirm `xctrace` has exited, inspect for deleted-open `.ktrace` handles, and verify free space on the affected Mac volume. Keep or remove artifacts according to the user's and repository's retention rules; never use broad temporary-file or Instruments-cache deletion.

## iOS measurement boundaries

- Power Profiler energy and CPU-impact conclusions require a supported physical device/OS combination. It is not supported by the Simulator. Verify the current Xcode/device help before capture; never infer energy or thermal results from simulator CPU traces.
- Device behavior changes with temperature, battery level, refresh rate, brightness, radio conditions, and foreground state. Repeat comparable runs on the same physical device when the question is about before/after changes.
- A device listed under `== Devices Offline ==` is unavailable for recording. Unlock and trust a physical device, and keep it awake and foregrounded for the scenario.
- Attach may be blocked by signing or OS policy. Use an authorized development build or supported launch mode; do not silently weaken signing or entitlements.
- Recording and export use storage on the Mac running Xcode even when the target is a physical iPhone/iPad. `--output` selects the final trace destination; it does not guarantee that host-side intermediate files use that volume.

## Xcode 27 and Instruments

When Xcode 27 is installed, load `references/templates.md` for new instruments and capture/export improvements. Capabilities depend on the installed Xcode and target OS. Swift Executor names require OS 27; on older systems they may appear as `Unknown executor`. The Foundation Models instrument covers Apple's Foundation Models framework, not arbitrary cloud or third-party model calls.

For optional Xcode project/build/test integration through MCP, load `references/xcode-agent-mcp.md`. MCP complements Instruments profiling; do not enable a host MCP server or widen its permissions as an implicit trace step.

## Optional helpers

- Use bundled scripts only when they fit the question or make a repetitive export/comparison easier. Resolve the skill directory dynamically and inspect a helper's usage before calling it.
- The runner does not own cleanup of shared Instruments files or services. The agent remains responsible for the post-recording checks in `references/storage-and-recovery.md`, whether or not a helper script was used; identify exact candidates and decide whether they are safe to remove, or ask the user when ownership or impact is unclear.
- Never edit scripts inside the installed skill. For a one-off parser adjustment, copy only the relevant helper to a task scratch directory and change the copy.
- If the app already has a project-specific profiling workflow, follow its instructions and device/process/data boundaries before using generic examples here.

## References (load as needed)

- `references/templates.md` — choose instruments by symptom; includes Xcode 27 additions.
- `references/workload-reproduction.md` — selecting and verifying device/simulator workload reproduction.
- `references/device-commands.md` — device discovery, process selection, xctrace capabilities, capture, and export.
- `references/storage-and-recovery.md` — host-side temporary storage, deleted-open `.ktrace` diagnosis, and safe recovery after recording.
- `references/xcode-agent-mcp.md` — optional Xcode 27 MCP integration and safe capability discovery.
- `references/subsystems.md` — optimization patterns for radio, ProMotion, media decoding, audio, and other app subsystems.
```

## File: README.md
size: 3413
sha: fd1368b9f94232aea4407c00882ce0c12dfbfe17
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/README.md

````text
# iOS-Trace

[中文](README.md) | [English](README_en.md)

[![Agent Skills Open Standard](https://img.shields.io/badge/Agent_Skills-Open_Standard-blueviolet.svg)](https://agentskills.io)
[![Install](https://img.shields.io/badge/Install-npx_skills_add-000000.svg)](https://skills.sh/kmgcc/iOS-Trace)
[![Platform](https://img.shields.io/badge/Platform-iOS_%2F_iPadOS-black.svg)](https://developer.apple.com/ios/)
[![Tooling](https://img.shields.io/badge/Xcode-Instruments_%2F_xctrace-007AFF.svg)](https://developer.apple.com/xcode/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> 需要 macOS 桌面应用性能分析？见 [macOS-Trace](https://github.com/kmgcc/macOS-Trace)。

面向 AI 编码 Agent 的 iOS / iPadOS 性能分析 runbook。Agent 根据真实症状和目标设备选择 Instruments、复现路径与验收证据；真机与模拟器各有不同测量边界。附带脚本仅是可选的数据处理工具，不是固定执行流程。

## 前置条件

- macOS 上可用的 Xcode 或 Command Line Tools；目标支持范围由当前 Xcode 与设备 OS 决定。Xcode 27 要求 macOS Tahoe 26.6 或更新版本，并仅支持 Apple silicon Mac。
- 真机需在线、解锁并信任此 Mac；真机 attach 和 UI 测试还受签名、Developer Mode 与系统版本影响。
- Python 3.8+ 仅用于可选脚本。

## 安装

### 推荐：skills CLI

```bash
npx skills add kmgcc/iOS-Trace
```

使用 `-g` 安装到用户级目录；可用 `-a` 选择 CLI 支持的 Agent。

### 手动安装

| Agent | 用户级全局目录 |
| :--- | :--- |
| Codex | `~/.agents/skills/ios-trace` |
| Antigravity | `~/.gemini/config/skills/ios-trace` |
| DSH | `~/.dsh/skills/ios-trace` |
| Claude Code | `~/.claude/skills/ios-trace` |
| Cursor | `~/.cursor/skills/ios-trace` |
| OpenCode | `~/.config/opencode/skills/ios-trace` |

把仓库内容放入对应目录即可。具体发现路径可能随 Agent 版本变化；项目级安装请遵循该 Agent 当前文档。

## 使用

要求 Agent 使用 `ios-trace` 调查明确的用户场景，例如真机滚动掉帧、发热、启动变慢、音频断续或内存增长。Agent 会按目标选择设备、采样器、复现方式和对比方法；不需要先运行固定脚本。

## 文档地图

- `SKILL.md` — 核心执行 runbook。
- `references/templates.md` — Instruments 选择指南与 Xcode 27 增强项。
- `references/workload-reproduction.md` — 按问题选择真机或模拟器的复现路径。
- `references/device-commands.md` — 设备发现、进程确认、xctrace 能力发现、记录与导出。
- `references/storage-and-recovery.md` — Mac 主机临时空间、已删除但仍打开的 `.ktrace` 诊断与安全恢复。
- `references/xcode-agent-mcp.md` — 可选 Xcode MCP 工作流及权限边界。
- `references/subsystems.md` — 射频、ProMotion、媒体解码、音频等优化线索。

## 使用边界

- 模拟器结果适合部分 CPU、逻辑和 UI 排查，不能证明真机功耗、射频或热表现。
- trace 可能包含提示词、路径、媒体或日志信息，按敏感任务数据处理。
- MCP 是可选的 Xcode 项目/开发集成；运行时性能证据来自 Instruments。
- 遵循项目自身的进程、设备、数据所有权、构建、测试和发布规则。

## License

MIT License。见 [LICENSE](LICENSE)。
````

## File: scripts/activity_cpu.py
size: 5728
sha: 288c7002946300ecbb31ebfd3c2b5b76d3f353cc
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/activity_cpu.py

```text
#!/usr/bin/env python3
"""
Parse an xctrace 'activity-monitor-process-live' XML export into per-process
CPU utilization (ms of CPU per second of wall time) and memory footprint.

Works on the exact XML shape emitted by:
    xcrun xctrace export --input <trace> \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='activity-monitor-process-live']"

Each row is one process snapshot at one sampling interval (rows are ordered in
time; the first row defines the process name via <process id=.. fmt="Name (pid)">,
later rows reference it):
  <duration>            wall-clock length of this sampling interval (ns)
  <duration-on-core>    CUMULATIVE CPU time consumed by the process (ns) — the
                        per-interval CPU is the delta between consecutive rows.

So per-second CPU load for interval i = (cpu[i] - cpu[i-1]) * 1000 / duration[i],
expressed as ms of CPU per second of wall time (1000 ms/s ≈ one full core).

Usage:
    python3 activity_cpu.py <xml_path> [process_name_filter]

Arguments:
    <xml_path>            Exported 'activity-monitor-process-live' table XML.
    [process_name_filter] Optional substring; only process names containing it
                          are summarized (e.g. 'VioRelay' matches 'VioRelay (5177)';
                          use '.app/VioRelay' to exclude 'VioRelayWidgets').

Example:
    python3 activity_cpu.py /tmp/ios-traces/actmon-pre.xml VioRelay
    # Repeat for pre/post runs and compare the Avg CPU (ms/s) line for A/B deltas.

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""

import re
import sys
import os

ROW_RE = re.compile(r'<row[^>]*>(.*?)</row>', re.S)
PROC_DEF_RE = re.compile(r'<process\s+id="\d+"\s+fmt="([^"]*)"')
DUR_RE = re.compile(r'<duration\s+id="\d+"\s+fmt="[^"]*">(\d+)</duration>')
CPU_RE = re.compile(r'<duration-on-core\s+id="\d+"\s+fmt="[^"]*">(\d+)</duration-on-core>')
MEM_RE = re.compile(r'<size-in-bytes\s+id="\d+"\s+fmt="[^"]*">(\d+)</size-in-bytes>')

def parse(path):
    """Return per-sample dicts for every row (ordered), with resolved process name."""
    with open(path, encoding='utf-8', errors='replace') as f:
        xml = f.read()

    samples = []
    cur_name = None
    cur_mem = 0
    cur_cpu = None
    cur_dur = None

    for rm in ROW_RE.finditer(xml):
        body = rm.group(1)

        pm = PROC_DEF_RE.search(body)
        if pm:
            cur_name = pm.group(1)

        dm = DUR_RE.search(body)
        cm = CPU_RE.search(body)
        mm = MEM_RE.search(body)

        dur = int(dm.group(1)) / 1e6 if dm else None
        cpu = int(cm.group(1)) / 1e6 if cm else None
        mem = int(mm.group(1)) / 1e6 if mm else None

        # First row of a new process: cpu is cumulative from process start, no delta.
        if cur_cpu is None:
            prev_cpu = cpu
        else:
            prev_cpu = cur_cpu

        if cpu is not None:
            cur_cpu = cpu
        if dur is not None:
            cur_dur = dur
        if mem is not None:
            cur_mem = mem

        # CPU load for this interval = (cpu - prev_cpu) ms of CPU per dur seconds,
        # normalized to ms per second.
        load = None
        if cpu is not None and prev_cpu is not None and cur_dur:
            load = (cpu - prev_cpu) * 1000.0 / cur_dur

        samples.append({
            'name': cur_name,
            'duration_ms': cur_dur or 0,
            'cpu_ms_s': load,
            'mem_mb': cur_mem,
        })

    return samples

def main():
    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 else 1)

    path = sys.argv[1]
    if not os.path.exists(path):
        print(f"Error: file not found: {path}", file=sys.stderr)
        sys.exit(1)
    if os.path.isdir(path) or path.endswith('.trace'):
        print(
            f"Error: Expected an exported XML file, but got a .trace bundle: {path}\n"
            f"Please export it first using:\n"
            f"  xcrun xctrace export --input \"{path}\" "
            f"--xpath \"/trace-toc/run[@number='1']/data/table[@schema='activity-monitor-process-live']\" > \"{path.replace('.trace', '-actmon.xml')}\"",
            file=sys.stderr,
        )
        sys.exit(1)

    filt = sys.argv[2] if len(sys.argv) > 2 else None
    samples = parse(path)

    # Group consecutive samples by process name.
    by_proc = {}
    for s in samples:
        nm = s['name']
        if nm is None:
            continue
        if filt and filt not in nm:
            continue
        by_proc.setdefault(nm, []).append(s)

    if not by_proc:
        print(f"No rows matched filter {filt!r}.")
        return

    print(f"Activity Monitor CPU summary: {path}")
    if filt:
        print(f"Filter: process name contains {filt!r}")
    print("=" * 88)
    print(f"{'Process':<40} {'Samples':>7} {'Avg CPU':>9} {'Max CPU':>9} {'Avg Mem':>12}")
    print("-" * 88)

    results = []
    for name, rs in sorted(by_proc.items(), key=lambda kv: -max((r['cpu_ms_s'] or 0) for r in kv[1])):
        loads = [r['cpu_ms_s'] for r in rs if r['cpu_ms_s'] is not None]
        if not loads:
            continue
        avg = sum(loads) / len(loads)
        mx = max(loads)
        avg_mem = sum(r['mem_mb'] for r in rs) / len(rs)
        results.append((name, len(loads), avg, mx, avg_mem))

    for name, n, avg, mx, mem in results:
        print(f"{name[:38]:<40} {n:>7} {avg:>8.0f}ms/s {mx:>8.0f}ms/s {mem:>10.1f}MB")

    print("-" * 88)
    print("CPU is ms of CPU per second of wall time (1000 ms/s ≈ one full core).")
    print("Compare Avg values across idle/pre/post runs for A/B deltas.")
    print()

if __name__ == '__main__':
    main()
```

## File: scripts/compare_cpu.py
size: 5807
sha: 2be8a6cef66f1491946bf40eefaef6c4d8c93e74
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/compare_cpu.py

```text
#!/usr/bin/env python3
"""
Compare multiple Activity Monitor runs and print a differential table, so A/B
regression checks still work when Power Profiler is unavailable (iOS < 26).

Reuses the same parsing as activity_cpu.py: per-interval CPU load is derived
from the cumulative duration-on-core delta, normalized to ms of CPU per second
of wall time (1000 ms/s ≈ one full core).

Usage:
    python3 compare_cpu.py <xml_path:label> <xml_path:label> ...
    python3 compare_cpu.py /tmp/ios-traces/idle-actmon.xml:"1. Idle" \
                           /tmp/ios-traces/pre-actmon.xml:"2. Pre-Opt" \
                           /tmp/ios-traces/post-actmon.xml:"3. Post-Opt"

Arguments:
    <xml_path:label>  Path to an exported 'activity-monitor-process-live' XML,
                      optionally followed by ':Label'. If ':Label' is omitted,
                      the filename without extension is used. The first XML is
                      the baseline; each later run is diffed against it.
    --process <name>  Optional; only summarize processes whose name contains
                      this substring (e.g. 'VioRelay').

Example:
    python3 compare_cpu.py idle.xml:"Idle" pre.xml:"Pre" post.xml:"Post" --process VioRelay

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""

import re
import sys
import os

ROW_RE = re.compile(r'<row[^>]*>(.*?)</row>', re.S)
PROC_DEF_RE = re.compile(r'<process\s+id="\d+"\s+fmt="([^"]*)"')
DUR_RE = re.compile(r'<duration\s+id="\d+"\s+fmt="[^"]*">(\d+)</duration>')
CPU_RE = re.compile(r'<duration-on-core\s+id="\d+"\s+fmt="[^"]*">(\d+)</duration-on-core>')
MEM_RE = re.compile(r'<size-in-bytes\s+id="\d+"\s+fmt="[^"]*">(\d+)</size-in-bytes>')

def parse(path):
    """Return list of {name, duration_ms, cpu_ms_s, mem_mb} per sample."""
    with open(path, encoding='utf-8', errors='replace') as f:
        xml = f.read()

    samples = []
    cur_name = None
    cur_mem = 0.0
    cur_cpu = None
    cur_dur = None

    for rm in ROW_RE.finditer(xml):
        body = rm.group(1)
        pm = PROC_DEF_RE.search(body)
        if pm:
            cur_name = pm.group(1)
        dm = DUR_RE.search(body)
        cm = CPU_RE.search(body)
        mm = MEM_RE.search(body)

        dur = int(dm.group(1)) / 1e6 if dm else None
        cpu = int(cm.group(1)) / 1e6 if cm else None
        mem = int(mm.group(1)) / 1e6 if mm else None

        prev_cpu = cur_cpu
        if cpu is not None:
            cur_cpu = cpu
        if dur is not None:
            cur_dur = dur
        if mem is not None:
            cur_mem = mem

        load = None
        if cpu is not None and prev_cpu is not None and cur_dur:
            load = (cpu - prev_cpu) * 1000.0 / cur_dur

        samples.append({
            'name': cur_name,
            'duration_ms': cur_dur or 0,
            'cpu_ms_s': load,
            'mem_mb': cur_mem,
        })
    return samples

def summarize(path, label, filt):
    samples = parse(path)
    by_proc = {}
    for s in samples:
        nm = s['name']
        if nm is None:
            continue
        if filt and filt not in nm:
            continue
        by_proc.setdefault(nm, []).append(s)

    # Pick the process with the highest observed CPU load (usually the target).
    best = None
    for name, rs in by_proc.items():
        loads = [r['cpu_ms_s'] for r in rs if r['cpu_ms_s'] is not None]
        if not loads:
            continue
        if best is None or max(loads) > best['max']:
            best = {'name': name, 'loads': loads,
                    'mem': sum(r['mem_mb'] for r in rs) / len(rs)}
    if best is None:
        return {'label': label, 'path': path, 'present': False}
    avg = sum(best['loads']) / len(best['loads'])
    return {
        'label': label, 'path': path, 'present': True,
        'name': best['name'], 'n': len(best['loads']),
        'avg': avg, 'max': max(best['loads']),
        'mem_mb': best['mem'],
    }

def main():
    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 else 1)

    filt = None
    if '--process' in sys.argv:
        i = sys.argv.index('--process')
        filt = sys.argv[i + 1]
        del sys.argv[i:i + 2]

    targets = []
    for arg in sys.argv[1:]:
        if not arg.strip():
            continue
        if ':' in arg:
            path, label = arg.split(':', 1)
        else:
            path = arg
            label = os.path.splitext(os.path.basename(path))[0]
        targets.append((path, label))

    results = []
    for path, label in targets:
        try:
            results.append(summarize(path, label, filt))
        except Exception as e:
            print(f"Error parsing '{path}': {e}", file=sys.stderr)
            sys.exit(1)

    print()
    print(f"{'Scenario':<26} {'Process':<30} {'Avg CPU':>9} {'Max CPU':>9} {'Avg Mem':>10}")
    print("=" * 92)
    for r in results:
        if not r['present']:
            print(f"{r['label']:<26} {'(no matching rows)':<30}")
            continue
        print(f"{r['label']:<26} {r['name'][:28]:<30} {r['avg']:>8.0f}ms/s {r['max']:>8.0f}ms/s {r['mem_mb']:>9.1f}MB")

    if len(results) > 1 and all(r['present'] for r in results):
        base = results[0]
        print("-" * 92)
        print(f"Differential vs Baseline [{base['label']}]:")
        for r in results[1:]:
            d_avg = r['avg'] - base['avg']
            d_mem = r['mem_mb'] - base['mem_mb']
            pct = (d_avg / base['avg'] * 100) if base['avg'] else 0
            print(f"  {r['label']:<24} CPU {d_avg:+.0f} ms/s ({pct:+.1f}%)   Mem {d_mem:+.1f} MB")
    print()
    print("CPU is ms of CPU per second of wall time (1000 ms/s ≈ one full core).")
    print()

if __name__ == '__main__':
    main()
```

## File: scripts/compare_elements.py
size: 6873
sha: 0712f7bb657b985282329dc3e93502f985147494
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/compare_elements.py

```text
#!/usr/bin/env python3
"""
Compare per-scenario Power Profiler runs for iOS applications and devices.

Usage:
    python3 compare_elements.py <xml_path:label> <xml_path:label> ...
    python3 compare_elements.py /tmp/ios-traces/idle.xml:"1. Idle Baseline" /tmp/ios-traces/streaming.xml:"2. Active Streaming"

Arguments:
    <xml_path:label>  Path to exported ProcessSubsystemPowerImpact XML, optionally followed by ':Label'.
                      If ':Label' is omitted, the filename without extension will be used.
                      The first XML provided is treated as the Baseline for differential (delta) calculations.

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""

import sys
import os
import re

COLUMNS = ['start', 'duration', 'process', 'process-name', 'cpu', 'display',
           'instr', 'gpu', 'net', 'wifi_rx', 'wifi_tx', 'cell_rx', 'cell_tx', 'kind']
TOKEN_RE = re.compile(r'<(sentinel|process|pid|device-session|[\w-]+)(?:\s+[^>]*?)?(?:>(?P<val>.*?)</\1>|/>)', re.S)

def parse(path):
    if not os.path.exists(path):
        raise FileNotFoundError(f"File not found: {path}")

    if os.path.isdir(path) or path.endswith('.trace'):
        raise ValueError(
            f"Expected an exported XML file, but got a .trace bundle: {path}\n"
            f"Please export it first using:\n"
            f"  xcrun xctrace export --input \"{path}\" "
            f"--xpath \"/trace-toc/run[@number='1']/data/table[@schema='ProcessSubsystemPowerImpact']\" > \"{path.replace('.trace', '-power.xml')}\""
        )

    with open(path, encoding='utf-8', errors='replace') as f:
        xml = f.read()

    idmap = {}
    for m in re.finditer(r'<([\w-]+)\s+id="(\d+)"\s+fmt="[^"]*">(.*?)</\1>', xml, re.S):
        idmap[int(m.group(2))] = m.group(3).strip()

    rows = []
    for m in re.finditer(r'<row[^>]*>(.*?)</row>', xml, re.S):
        body = m.group(1)
        tokens = []
        for tm in TOKEN_RE.finditer(body):
            name = tm.group(1)
            if name in ('pid', 'device-session'):
                continue
            if name in ('sentinel', 'process'):
                tokens.append(None)
                continue
            val = tm.group('val')
            if val is not None:
                tokens.append(val.strip())
            else:
                rm = re.search(r'ref="(\d+)"', tm.group(0))
                tokens.append(idmap.get(int(rm.group(1))) if rm else None)

        row = {c: None for c in COLUMNS}
        for i, v in enumerate(tokens[:len(COLUMNS)]):
            row[COLUMNS[i]] = v
        rows.append(row)

    return rows

def num(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None

def summarize(path, label):
    rows = parse(path)
    # kind '0' = regular per-second samples (cpu, display, instr, gpu)
    reg = [r for r in rows if r.get('kind') == '0']
    # kind '1' = networking samples (wifi, cellular)
    net = [r for r in rows if r.get('kind') == '1']

    n_sec = len(reg)
    cpu_vals = [num(r['cpu']) for r in reg if num(r['cpu']) is not None]
    disp_vals = [num(r['display']) for r in reg if num(r['display']) is not None]
    gpu_vals = [num(r['gpu']) for r in reg if num(r['gpu']) is not None]
    instr = sum(num(r['instr']) or 0 for r in reg)

    wifi_tx = sum(num(r['wifi_tx']) or 0 for r in net)
    wifi_rx = sum(num(r['wifi_rx']) or 0 for r in net)

    def avg(vals):
        return sum(vals)/len(vals) if vals else None

    return {
        'label': label,
        'path': path,
        'n_sec': n_sec,
        'cpu_avg': avg(cpu_vals),
        'cpu_max': max(cpu_vals) if cpu_vals else None,
        'disp_avg': avg(disp_vals),
        'gpu_avg': avg(gpu_vals),
        'instr_total': instr,
        'instr_per_s': instr / n_sec if n_sec > 0 else 0,
        'wifi_tx_kib': wifi_tx / 1024,
        'wifi_rx_kib': wifi_rx / 1024,
    }

def main():
    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 else 1)

    targets = []
    for arg in sys.argv[1:]:
        if ':' in arg:
            path, label = arg.split(':', 1)
        else:
            path = arg
            label = os.path.splitext(os.path.basename(path))[0]
        targets.append((path, label))

    results = []
    for path, label in targets:
        try:
            results.append(summarize(path, label))
        except Exception as e:
            print(f"Error parsing '{path}': {e}", file=sys.stderr)
            sys.exit(1)

    has_net = any(r['wifi_tx_kib'] > 0 or r['wifi_rx_kib'] > 0 for r in results)

    print()
    if has_net:
        print(f"{'Scenario':<24} {'Sec':>4} {'CPU Avg':>8} {'CPU Max':>8} {'Display':>8} {'GPU Avg':>8} {'Total Instr':>12} {'Instr M/s':>10} {'WiFi Tx/Rx':>12}")
        print("=" * 105)
    else:
        print(f"{'Scenario':<26} {'Sec':>4} {'CPU Avg':>8} {'CPU Max':>8} {'Display':>8} {'GPU Avg':>8} {'Total Instr':>12} {'Instr M/s':>10}")
        print("=" * 92)

    for r in results:
        disp_str = f"{r['disp_avg']:>8.2f}" if r['disp_avg'] is not None else f"{'—':>8}"
        gpu_str = f"{r['gpu_avg']:>8.2f}" if r['gpu_avg'] is not None else f"{'—':>8}"
        cpu_avg_str = f"{r['cpu_avg']:>8.2f}" if r['cpu_avg'] is not None else f"{'—':>8}"
        cpu_max_str = f"{r['cpu_max']:>8.1f}" if r['cpu_max'] is not None else f"{'—':>8}"
        instr_g_str = f"{r['instr_total']/1e9:>11.2f}G"
        instr_m_str = f"{r['instr_per_s']/1e6:>10.1f}"

        if has_net:
            wifi_str = f"{r['wifi_tx_kib']/1024:.1f}/{r['wifi_rx_kib']/1024:.1f}MB"
            print(f"{r['label']:<24} {r['n_sec']:>4} {cpu_avg_str} {cpu_max_str} "
                  f"{disp_str} {gpu_str} {instr_g_str} {instr_m_str} {wifi_str:>12}")
        else:
            print(f"{r['label']:<26} {r['n_sec']:>4} {cpu_avg_str} {cpu_max_str} "
                  f"{disp_str} {gpu_str} {instr_g_str} {instr_m_str}")

    if len(results) > 1:
        base = results[0]['instr_per_s']
        base_label = results[0]['label']
        divider_len = 105 if has_net else 92
        print("-" * divider_len)
        print(f"Differential vs Baseline [{base_label}]:")
        for r in results[1:]:
            d_instr = (r['instr_per_s'] - base) / 1e6
            d_cpu = (r['cpu_avg'] - results[0]['cpu_avg']) if (r['cpu_avg'] is not None and results[0]['cpu_avg'] is not None) else None
            cpu_diff_str = f", CPU Avg Delta {d_cpu:+.2f}" if d_cpu is not None else ""
            net_delta_str = ""
            if has_net:
                d_tx = r['wifi_tx_kib'] - results[0]['wifi_tx_kib']
                net_delta_str = f", WiFi Tx Delta {d_tx/1024:+.2f}MB"
            print(f"  {r['label']:<24} {d_instr:>+8.1f} M/s instructions{cpu_diff_str}{net_delta_str}")
    print()

if __name__ == '__main__':
    main()
```

## File: scripts/parse_power.py
size: 5455
sha: ab36eaa5659a0e69695f0c5764ed8ba3eb013651
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/parse_power.py

```text
#!/usr/bin/env python3
"""
Parse Power Profiler ProcessSubsystemPowerImpact XML for iOS devices and apps.

Usage:
    python3 parse_power.py <path_to_xml> [scenario_label]
    python3 parse_power.py /tmp/ios-traces/streaming-power.xml "Audio Streaming Active"

Arguments:
    <path_to_xml>     Path to exported ProcessSubsystemPowerImpact XML.
    [scenario_label]  Optional descriptive label for the run.

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""

import sys
import os
import re
from collections import defaultdict

COLUMNS = ['start', 'duration', 'process', 'process-name', 'cpu', 'display',
           'instr', 'gpu', 'net', 'wifi_rx', 'wifi_tx', 'cell_rx', 'cell_tx', 'kind']
TOKEN_RE = re.compile(r'<(sentinel|process|pid|device-session|[\w-]+)(?:\s+[^>]*?)?(?:>(?P<val>.*?)</\1>|/>)', re.S)

def parse(path):
    if not os.path.exists(path):
        raise FileNotFoundError(f"File not found: {path}")

    if os.path.isdir(path) or path.endswith('.trace'):
        raise ValueError(
            f"Expected an exported XML file, but got a .trace bundle: {path}\n"
            f"Please export it first using:\n"
            f"  xcrun xctrace export --input \"{path}\" "
            f"--xpath \"/trace-toc/run[@number='1']/data/table[@schema='ProcessSubsystemPowerImpact']\" > \"{path.replace('.trace', '-power.xml')}\""
        )

    with open(path, encoding='utf-8', errors='replace') as f:
        xml = f.read()

    idmap = {}
    for m in re.finditer(r'<([\w-]+)\s+id="(\d+)"\s+fmt="[^"]*">(.*?)</\1>', xml, re.S):
        idmap[int(m.group(2))] = m.group(3).strip()

    rows = []
    for m in re.finditer(r'<row(?P<attrs>[^>]*)>(?P<body>.*?)</row>', xml, re.S):
        body = m.group('body')
        tokens = []
        for tm in TOKEN_RE.finditer(body):
            name = tm.group(1)
            if name in ('pid', 'device-session'):
                continue
            if name == 'sentinel':
                tokens.append(None)
                continue
            if name == 'process':
                tokens.append(None)
                continue
            val = tm.group('val')
            if val is not None:
                tokens.append(val.strip())
            else:
                rm = re.search(r'ref="(\d+)"', tm.group(0))
                tokens.append(idmap.get(int(rm.group(1))) if rm else None)

        row = {c: None for c in COLUMNS}
        for i, v in enumerate(tokens[:len(COLUMNS)]):
            row[COLUMNS[i]] = v
        rows.append(row)

    return rows

def num(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None

def summarize(path, label=None):
    if label is None:
        label = os.path.basename(path)
    rows = parse(path)

    print(f"\n===== [iOS Power Impact Summary] {label} =====")
    print(f"Data Source:       {path}")
    print(f"Total Table Rows:  {len(rows)}")

    kinds = defaultdict(int)
    for r in rows:
        kinds[r.get('kind')] += 1

    def avgmax(key, pred=None):
        vals = [num(r[key]) for r in rows if num(r[key]) is not None and (pred is None or pred(r))]
        if not vals:
            return None, None
        return sum(vals) / len(vals), max(vals)

    cpu_avg, cpu_max = avgmax('cpu', lambda r: r.get('kind') == '0')
    disp_avg, disp_max = avgmax('display', lambda r: r.get('kind') == '0')
    gpu_avg, gpu_max = avgmax('gpu', lambda r: r.get('kind') == '0')
    net_avg, _ = avgmax('net', lambda r: r.get('kind') == '1')
    instr_total = sum(num(r['instr']) or 0 for r in rows if r.get('kind') == '0')
    n_sec = sum(1 for r in rows if r.get('kind') == '0')
    instr_per_s = instr_total / n_sec if n_sec > 0 else 0

    wifi_tx = sum(num(r['wifi_tx']) or 0 for r in rows if r.get('kind') == '1')
    wifi_rx = sum(num(r['wifi_rx']) or 0 for r in rows if r.get('kind') == '1')
    cell_tx = sum(num(r['cell_tx']) or 0 for r in rows if r.get('kind') == '1')
    cell_rx = sum(num(r['cell_rx']) or 0 for r in rows if r.get('kind') == '1')

    print(f"Effective Duration: {n_sec}s (1Hz metric samples)")
    print(f"CPU Impact:        Avg {cpu_avg:.2f}  | Max {cpu_max:.2f}" if cpu_avg is not None else "CPU Impact:        —")
    print(f"Display Impact:    Avg {disp_avg:.2f}  | Max {disp_max:.2f}" if disp_avg is not None else "Display Impact:    —")
    print(f"GPU Impact:        Avg {gpu_avg:.2f}  | Max {gpu_max:.2f}" if gpu_avg is not None else "GPU Impact:        —")
    print(f"Network Impact:    Avg {net_avg:.2f}" if net_avg is not None else "Network Impact:    —")
    print(f"Total CPU Instr:   {instr_total/1e9:.3f} G (Giga-instructions)")
    print(f"Instruction Rate:  {instr_per_s/1e6:.1f} M/s (Mega-instructions/sec)")
    if wifi_tx > 0 or wifi_rx > 0:
        print(f"WiFi Tx / Rx:      {wifi_tx/1024:.1f} KiB / {wifi_rx/1024:.1f} KiB")
    if cell_tx > 0 or cell_rx > 0:
        print(f"Cellular Tx / Rx:  {cell_tx/1024:.1f} KiB / {cell_rx/1024:.1f} KiB")
    print("==============================================\n")
    return rows

def main():
    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 else 1)

    path = sys.argv[1]
    label = sys.argv[2] if len(sys.argv) > 2 else None
    try:
        summarize(path, label)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()
```

## File: scripts/run_trace.sh
size: 13372
sha: 4265721e2e2763e33db81a2c73bbdf5aaabde440
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/run_trace.sh

```text
#!/usr/bin/env bash
# iOS-Trace Automation Runner
# Headless Instruments profiling for iOS physical devices and simulators.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUTPUT_DIR="/tmp/ios-traces"
TEMPLATE="Power Profiler"
DURATION="60s"
DEVICE=""
BUNDLE_ID=""
ATTACH_PID=""
PROCESS_NAME=""
LABEL=""
AUTO_ANALYZE=1
EXTRA_LAUNCH_ARGS=()

usage() {
  cat <<EOF
iOS-Trace Automated Runner

Usage:
  $(basename "$0") [options]

Target Device:
  -d, --device <UDID|Name>    Physical iPhone/iPad UDID or Simulator name/UUID.
                              Run 'xcrun xctrace list devices' to list available devices.
                              If omitted, the script checks for the first connected device.

Target Application (Required: choose one):
  -b, --bundle-id <id>        Bundle identifier to launch (e.g. 'com.example.MyApp').
  -a, --attach <PID>          PID of already running app on device.
  -p, --process <name>        Process name to locate on device via devicectl and attach.

Profiling Options:
  -t, --template <name>       Instruments template. Supports shorthands:
                              power       -> 'Power Profiler' (default; iOS 26+ only)
                              time        -> 'Time Profiler'
                              activity    -> 'Activity Monitor'
                              alloc       -> 'Allocations'
                              leaks       -> 'Leaks'
                              metal       -> 'Metal System Trace'
                              hitches     -> 'Animation Hitches'
                              swiftui     -> 'SwiftUI'
                              concurrency -> 'Swift Concurrency'
                              launch      -> 'App Launch'
                              network     -> 'Network'
                              counters    -> 'CPU Counters'
                              Or specify any exact Instruments template name.
  -l, --duration <time>       Recording duration limit (default: 60s, e.g. 30s, 120s)
  -o, --output-dir <path>     Directory to save .trace and exported .xml files (default: /tmp/ios-traces)
  --label <text>              Custom label for run output (default: bundle ID or process name)
  --no-analyze                Skip automatic XML export and Python analysis

Notes:
  - Power Profiler requires the device to run iOS 26 or newer. On older iOS,
    use --template time (Time Profiler, hot call-trees) plus --template activity
    (Activity Monitor, per-process CPU ms/s) as the energy/CPU fallback pair.
  - Auto-analysis per template: power -> parse_power.py; time -> top_time.py;
    activity -> activity_cpu.py; alloc -> top_categories.py.

Examples:
  # 1. Profile running iOS app on physical device for 60s with Power Profiler:
  $(basename "$0") --device "00008140-000C54310E82801C" --process "MyApp" --template power --duration 60s

  # 2. Launch app cold on device under Power Profiler:
  $(basename "$0") --device "00008140-000C54310E82801C" --bundle-id "com.example.MyApp" --template power

  # 3. Profile UI animation hitches during UI interactions on iOS Simulator:
  $(basename "$0") --device "iPhone 17 Pro Max Simulator" --process "MyApp" --template hitches --duration 30s

  # 4. iOS < 26 device: Time Profiler hot spots + Activity Monitor CPU fallback:
  $(basename "$0") --device "00008140-000C54310E82801C" --bundle-id "com.example.MyApp" --template time --duration 60s
  $(basename "$0") --device "00008140-000C54310E82801C" --process "MyApp" --template activity --duration 30s
EOF
  exit 0
}

# Parse options
while [[ $# -gt 0 ]]; do
  case "$1" in
    -d|--device)
      DEVICE="$2"
      shift 2
      ;;
    -b|--bundle-id)
      BUNDLE_ID="$2"
      shift 2
      ;;
    -a|--attach)
      ATTACH_PID="$2"
      shift 2
      ;;
    -p|--process)
      PROCESS_NAME="$2"
      shift 2
      ;;
    -t|--template)
      case "$2" in
        power)       TEMPLATE="Power Profiler" ;;
        time)        TEMPLATE="Time Profiler" ;;
        activity)    TEMPLATE="Activity Monitor" ;;
        alloc)       TEMPLATE="Allocations" ;;
        leaks)       TEMPLATE="Leaks" ;;
        metal)       TEMPLATE="Metal System Trace" ;;
        hitches)     TEMPLATE="Animation Hitches" ;;
        swiftui)     TEMPLATE="SwiftUI" ;;
        concurrency) TEMPLATE="Swift Concurrency" ;;
        launch)      TEMPLATE="App Launch" ;;
        network)     TEMPLATE="Network" ;;
        counters)    TEMPLATE="CPU Counters" ;;
        *)           TEMPLATE="$2" ;;
      esac
      shift 2
      ;;
    -l|--duration)
      DURATION="$2"
      shift 2
      ;;
    -o|--output-dir)
      OUTPUT_DIR="$2"
      shift 2
      ;;
    --label)
      LABEL="$2"
      shift 2
      ;;
    --no-analyze)
      AUTO_ANALYZE=0
      shift
      ;;
    -h|--help)
      usage
      ;;
    --)
      shift
      EXTRA_LAUNCH_ARGS=("$@")
      break
      ;;
    *)
      echo "[ERROR] Unknown option: $1" >&2
      usage
      ;;
  esac
done

# Check prerequisites
if ! command -v xcrun &>/dev/null; then
  echo "[ERROR] 'xcrun' not found. Install Xcode Command Line Tools via: xcode-select --install" >&2
  exit 1
fi

if ! xcrun xctrace version &>/dev/null; then
  echo "[ERROR] 'xctrace' is not functional. Ensure Xcode is active." >&2
  exit 1
fi

# Device discovery if not provided
if [[ -z "$DEVICE" ]]; then
  echo "[INFO] No device specified. Querying available devices..."
  # Prefer physical iPhone/iPad over other connected device types (e.g. Apple Watch)
  DETECTED_DEVICE=$(xcrun xctrace list devices 2>&1 | awk '/== Devices ==/{flag=1; next} /== Devices Offline ==/{flag=0} flag && !/Mac/ && /iPhone|iPad/ && NF {print; exit}')
  if [[ -z "$DETECTED_DEVICE" ]]; then
    DETECTED_DEVICE=$(xcrun xctrace list devices 2>&1 | awk '/== Devices ==/{flag=1; next} /== Devices Offline ==/{flag=0} flag && !/Mac/ && NF {print; exit}')
  fi
  if [[ -n "$DETECTED_DEVICE" ]]; then
    # Extract device UDID inside parentheses
    DEVICE=$(echo "$DETECTED_DEVICE" | sed -E 's/.*\(([A-Fa-f0-9-]+)\).*/\1/')
    echo "[INFO] Auto-detected connected physical device: $DETECTED_DEVICE (UDID: $DEVICE)"
  else
    echo "[ERROR] No connected physical iOS device detected." >&2
    echo "Please specify a device via --device <UDID|Name>. Run 'xcrun xctrace list devices' to list devices." >&2
    exit 1
  fi
fi

if [[ -z "$BUNDLE_ID" && -z "$ATTACH_PID" && -z "$PROCESS_NAME" ]]; then
  echo "[ERROR] You must specify a target: --bundle-id <id>, --attach <PID>, or --process <name>." >&2
  echo "Run '$(basename "$0") --help' for usage." >&2
  exit 1
fi

# Resolve process name to PID via devicectl if process name was specified
if [[ -n "$PROCESS_NAME" && -z "$ATTACH_PID" ]]; then
  echo "[INFO] Querying processes on device '$DEVICE' for '$PROCESS_NAME'..."
  if command -v xcrun &>/dev/null && xcrun devicectl help &>/dev/null; then
    # Prefer the app's main executable (path ends with '<Name>.app/<Name>') over
    # extensions/widgets (e.g. 'VioRelayWidgets'). The main process path looks like
    # '.../VioRelay.app/VioRelay'; extensions end in '.appex/<Name>'.
    FOUND_PID=$(xcrun devicectl device info processes --device "$DEVICE" 2>/dev/null \
      | awk -v name="$PROCESS_NAME" \
        'BEGIN{pick=""; pickp=""}
         $0 ~ name {
           p=$1;
           # Prefer a line whose path ends with '<name>.app/<name>' (main executable)
           if (p ~ /^[0-9]+$/ && $0 ~ ("/" name "\\.app/" name "$")) { pick=p; pickp=$0; exit }
           if (pick=="") { pick=p; pickp=$0 }
         }
         END{ if (pick!="") print pick }' || true)
    if [[ -n "$FOUND_PID" && "$FOUND_PID" =~ ^[0-9]+$ ]]; then
      ATTACH_PID="$FOUND_PID"
      echo "[INFO] Found PID $ATTACH_PID for process '$PROCESS_NAME'."
    fi
  fi

  if [[ -z "$ATTACH_PID" ]]; then
    echo "[WARN] Could not automatically resolve PID for '$PROCESS_NAME'. Will attempt process attach by name."
  fi
fi

mkdir -p "$OUTPUT_DIR"

TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
SAFE_TEMPLATE=$(echo "$TEMPLATE" | tr -d ' ' | tr '[:upper:]' '[:lower:]')

if [[ -z "$LABEL" ]]; then
  TARGET_TAG="${BUNDLE_ID:-${PROCESS_NAME:-pid$ATTACH_PID}}"
  LABEL="${TARGET_TAG}-${SAFE_TEMPLATE}"
fi

TRACE_FILE="${OUTPUT_DIR}/${LABEL}-${TIMESTAMP}.trace"

echo "========================================================================"
echo " iOS-Trace Profiling Run"
echo "========================================================================"
echo "  Device:    $DEVICE"
echo "  Template:  $TEMPLATE"
echo "  Duration:  $DURATION"
echo "  Target:    ${BUNDLE_ID:+Launch Bundle '$BUNDLE_ID'}${ATTACH_PID:+Attach PID '$ATTACH_PID'}${PROCESS_NAME:+Process '$PROCESS_NAME'}"
echo "  Output:    $TRACE_FILE"
echo "========================================================================"

# Execution
if [[ -n "$BUNDLE_ID" ]]; then
  xcrun xctrace record \
    --device "$DEVICE" \
    --template "$TEMPLATE" \
    --time-limit "$DURATION" \
    --output "$TRACE_FILE" \
    --launch -- "$BUNDLE_ID" ${EXTRA_LAUNCH_ARGS[@]+"${EXTRA_LAUNCH_ARGS[@]}"}
elif [[ -n "$ATTACH_PID" ]]; then
  xcrun xctrace record \
    --device "$DEVICE" \
    --template "$TEMPLATE" \
    --time-limit "$DURATION" \
    --output "$TRACE_FILE" \
    --attach "$ATTACH_PID"
else
  xcrun xctrace record \
    --device "$DEVICE" \
    --template "$TEMPLATE" \
    --time-limit "$DURATION" \
    --output "$TRACE_FILE" \
    --attach "$PROCESS_NAME"
fi

echo ""
echo "[INFO] Trace recorded successfully: $TRACE_FILE"
echo "[INFO] Check Mac temporary/output volume space and deleted-open .ktrace handles; see ${SCRIPT_DIR}/../references/storage-and-recovery.md. No automatic cleanup is performed."

# Post-processing / analysis
if [[ $AUTO_ANALYZE -eq 1 ]]; then
  if [[ "$TEMPLATE" == "Power Profiler" ]]; then
    XML_FILE="${OUTPUT_DIR}/${LABEL}-${TIMESTAMP}-power.xml"
    echo "[INFO] Exporting ProcessSubsystemPowerImpact table to XML..."
    xcrun xctrace export \
      --input "$TRACE_FILE" \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='ProcessSubsystemPowerImpact']" \
      > "$XML_FILE" 2>/dev/null || {
        echo "[WARN] ProcessSubsystemPowerImpact table not present or export returned non-zero."
      }

    if [[ -f "$XML_FILE" && -s "$XML_FILE" && $(grep -c '<row>' "$XML_FILE" 2>/dev/null || echo 0) -gt 0 ]]; then
      echo "[INFO] Parsing Power Impact metrics..."
      python3 "${SCRIPT_DIR}/parse_power.py" "$XML_FILE" "$LABEL"
    else
      echo "[WARN] Power Profiler produced no data rows. This template requires iOS 26+."
      echo "[HINT] On iOS < 26, use --template time (Time Profiler, hot call-trees) and"
      echo "      --template activity (Activity Monitor, per-process CPU ms/s) instead."
    fi

  elif [[ "$TEMPLATE" == "Time Profiler" ]]; then
    XML_FILE="${OUTPUT_DIR}/${LABEL}-${TIMESTAMP}-time.xml"
    echo "[INFO] Exporting time-profile table to XML..."
    xcrun xctrace export \
      --input "$TRACE_FILE" \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='time-profile']" \
      > "$XML_FILE" 2>/dev/null || {
        echo "[WARN] time-profile table not present or export returned non-zero."
      }

    if [[ -f "$XML_FILE" && -s "$XML_FILE" && $(grep -c '<row>' "$XML_FILE" 2>/dev/null || echo 0) -gt 0 ]]; then
      echo "[INFO] Parsing top CPU functions (top 25, leaf-attributed)..."
      python3 "${SCRIPT_DIR}/top_time.py" "$XML_FILE" 25 --leaf
    else
      echo "[WARN] Time Profiler produced no data rows."
    fi

  elif [[ "$TEMPLATE" == "Activity Monitor" ]]; then
    XML_FILE="${OUTPUT_DIR}/${LABEL}-${TIMESTAMP}-actmon.xml"
    echo "[INFO] Exporting activity-monitor-process-live table to XML..."
    xcrun xctrace export \
      --input "$TRACE_FILE" \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='activity-monitor-process-live']" \
      > "$XML_FILE" 2>/dev/null || {
        echo "[WARN] activity-monitor-process-live table not present or export returned non-zero."
      }

    if [[ -f "$XML_FILE" && -s "$XML_FILE" && $(grep -c '<row>' "$XML_FILE" 2>/dev/null || echo 0) -gt 0 ]]; then
      echo "[INFO] Parsing per-process CPU (ms/s)..."
      if [[ -n "$PROCESS_NAME" ]]; then
        python3 "${SCRIPT_DIR}/activity_cpu.py" "$XML_FILE" "$PROCESS_NAME"
      else
        python3 "${SCRIPT_DIR}/activity_cpu.py" "$XML_FILE"
      fi
    else
      echo "[WARN] Activity Monitor produced no data rows."
    fi

  elif [[ "$TEMPLATE" == "Allocations" ]]; then
    XML_FILE="${OUTPUT_DIR}/${LABEL}-${TIMESTAMP}-alloc.xml"
    echo "[INFO] Exporting all-allocations-summary table to XML..."
    xcrun xctrace export \
      --input "$TRACE_FILE" \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='all-allocations-summary']" \
      > "$XML_FILE" 2>/dev/null || {
        echo "[WARN] all-allocations-summary table not present or export returned non-zero."
      }

    DURATION_SEC=$(echo "$DURATION" | sed 's/[^0-9]//g')
    if [[ -z "$DURATION_SEC" ]]; then DURATION_SEC=60; fi

    if [[ -f "$XML_FILE" && -s "$XML_FILE" && $(grep -c '<row>' "$XML_FILE" 2>/dev/null || echo 0) -gt 0 ]]; then
      echo "[INFO] Parsing allocation categories..."
      python3 "${SCRIPT_DIR}/top_categories.py" "$XML_FILE" "$DURATION_SEC" 10.0
    else
      echo "[WARN] Allocations produced no data rows."
    fi
  fi
fi

echo "[INFO] iOS profiling session complete."
```

## File: scripts/top_categories.py
size: 3204
sha: 3032e627233806ecc0fb3d89e93d21d04c6da649
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/top_categories.py

```text
#!/usr/bin/env python3
"""
Analyze memory allocation categories from exported Allocations XML on iOS.

Lists allocation categories ranked by event frequency (allocations/sec), persistent bytes, and transient bytes.
Useful for identifying buffer thrashing, missing object reuse, and memory bloat.

Usage:
    python3 top_categories.py <path_to_xml> <duration_in_seconds> [min_rate]
    python3 top_categories.py /tmp/ios-traces/alloc.xml 60 10.0

Arguments:
    <path_to_xml>          Path to exported Allocations XML (table schema 'all-allocations-summary').
    <duration_in_seconds>  Duration of trace in seconds (used to compute allocation rate).
    [min_rate]             Minimum allocation rate (events/sec) to display (default: 10.0).

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""

import sys
import os
import xml.etree.ElementTree as ET

def main():
    if len(sys.argv) < 3 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help') else 1)

    path = sys.argv[1]
    if not os.path.exists(path):
        print(f"Error: file not found: {path}", file=sys.stderr)
        sys.exit(1)

    if os.path.isdir(path) or path.endswith('.trace'):
        print(
            f"Error: Expected an exported XML file, but got a .trace bundle: {path}\n"
            f"Please export it first using:\n"
            f"  xcrun xctrace export --input \"{path}\" "
            f"--xpath \"/trace-toc/run[@number='1']/data/table[@schema='all-allocations-summary']\" > \"{path.replace('.trace', '-alloc.xml')}\"",
            file=sys.stderr
        )
        sys.exit(1)

    try:
        seconds = float(sys.argv[2])
    except ValueError:
        print(f"Error: duration must be a valid number: {sys.argv[2]}", file=sys.stderr)
        sys.exit(1)

    min_rate = float(sys.argv[3]) if len(sys.argv) > 3 else 10.0

    rows = {}
    try:
        tree = ET.parse(path)
        for node in tree.iter():
            if node.tag.endswith('row'):
                cat = node.get('category')
                if cat:
                    rows[cat] = node.attrib
    except Exception as e:
        print(f"Error parsing XML: {e}", file=sys.stderr)
        sys.exit(1)

    entries = []
    for cat, attrib in rows.items():
        count = int(attrib.get('count-events', '0') or 0)
        rate = count / seconds if seconds > 0 else 0
        if rate >= min_rate:
            persistent = float(attrib.get('persistent-bytes', '0') or 0)
            transient = float(attrib.get('transient-bytes', '0') or 0)
            entries.append((rate, cat, persistent, transient))

    entries.sort(reverse=True)
    print()
    print(f"Allocations Breakdown: {path}")
    print(f"Filtering: categories with rate >= {min_rate:.1f} events/s across {seconds:.1f}s sample ({len(entries)} matches)")
    print("=" * 86)
    print(f"{'Rate (events/s)':>15}   {'Persistent':>14}   {'Transient':>14}   {'Category Name'}")
    print("-" * 86)
    for rate, cat, p, t in entries:
        print(f"{rate:>14.0f}/s   {p/1e6:>11.2f} MB   {t/1e6:>11.2f} MB   {cat}")
    print()

if __name__ == '__main__':
    main()
```

## File: scripts/top_time.py
size: 6349
sha: 431f9948bbdce0e6f624437b56b60d7407545f79
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/scripts/top_time.py

```text
#!/usr/bin/env python3
"""
Parse an xctrace 'time-profile' XML export (idmap/ref format) into top CPU
functions, thread breakdown, and per-binary attribution.

Works on the exact XML shape emitted by:
    xcrun xctrace export --input <trace> \
      --xpath "/trace-toc/run[@number='1']/data/table[@schema='time-profile']"

Usage:
    python3 top_time.py <time-profile.xml> [topN] [--leaf] [--by-binary]

Arguments:
    <time-profile.xml>  Exported 'time-profile' table XML.
    [topN]              Number of top entries to print (default: 25).
    [--leaf]            Attribute samples to leaf frames only (per-call-site cost).
                        Default is any-frame (inclusive, each sampled frame counts).
    [--by-binary]       Attribute samples by binary name instead of by function.

Example:
    python3 top_time.py /tmp/ios-traces/idle-time-profile.xml 15 --leaf

Dependencies:
    Python 3.8+ (Zero external pip dependencies; standard library only).
"""
import re
import sys
from collections import defaultdict

ROW_RE = re.compile(r'<row>(?P<body>.*?)</row>', re.S)
WEIGHT_DEF_RE = re.compile(r'<weight\s+id="(\d+)"[^>]*>([0-9]+)</weight>')
THREAD_DEF_RE = re.compile(r'<thread\s+id="(\d+)"[^>]*fmt="([^"]*)"')
FRAME_DEF_RE = re.compile(
    r'<frame\s+id="(\d+)"\s+name="([^"]*)"[^>]*>(?:<binary(?:[^>]*name="([^"]*)")?[^>]*/>)?</frame>')
BT_DEF_RE = re.compile(r'<backtrace\s+id="(\d+)">(?P<frames>.*?)</backtrace>', re.S)
TBT_DEF_RE = re.compile(r'<tagged-backtrace\s+id="(\d+)"[^>]*>(?P<body>.*?)</tagged-backtrace>', re.S)

def frame_name_binary(frame_xml):
    """Parse one <frame ...>...</frame> or <frame ref="N"/> into (name, binary, ref)."""
    m = re.search(r'<frame\s+id="(\d+)"\s+name="([^"]*)"[^>]*>(?P<body>.*?)</frame>', frame_xml, re.S)
    if m:
        name = m.group(2)
        binary = '?'
        bm = re.search(r'<binary[^>]*name="([^"]*)"', m.group('body'))
        if bm:
            binary = bm.group(1)
        return name, binary, None
    m = re.search(r'<frame\s+ref="(\d+)"\s*/>', frame_xml)
    if m:
        return None, None, int(m.group(1))
    return None, None, None

def parse(path):
    with open(path, encoding='utf-8', errors='replace') as f:
        xml = f.read()

    weights = {int(i): float(v) / 1e6 for i, v in WEIGHT_DEF_RE.findall(xml)}
    threads = {int(i): fmt for i, fmt in THREAD_DEF_RE.findall(xml)}
    frames = {}   # frame id -> (name, binary)
    for m in FRAME_DEF_RE.finditer(xml):
        frames[int(m.group(1))] = (m.group(2), m.group(3) or '?')
    bts = {}      # backtrace id -> body xml
    for m in BT_DEF_RE.finditer(xml):
        bts[int(m.group(1))] = m.group('frames')
    tbts = {}     # tagged-backtrace id -> body xml
    for m in TBT_DEF_RE.finditer(xml):
        tbts[int(m.group(1))] = m.group('body')

    rows = 0
    total = 0.0
    leaf_counts = defaultdict(float)
    frame_counts = defaultdict(float)
    bin_counts = defaultdict(float)
    thread_counts = defaultdict(float)

    for rm in ROW_RE.finditer(xml):
        body = rm.group('body')
        rows += 1

        w = 1.0
        wm = re.search(r'<weight\s+ref="(\d+)"\s*/>', body)
        if wm:
            w = weights.get(int(wm.group(1)), 1.0)
        else:
            wm = re.search(r'<weight\s+id="\d+"[^>]*>([0-9]+)</weight>', body)
            if wm:
                w = float(wm.group(1)) / 1e6
        total += w

        tm = re.search(r'<thread\s+ref="(\d+)"\s*/>', body)
        tname = None
        if tm:
            tname = threads.get(int(tm.group(1)))
        else:
            tm = re.search(r'<thread\s+id="\d+"[^>]*fmt="([^"]*)"', body)
            if tm:
                tname = tm.group(1)
        if tname:
            thread_counts[tname] += w

        bt = None
        tbm = re.search(r'<tagged-backtrace\s+ref="(\d+)"\s*/>', body)
        if tbm:
            bt = tbts.get(int(tbm.group(1)))
        else:
            tbm = re.search(r'<tagged-backtrace\s+id="\d+"[^>]*>(?P<body>.*?)</tagged-backtrace>', body, re.S)
            if tbm:
                bt = tbm.group('body')
        if not bt:
            continue

        bm2 = re.search(r'<backtrace\s+ref="(\d+)"\s*/>', bt)
        frames_body = None
        if bm2:
            frames_body = bts.get(int(bm2.group(1)))
        else:
            bm2 = re.search(r'<backtrace\s+id="\d+">(?P<frames>.*?)</backtrace>', bt, re.S)
            if bm2:
                frames_body = bm2.group('frames')
        if frames_body is None:
            continue

        stack = []
        for fm in re.finditer(r'<frame\b[^>]*/>', frames_body):
            name, binary, ref = frame_name_binary(fm.group(0))
            if ref is not None:
                f = frames.get(ref)
                if f:
                    stack.append(f)
            else:
                stack.append((name, binary))
        if not stack:
            continue
        leaf = stack[0]
        leaf_counts[leaf[0]] += w
        bin_counts[leaf[1]] += w
        for name, binary in stack:
            frame_counts[name] += w

    return rows, total, leaf_counts, frame_counts, bin_counts, thread_counts

def main():
    if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
        print(__doc__.strip())
        sys.exit(0 if len(sys.argv) > 1 else 1)

    path = sys.argv[1]
    topn = int(sys.argv[2]) if len(sys.argv) > 2 else 25
    leaf_only = '--leaf' in sys.argv
    by_binary = '--by-binary' in sys.argv

    rows, total, leaf_counts, frame_counts, bin_counts, thread_counts = parse(path)

    print(f"rows={rows} total_sample_ms={total:.1f} (~{total/1000.0:.2f}s CPU)")
    print("\n== Threads by sample weight ==")
    for name, w in sorted(thread_counts.items(), key=lambda kv: -kv[1])[:8]:
        print(f"{w:10.1f} ms  {name[:95]}")
    if by_binary:
        print("\n== Top binaries (leaf-attributed) ==")
        for name, w in sorted(bin_counts.items(), key=lambda kv: -kv[1])[:topn]:
            print(f"{w:10.1f} ms  {name}")
        return
    counts = leaf_counts if leaf_only else frame_counts
    kind = "LEAF" if leaf_only else "ANY-FRAME"
    print(f"\n== Top {topn} functions ({kind}) ==")
    for name, w in sorted(counts.items(), key=lambda kv: -kv[1])[:topn]:
        pct = 100.0 * w / total if total else 0
        print(f"{w:10.1f} ms  {pct:5.1f}%  {name[:115]}")

if __name__ == '__main__':
    main()
```

## File: references/device-commands.md
size: 4353
sha: e470214ca9dce29c847fb90a1dc947e1b76ac69b
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/device-commands.md

```text
# Device and xctrace Reference

Load when selecting a physical device or simulator, choosing attach versus launch, or resolving a capture problem. Commands and instrument support vary across Xcode and OS releases; inspect the active tool before recording.

## Discover current capabilities

- Check `xcodebuild -version` and `xcrun xctrace version` to identify the selected toolchain.
- Xcode 27 release notes specify iOS 17+ for on-device debugging. This does not define support for every Instruments template or recording mode; verify the selected template against the target OS.
- Use `xcrun xctrace list devices` to locate the intended device or simulator and distinguish online from offline devices.
- Inspect `xcrun xctrace list templates`, `xcrun xctrace record --help`, `xcrun xctrace export --help`, and the relevant `xcrun devicectl` / `simctl` help. Confirm the chosen template supports the target type and OS.
- For Xcode 27 recording settings, use the `--show-recording-options` form documented by the installed `xctrace` help; review any JSON before passing it with `--recording-options`.
- Do not assume old short aliases or examples work with a different installed helper/Xcode. When an instrument is GUI-only or exports insufficient data, open the trace in Instruments.

## Select and verify the target

- Prefer a physical device for energy, thermal, radio, real refresh-rate, and device-specific GPU measurements. Use the Simulator for suitable CPU, logic, and interaction triage.
- Confirm the bundle ID, app process, and executable. Device process lists can include app extensions and widgets; select the main app process for the question. If multiple instances or extensions match, inspect them instead of choosing the first PID.
- Choose attach for an already-running app when that preserves the scenario. Choose profiler-launched execution when cold launch or startup itself is under study. Follow the project's signing, build, device and data rules.
- Attach may require a development-signed app with the appropriate debugging entitlement and device state. If it fails, identify the signing/OS boundary and use an authorized development build or supported launch path; do not silently weaken signing or entitlements.
- Verify the process and app state during capture. A successful recorder exit does not prove that the intended workload or process was sampled.

## Physical-device readiness

- The device must be online, unlocked, trusted, and available to the selected Xcode. Follow the device's Developer Mode and signing requirements for the chosen action.
- Keep the app in the foreground and display awake for UI or rendering measurements. If that requires changing Auto-Lock or another device setting, follow the user's stated preference or ask before changing it.
- For before/after energy runs, record device model, OS, battery/power state, temperature context if available, brightness, and network conditions. Keep these conditions comparable.

## Record and export

Create an output location appropriate for the task and name traces for the scenario, device/OS, and run phase. Use the CLI when it preserves the question and capture scope; open Instruments for track relationships, inspectors, device-specific detail, or comparisons that are clearer visually.

The recorder and its temporary files run on the Mac, including when the target is a physical device. Check host free space on both the temporary volume and the output volume before long captures. `--time-limit` limits collection time; it does not limit bytes or guarantee prompt finalization. Load `references/storage-and-recovery.md` if disk space falls unexpectedly, `xctrace` remains alive, or space does not return after capture.

Before using custom recording options, inspect the installed template defaults and save only the reviewed changes needed for the question. Before exporting, use current help to restrict the time range, process, table, or fields to the evidence required. Treat traces and exports as potentially sensitive, and keep raw trace bundles and huge exports out of chat.

If recording fails, report the Xcode/OS, target type, template, and relevant diagnostic; then adjust based on the failure. Do not retry with an arbitrary process, broader permissions, a reset device, or a different target that cannot answer the same question.
```

## File: references/storage-and-recovery.md
size: 5684
sha: 57146cca653c53e1ebd08aaf7ea0f9e52e70d11b
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/storage-and-recovery.md

````text
# Recording Storage and Recovery

Load this reference when a capture grows rapidly, Mac disk space drops, `xctrace` stays alive after its time limit, or storage does not return after recording. These checks apply to both physical iOS devices and Simulators: the target may be an iPhone or Simulator, but Instruments records and processes the trace on the Mac.

## Before recording

1. Identify the actual temporary and output volumes. Check `TMPDIR` and the output directory with `df -h`; create the output directory first if needed. `TMPDIR` is a starting point, not proof that every Instruments service uses it.
2. If this toolchain, template, device, or workload has not been measured on this Mac, begin with a short capture and observe free space and output growth. Set a reserve appropriate for the Mac and the expected capture; stop before either volume reaches it.
3. Treat `--time-limit` as a collection-time limit, not a byte cap or a guarantee that finalization completes promptly. Keep the recorder process under observation through finalization and set a reasonable deadline for the task.
4. `--output` selects the final `.trace` location. It does not guarantee that intermediate files or service caches use that volume. Setting `TMPDIR` may redirect some temporary files, but do not assume that it redirects `DTServiceHub` or other Instruments services. Verify actual open paths with `lsof` during a short capture before relying on an external disk to protect the internal disk.
5. Before a large export, check the export volume and narrow the time range, process, tables, or fields to the evidence needed. If a deleted-open `.ktrace` is still consuming space, diagnose it before starting another recording or large export.

## Inspect storage after each recording

After `xctrace record` exits, check the same volumes again:

```bash
df -h "${TMPDIR:-/tmp}" "/path/to/trace-output"
```

Then inspect files that have been unlinked but still have an open handle:

```bash
lsof -nP +c 0 +L1 2>/dev/null | grep -E 'DTServiceHub.*\.ktrace|\.ktrace.*DTServiceHub'
```

An empty result means this filter found no matching deleted-open `.ktrace`; it does not prove that all temporary files are gone. If space is still missing, inspect `df`, the sizes of the run's output and known temporary files, and other open files before acting. Record the path, size, PID, and command for any candidate.

For a matching PID, inspect its start time, executable, and command:

```bash
ps -p <PID> -o pid=,lstart=,command=
lsof -nP -p <PID> -d txt
```

Check for active `xctrace record` processes and Instruments GUI recordings before stopping `DTServiceHub`. A service can be shared with another recording; do not assume it belongs to the most recent task merely because its name matches.

## Decide what can be cleaned

- Preserve requested `.trace` bundles and exports. Do not remove an incomplete trace until its diagnostic value and retention are understood.
- A named intermediate file can be removed only after the recorder has exited, no process has it open, and evidence ties that exact path to the completed run. Inspect exact paths first; do not use a global `find ... -delete` or wildcard `rm` for `instruments*.ktrace`.
- Deleting a file does not release its blocks while a process still has it open. If `lsof +L1` shows a deleted `.ktrace`, closing the owning process's handle is what releases those blocks.
- For an exact `DTServiceHub` PID holding a deleted `.ktrace`, first confirm the executable and start time, confirm that no active Instruments recording depends on it, and confirm that the original recorder has exited. If the evidence is ambiguous or the service could belong to the user or another task, ask the user before stopping it.
- When the stale handle is clearly attributable to a completed run and no active session uses the service, send `SIGTERM` to that exact PID, wait, then rerun `lsof +L1` and `df -h` to verify release. Escalate to `SIGKILL` only for the same verified stale PID if it still holds the deleted file after `SIGTERM` and the task's process rules allow it. Never use `killall -9 DTServiceHub` as routine cleanup.
- The `com.apple.dt.InstrumentsCLI` cache is separate from deleted-open trace storage. Do not recursively delete the shared cache automatically. Inspect its exact size and contents, confirm no Instruments activity is using it, and ask before removing anything whose ownership or value is unclear.
- Do not kill the profiled app as a storage cleanup step. If a recording hangs or threatens the storage reserve, identify the exact `xctrace` process started for this run and stop that recorder according to the task's process rules; then inspect the service handles separately.

After any cleanup, rerun `lsof +L1` and `df -h` on the affected volume. Report the observed before/after free space and what was removed or stopped; a successful `rm` alone does not establish that storage was reclaimed.

## Recovery sequence

1. Stop starting new recordings or large exports while the affected volume is near its reserve.
2. Confirm the `xctrace` process for this run has exited. If it is still finalizing beyond the task's deadline, verify its PID and command before stopping only that recorder.
3. Inspect `lsof +L1`, identify the owning PID and exact deleted-open path, and check for other active Instruments sessions.
4. Decide whether an exact run-owned intermediate can be removed or whether a stale handle must be closed. Ask the user when ownership or impact is uncertain.
5. Verify the handle closed and free space returned with `lsof` and `df`. Preserve evidence and report any remaining growth or unresolved service state.
````

## File: references/subsystems.md
size: 2645
sha: c60edc3ee587a68ba5b95a9d4c07aadc29a2c765
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/subsystems.md

```text
# Mobile Subsystem Optimization Notes (iOS)

Load this file when the profile attributes a bottleneck to a specific subsystem
(battery/radio, ProMotion displays, media & large-asset decoding, or real-time
audio). These are battle-tested optimization patterns for iOS.

## Battery & Radio Energy Management

- **Cellular & WiFi radio tails**: Opening a network socket transitions the cellular baseband or WiFi chip from low-power sleep to high-power active state, maintaining high power consumption for several seconds after the transfer finishes (radio tail). Batch network requests into unified bursts rather than firing periodic independent pings every few seconds.
- **Verification**: Run `Power Profiler` and inspect the `WiFi Tx/Rx` and `Network Impact` metrics in `scripts/parse_power.py`.

## ProMotion 120Hz Displays and Hitches

- **Frame budget**: On ProMotion devices (iPhone Pro models), the display refresh interval is 8.33ms (120Hz). Exceeding 8.33ms on either the main thread (view preparation and layout) or render server (CoreAnimation commit) drops frames.
- **Hitches taxonomy**:
  - *Commit Hitches*: Main thread took too long to build view hierarchy or compute geometry before committing to render server.
  - *Render Hitches*: GPU took too long rendering layers (complex shadows, blur effects, offscreen passes).
- **Diagnosis**: Use `Animation Hitches` with `--duration 30s` during UI interactions (scrolling, transitions, gestures).

## Media & Large-Asset Decoding and Memory Spikes

- **Memory spikes on iOS**: iOS jetsam kills background or foreground apps exceeding strict memory ceilings (often ~1.5GB to 2GB on mobile). Materializing large assets at full resolution inflates the heap: decoding raw photos or big bitmaps into `UIImage` costs 4 bytes per pixel uncompressed, decoding video frames into pixel buffers at source resolution is far larger, and loading whole PDF pages or documents into memory is equally wasteful.
- **Decode at display size**: Downsample images at decode time using `CGImageSourceCreateThumbnailAtIndex` with `kCGImageSourceThumbnailMaxPixelSize`, decode video frames at playback resolution, render PDF pages on demand, and stream/parse large documents incrementally instead of buffering them whole.

## Real-Time Audio & Background Execution

- **Audio Session interruptions**: Real-time audio rendering callbacks running on `AVAudioEngine` or RemoteIO unit must never perform heap allocation or file I/O.
- **Background Mode**: If testing background audio or streaming, verify process behavior when transitions to background state occur (`UIApplication.didEnterBackgroundNotification`).
```

## File: references/templates.md
size: 5788
sha: 0e0d5a705ad4e6e85a8954a9fd2048520efd1c58
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/templates.md

```text
# Instruments Template Guide (iOS / iPadOS)

Load when selecting a recording for a specific performance question. Template names, target support, and CLI options depend on the active Xcode and device OS. Start with `xcrun xctrace list templates` and the installed help; use exact names reported there. This guide describes candidates and evidence, not a hardcoded command matrix.

For release-specific changes, check [Apple's Xcode 27 release notes](https://developer.apple.com/documentation/xcode-release-notes/xcode-27-release-notes).

| Question or symptom | Candidate instruments | Evidence to inspect |
| --- | --- | --- |
| CPU work, hot functions, or unexpected wakeups | Time Profiler; CPU Profiler where available | Sample weights by thread, call tree, running intervals, and overlap with the reported symptom. |
| Battery, energy, or thermal behavior | Power Profiler on a supported physical device; Time Profiler for code attribution | Per-process subsystem impact and hot work during the active scenario. Check current device/OS support; do not infer physical energy or thermal impact from a Simulator. |
| Scrolling, animation, or touch-response hitches | Animation Hitches; SwiftUI; Metal System Trace when GPU work is implicated | Hitch intervals and frame phases, view/layout work, GPU activity, refresh-rate context, and the interaction that triggers the delay. |
| Memory growth, churn, or Jetsam risk | Allocations; Leaks; device memory or termination diagnostics as appropriate | Live/persistent allocations, allocation backtraces, growth across repeated lifecycles, and whether owners outlive their intended lifecycle. A Leaks result alone does not establish bounded memory use. |
| Slow cold launch or resume | App Launch; Time Profiler or signposts for attribution | Launch phases, dyld work, static initialization, first useful frame, resume path, and the app's readiness signal. Keep launch conditions comparable. |
| Async stalls, actor contention, or executor starvation | Swift Concurrency; Swift Executors; Time Profiler or CPU Profiler; System Trace for scheduling evidence | Tasks and actors, waits/suspensions, executor queues, thread state, and scheduling around the user-visible delay. |
| Network latency, repeated requests, or radio activity | Network; Power Profiler where available; signposts or app logs | Request timing, connections, payloads, retries, and whether radio-active periods overlap the app's work. Use a physical device for radio/energy conclusions. |
| Audio glitches or real-time callback instability | Audio System Trace; Time Profiler; Allocations when allocation is suspected | Audio I/O timing, late or missed work, callback duration, locks, and allocations on real-time paths. |
| GPU or shader cost | Metal System Trace; CPU Counters where supported | GPU encoder/pass timing, frame boundaries, counters, and the target hardware's support. Some data requires opening the trace in Instruments rather than relying on a CLI export. |
| Apple Foundation Models latency or usage | Foundation Models | Instructions, prompts, responses, token usage, tool activity, and inference latency for calls through Apple's Foundation Models framework. Treat captured prompt/response data as sensitive. |

## Xcode 27 additions

- **Swift Executors**: displays the Cooperative Thread Pool, Main Actor, and custom `TaskExecutor` / `SerialExecutor` implementations. Executor names are captured on OS 27; earlier systems may show `Unknown executor`.
- **Swift Concurrency + CPU profiling**: recording Swift Concurrency alongside Time Profiler or CPU Profiler enables `Profile` details with call trees sampled while tasks are running. Use this to connect task/actor timelines to code-level CPU work; justify the extra capture overhead with the question.
- **SwiftUI layout detail**: records more layout-pass information, including reasons a layout computation was not cached. Confirm repeated layout work coincides with the visible hitch or CPU cost.
- **System Trace**: presents system calls, VM faults, and thread states in a unified timeline, with thread-priority context. Follow scheduling around the affected app thread instead of treating broad system activity as an app bottleneck.
- **Foundation Models**: covers Apple's Foundation Models framework. It is not a general profiler for remote APIs, third-party model providers, or every local inference runtime. Prompt and response contents can be sensitive.
- **Capture and export**: `xctrace record --show-recording-options` reports options for the installed template/instrument; pass reviewed JSON through `--recording-options` only when needed. `xctrace export` can restrict the exported time range, and Allocations exports can include captured backtraces. Check current CLI help because options vary by Xcode.
- **Reviewing runs**: use Instruments' run-comparison and summary views when they make a before/after result clearer. Inspect run metadata and keep the same real scenario and target conditions.

## Device and simulator notes

- Power Profiler is not supported on the Simulator. Energy, CPU-impact, and thermal claims require a supported physical device and OS.
- Power Profiler support depends on device OS; this repository has historically required iOS 26 or later. Check current `xctrace` help and the connected device before relying on it. For unsupported devices, choose CPU attribution tools and report the missing energy evidence explicitly.
- Some device- or GPU-specific instruments expose different data in GUI and CLI exports. Open the trace in Instruments when the relevant timeline is not represented in the export.
- Select only instruments that distinguish a plausible cause. Multi-instrument traces can add overhead and produce more sensitive or larger recordings.
```

## File: references/workload-reproduction.md
size: 3965
sha: c724240057e9653b541168a6c35af3a5aa6cfa7d
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/workload-reproduction.md

```text
# Reproducing iOS and iPadOS Workloads

Load when the report depends on a tap, scroll, launch, playback, network request, import, resume, or other timed activity. Choose the reproduction path that preserves the behavior under investigation.

## Choose and verify the path

1. Describe the scenario as observable app state and actions. Identify the time interval, device/OS requirements, content, network or account dependencies, and whether the question concerns the interaction itself or steady-state work after it.
2. Choose a trustworthy path for this app: user-triggered interaction, a supported launch argument or deep link, an existing benchmark/test, or UI automation. Launch hooks are useful only when the app consumes them and they exercise the reported work.
3. Prefer the least intrusive path that retains the scenario. Use the Simulator for quick CPU/logic triage when it faithfully exercises the path. Use a physical device for battery, energy, thermal, radio, device GPU, ProMotion, or other hardware-specific behavior.
4. Verify the action occurred and the target app is in the expected state. Use app state, logs, signposts, UI observation, or the trace as appropriate; a successful command or test launch alone does not prove the intended path ran.
5. For before/after comparisons, repeat the same scenario and reproduction mechanism. Keep device model, OS, build configuration, app content, screen brightness, refresh conditions, battery/power state, network conditions, window/app state, and capture scope comparable where they affect the result. Record differences and narrow the conclusion when a condition could not be held constant.
6. If automation changes timing, cannot reach the required state, or the app does not expose a reliable hook, use a manual interaction or a better-supported path. Ask the user to perform an action only when the required state cannot be established safely or accurately by the agent.

An idle capture may help isolate background cost, but it is optional. It does not establish improvement to an active scroll, playback, launch, network, or other reported scenario.

## Physical-device precautions

- Use `xcrun xctrace list devices` to confirm the intended device is online. Do not record against entries under `== Devices Offline ==`.
- Unlock and trust the device before use. Keep it awake and the app foregrounded for UI/rendering work; backgrounding can suspend or change app behavior.
- For battery/energy comparisons, use the same physical device, control brightness and network conditions, and allow temperature and battery state to be comparable. A warm device or changing radio conditions can dominate short runs.
- Do not reset, erase, re-provision, or clear app data merely to make a scenario repeatable. Follow project and user data-ownership rules.

## Simulator limits

- The Simulator is useful for fast CPU, logic, and UI-interaction triage when its behavior matches the question.
- Power Profiler energy/CPU-impact and thermal conclusions require a supported physical device; the Simulator does not provide them.
- Simulator results do not establish physical-device radio, battery, thermal, or device-GPU behavior. Simulator `xctrace` can also fail or hang in some environments; verify that a useful trace was actually produced before analysis.

## Capture design

Choose duration and repetition from the behavior. Include warm-up if the user experiences it, the trigger and aftermath for transient issues, and repeated lifecycle events for memory growth. Use signposts or existing logs when they materially improve alignment. Keep the target app visible for rendering measurements and note when background operation is itself the scenario.

Align analysis to the verified workload interval. If the device was offline, the app backgrounded, automation missed the interaction, or the wrong process was captured, discard that run as evidence and correct the reproduction before diagnosing code.
```

## File: references/xcode-agent-mcp.md
size: 2528
sha: 2bcd0663c8b17006763691136bcad3b7bc1af44f
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/references/xcode-agent-mcp.md

````text
# Xcode Coding Agents and MCP

Use when Xcode's project, build, test, or app-verification context may help investigate an iOS/iPadOS performance issue. This is an optional integration; Instruments traces remain the profiling evidence.

## Choose the right boundary

- Use the coding agent available in the host for repository inspection, edits, and coordination.
- If the agent exposes Xcode MCP tools, inspect the tool descriptions and permissions available in that session. Xcode and client capabilities vary by version.
- Use Xcode MCP for the Xcode actions it supports, such as project/build/test context or app verification. Use `xctrace` and Instruments for timelines, samples, hitches, allocations, power, and runtime attribution.
- Keep project test gates, signing, device ownership, user data, and physical-device rules in force when an MCP tool can perform an action.

## Xcode 27 MCP preview

Xcode 27 release notes describe a preview `xcrun mcp-server` experience that can run without an open workspace and can grant a code-signed agent access to projects under an approved directory tree. See [Apple's Xcode 27 release notes](https://developer.apple.com/documentation/xcode-release-notes/xcode-27-release-notes), and check the installed release notes and help before relying on it.

Discover commands before use:

```text
xcrun mcp-server --help
xcrun mcp-server status
xcrun mcpbridge --help
```

The local help describes `mcpbridge` as the stdio entry point for Xcode MCP tools. Use the Agent client's current configuration instructions rather than copying a guessed configuration block. `mcp-server enable` requires administrator authorization and changes host-level settings. Do not enable, disable, approve agents, allow folders, or clear permissions as an implicit profiling step. Never use the preview's unsafe allow-all option for normal interactive development.

Do not assume a `start` subcommand or universal permission model. Use only the commands shown by the installed tool. Some settings may require relaunching Xcode or restarting the host. Enabling the server also does not automatically configure Codex, Antigravity, or another client.

## Apple-authored agent skills

Xcode 27 release notes describe exporting Apple's coding-agent skills for Codex when they are not available automatically. Check current Xcode documentation and `xcrun agent skills --help` before exporting; this is separate from iOS-Trace and should not overwrite an existing skill collection without reviewing the destination.
````

## File: .gitignore
size: 255
sha: 72bf1ae9c8f544ae2492d35a508641747670d62c
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/.gitignore

```text
# macOS system files
.DS_Store
.AppleDouble
.LSOverride

# Instruments & trace outputs
*.trace/
*.trace
*.xml
*.dtps/
/tmp/

# Python bytecode
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
.venv/

# Editor files
.idea/
.vscode/
*.swp
*.swo
*~
```

## File: LICENSE
size: 1081
sha: 930e9551b7a00ad56c152f84305b5e1ea1787ea0
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 kmg (kmgccc@outlook.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: README_en.md
size: 3678
sha: cd8e253981e1d5083b9cdeb8345000244606e924
upstream: https://github.com/kmgcc/ios-trace/blob/HEAD/README_en.md

````text
# iOS-Trace

[English](README_en.md) | [中文](README.md)

[![Agent Skills Open Standard](https://img.shields.io/badge/Agent_Skills-Open_Standard-blueviolet.svg)](https://agentskills.io)
[![Install](https://img.shields.io/badge/Install-npx_skills_add-000000.svg)](https://skills.sh/kmgcc/iOS-Trace)
[![Platform](https://img.shields.io/badge/Platform-iOS_%2F_iPadOS-black.svg)](https://developer.apple.com/ios/)
[![Tooling](https://img.shields.io/badge/Xcode-Instruments_%2F_xctrace-007AFF.svg)](https://developer.apple.com/xcode/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> Need profiling for macOS desktop apps? See [macOS-Trace](https://github.com/kmgcc/macOS-Trace).

An agent-native runbook for profiling iOS and iPadOS apps. Choose instruments, workload reproduction, and success evidence based on the actual symptom and target device. Physical devices and simulators have different measurement boundaries. Bundled scripts are optional data-processing helpers, not a required workflow.

## Prerequisites

- A usable Xcode or Command Line Tools installation on macOS. Target support depends on Xcode and device OS. Xcode 27 requires macOS Tahoe 26.6 or later and runs only on Apple silicon.
- A physical device must be online, unlocked, and trusted by the Mac. Attach and UI testing also depend on signing, Developer Mode, and OS support.
- Python 3.8+ only when using optional helper scripts.

## Installation

### Recommended: skills CLI

```bash
npx skills add kmgcc/iOS-Trace
```

Use `-g` for a user-level installation, or `-a` to select an agent supported by the CLI.

### Manual installation

| Agent | User-level global directory |
| :--- | :--- |
| Codex | `~/.agents/skills/ios-trace` |
| Antigravity | `~/.gemini/config/skills/ios-trace` |
| DSH | `~/.dsh/skills/ios-trace` |
| Claude Code | `~/.claude/skills/ios-trace` |
| Cursor | `~/.cursor/skills/ios-trace` |
| OpenCode | `~/.config/opencode/skills/ios-trace` |

Copy the repository contents into the selected directory. Discovery paths can change by agent version; follow the agent's current documentation for project-level installation.

## Use

Ask the agent to use `ios-trace` for a concrete scenario, such as device scrolling hitches, overheating, slow launch, audio dropouts, or memory growth. It will choose a target, profiler, reproduction path, and comparison based on the question; no fixed script sequence is required.

## Documentation map

- `SKILL.md` — core runbook.
- `references/templates.md` — Instruments selection guide and Xcode 27 additions.
- `references/workload-reproduction.md` — choosing a physical-device or simulator path for the question.
- `references/device-commands.md` — device discovery, process verification, xctrace discovery, capture, and export.
- `references/storage-and-recovery.md` — Mac host temporary storage, deleted-open `.ktrace` diagnosis, and safe recovery.
- `references/xcode-agent-mcp.md` — optional Xcode MCP workflow and permission boundaries.
- `references/subsystems.md` — radio, ProMotion, media decoding, audio, and other optimization leads.

## Boundaries

- Simulator results can help with some CPU, logic, and UI investigations; they cannot establish physical-device power, radio, or thermal behavior.
- Traces may contain prompts, paths, media metadata, or logs; treat them as sensitive task data.
- MCP is an optional Xcode project/development integration. Runtime performance evidence comes from Instruments.
- Follow project rules for processes, devices, data ownership, builds, tests, and release workflows.

## License

MIT License. See [LICENSE](LICENSE).
````
