# Accessibility Inspector Tree Snapshot for Audit

Canonical: https://figment.so/blog/mac-accessibility-inspector-tree-snapshot

Install xctree with Homebrew, run xctree --format json against a booted iOS Simulator, then diff two snapshots with the Python script below. It runs on a Sequoia Mac, including Figment's Intel VM.

**Export the tree with `xctree --format json` while the app runs in a booted iOS Simulator, then diff two snapshots with the Python script below to flag lost labels, changed roles and removed elements.** Xcode's Accessibility Inspector is good for interactive audits but does not emit a JSON hierarchy you can diff in CI. The open-source [xctree CLI](https://github.com/ldomaradzki/xctree) fills that gap, and the script maps each change to the [WCAG 2.2](https://www.w3.org/TR/WCAG22/) success criterion it affects.

## What does Accessibility Inspector give me, and what does it not?

It shows the hierarchy VoiceOver reads, but only interactively. Open it from Xcode → Open Developer Tool → Accessibility Inspector, point it at a running macOS process or an iOS Simulator app, and read the attributes below.

| Attribute | WCAG 2.2 success criterion |
|---|---|
| `label` (accessible name) | 4.1.2 Name, Role, Value; 2.5.3 Label in Name |
| `role` | 4.1.2 Name, Role, Value |
| `value` | 4.1.2 Name, Role, Value |
| `hint` | 3.3.2 Labels or Instructions |
| `enabled` state | 4.1.2 Name, Role, Value |
| Structural relationships | 1.3.1 Info and Relationships |

The Audit tab exports its automated-check findings as a readable report. That suits a one-off review but is not structured for scripted diffing between builds, so you need the raw tree.

## How do I export the tree as JSON with xctree?

Install xctree, boot a simulator, launch your app, and run `xctree --format json`. xctree reads the same public macOS Accessibility APIs the inspector uses and targets apps in a booted iOS Simulator. The project README lists three prerequisites: macOS 15 (Sequoia) or later, Xcode installed, and a running iOS Simulator. The terminal that runs xctree also needs permission under System Settings → Privacy & Security → Accessibility. It works only against the iOS Simulator, not physical devices. For the macOS process tree, use the inspector interactively.

```bash
# Install via the project's Homebrew tap
brew tap ldomaradzki/xctree
brew install xctree

# Boot a simulator, launch the app under test, then capture the tree.
# Use a UDID you confirmed with `xcrun simctl list devices available`.
: "${SIMULATOR_UDID:?set SIMULATOR_UDID to the target simulator}"
xcrun simctl boot "$SIMULATOR_UDID" || true
xctree --format json > "accessibility-snapshot-$(date +%Y%m%dT%H%M%S).json"
```

Per the README, each JSON node carries `identifier`, `label`, `role` and `traits`, plus `children` for nested elements. Run `xctree --help` and inspect one real export from your own app before trusting any specific key. The Python diff below treats missing keys as `None`, so a future schema addition does not silently hide regressions.

```json
{
  "identifier": "sign-in-button",
  "label": "Sign In",
  "role": "AXButton",
  "traits": ["button"],
  "children": []
}
```

An empty `label` on a tappable element is a 4.1.2 problem. A button whose `role` flips to `AXStaticText` after a refactor stops announcing as interactive. The diff catches both.

## How do I diff two snapshots?

Run the script below after each build against the previous baseline. It exits non-zero when a label disappears, a role changes or an element is dropped from the tree, which is enough to fail a CI step before merge. The code is a small example, not an executed benchmark: validate it against two real exports from your app before wiring it to a merge gate.

```python
#!/usr/bin/env python3
"""
a11y_diff.py: compare two xctree JSON snapshots and report accessibility changes.
Usage: python3 a11y_diff.py baseline.json current.json
Exit:  0 if no regressions, 1 if one or more regressions, 2 on usage error.
"""

import json
import sys
from pathlib import Path

WCAG_MAP = {
    "label":   ("4.1.2 Name, Role, Value", "2.5.3 Label in Name"),
    "role":    ("4.1.2 Name, Role, Value",),
    "value":   ("4.1.2 Name, Role, Value",),
    "hint":    ("3.3.2 Labels or Instructions",),
    "enabled": ("4.1.2 Name, Role, Value",),
}
ATTRS = list(WCAG_MAP.keys())

def flatten(node, path=""):
    key = node.get("identifier") or (
        f"{path}/{node.get('role', '?')}:{node.get('label', '')}"
    )
    out = {key: {a: node.get(a) for a in ATTRS}}
    for child in node.get("children", []) or []:
        out.update(flatten(child, key))
    return out

def load(path):
    data = json.loads(Path(path).read_text())
    if isinstance(data, list):
        flat = {}
        for n in data:
            flat.update(flatten(n))
        return flat
    return flatten(data)

def main(baseline_path, current_path):
    baseline, current = load(baseline_path), load(current_path)
    removed = set(baseline) - set(current)
    added = set(current) - set(baseline)
    regressions = len(removed)

    for k in sorted(removed):
        print(f"REMOVED  {k}  [WCAG 4.1.2 element missing]")

    for key in sorted(set(baseline) & set(current)):
        for attr in ATTRS:
            bv, cv = baseline[key].get(attr), current[key].get(attr)
            if bv == cv:
                continue
            is_regression = (
                (attr == "label" and bv and not cv)
                or (attr == "role" and bv is not None and bv != cv)
                or (attr == "enabled" and bv is True and cv is False)
            )
            tag = "FAIL" if is_regression else "WARN"
            regressions += int(is_regression)
            wcag = ", ".join(WCAG_MAP[attr])
            print(f"{tag}  {key}  {attr}: {bv!r} -> {cv!r}  [{wcag}]")

    for k in sorted(added):
        print(f"ADDED    {k}  (review: a new unlabelled control is itself a regression)")

    print(f"\n{regressions} regression(s).")
    return 1 if regressions else 0

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python3 a11y_diff.py baseline.json current.json")
        sys.exit(2)
    sys.exit(main(sys.argv[1], sys.argv[2]))
```

Treat `WARN` rows (new label text, new value, new hint) as triage items. Not every rewording is a regression, but one that breaks "Label in Name" for voice control is. Treat `ADDED` keys as a review step: a new control without a stable identifier is often itself the bug.

## How do I wire it into my build?

Add a pre-test Xcode run-script phase locally, and store a baseline in CI. Keep the phase defensive so a developer build with no simulator booted does not fail, and use a unique path per run so parallel schemes do not overwrite each other.

```bash
set -euo pipefail
SNAP_DIR="${BUILT_PRODUCTS_DIR}/accessibility-snapshots"
mkdir -p "$SNAP_DIR"
STAMP="$(date +%Y%m%dT%H%M%S)-$$"
SHA="$(git rev-parse --short HEAD 2>/dev/null || echo nogit)"
OUT="$SNAP_DIR/tree_${SHA}_${STAMP}.json"
if xcrun simctl list devices booted | grep -q '(Booted)'; then
  xctree --format json > "$OUT"
  echo "wrote $OUT"
else
  echo "no booted simulator; skipping accessibility snapshot" >&2
fi
```

In CI, store the baseline snapshot as a build artifact keyed to the `main` branch, then run `a11y_diff.py` against it on each pull request. Because xctree needs a booted iOS Simulator, the runner must be a Mac that can boot the matching simulator runtime.

## How do I check that the gate works?

Walk through this once against your own app before you trust the gate.

1. Boot one simulator, launch your main screen and run `xctree --format json > a.json`. Close the app, reopen it and run again to produce `b.json`. The diff between `a.json` and `b.json` should report zero `FAIL` rows. If it does not, your app's identifiers are unstable and need `accessibilityIdentifier` set before any diff is meaningful.
2. Delete the label from one test-only control, rebuild and snapshot as `c.json`. Confirm `a11y_diff.py a.json c.json` prints a `FAIL` row for that key with WCAG 4.1.2.
3. Change that same control from a button to a static label and snapshot as `d.json`. Confirm a `FAIL` row for the `role` change.
4. Keep `a.json` as the branch baseline and `d.json` as a known-bad fixture, so you can regression-test the diff script itself.

## Which Figment plan runs Accessibility Inspector and xctree?

The inspector needs a desktop session and xctree needs only the simulator and a Terminal, so any plan with a Mac desktop works. The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia, which meets xctree's macOS 15 requirement, and supports Xcode 26.3 or earlier per Apple's table. It cannot run Xcode 26.4 or later, arm64-only binaries or visionOS. Choose the Apple Silicon Mac VM ($39 a month, $6 a day) for those. We have not measured simulator speed on any plan. Compare the [Mac hosting plans](/mac-hosting) and check the macOS and Xcode versions shown before purchase.

## What should I read next?

- [Keyboard navigation audit workflow for macOS apps](/blog/mac-accessibility-keyboard-nav-audit)
- [Test ATS exceptions and network security in the simulator](/blog/mac-simulator-ats-exception-test)
- [Register a hosted Mac as a persistent GitHub Actions runner](/blog/mac-github-actions-self-hosted-runner)
