Over the past year I have been building Monjour - an iOS and macOS calendar and journal app, now around 1,300 Swift files - almost entirely through CLI coding agents.

Doing this on iOS comes with a specific set of problems. Unlike web stacks, there is still no clean cloud agent environment that runs Xcode, simulators, and Apple signing out of the box. Everything happens on your own machine, inside a toolchain built around a single GUI window.

Below is a list of the problems I kept hitting, why they happen, and an outline of the fixes I settled on. Every setup is different, so these are intentionally kept at the level you can hand to your own agent to adapt for your repo, with a short code sketch at the end of each section.

Flexible multi-agent tmux workflow

Because cloud sandboxes are not really an option for iOS yet, running multiple agents in parallel has to happen locally.

My setup pairs git worktrees with tmux and a git-backed CLI issue tracker (Beads, or bd). Each task gets its own branch, its own worktree off main, and its own tmux window. I also wrote bew, a small TUI that pairs open issues with their tmux sessions so I can jump between agents without tracking branch names by hand.

My entire workflow is handled by four simple slash commands. I use them in Claude Code, though they are plain prompt templates and work in any CLI harness:

  • /triage walks through a raw list of bugs I gathered during testing, checking for duplicates before creating issues one by one.
  • /ship claims an issue, spins up a worktree and tmux window, implements the change, runs verification, and opens a PR.
  • /merge-shipped squash-merges PRs I commented ready to merge on (GitHub does not let you approve your own PRs) and closes their issues.
  • /archive archives and removes finished worktrees and branches.
Example: commands/ship.md
11. Read the issue and claim it: `bd update <id> --claim`.
22. Create a worktree off `main` at `.worktrees/<id>-<slug>` and cd into it.
33. Rename this pane's tmux window:
4   `tmux rename-window -t "$TMUX_PANE" <id>-<slug>`
5   (the `-t "$TMUX_PANE"` target keeps it from renaming whichever window you're focused on).
64. Scope, plan, and implement the change.
75. Run `scripts/check.sh` and fix every failure.
86. Commit, push, and open a PR with `gh pr create --base main`.

Managing DerivedData

Every git worktree builds into a new folder under ~/Library/Developer/Xcode/DerivedData, and git worktree remove leaves it behind. After a few weeks of parallel branches, orphaned build products quietly eat tens of gigabytes of disk space.

Cleanup has to happen alongside worktree removal, not whenever you remember to nuke DerivedData by hand.

My archive script deletes the matching DerivedData folder whenever a worktree is removed by checking WorkspacePath in each folder's info.plist.

Example: remove_derived_data - Bash
1remove_derived_data() {
2  local worktree_path="$1" plist
3  for plist in "$HOME"/Library/Developer/Xcode/DerivedData/*/info.plist; do
4    case "$(plutil -extract WorkspacePath raw "$plist" 2>/dev/null)" in
5      "$worktree_path"/*) rm -rf "$(dirname "$plist")" ;;
6    esac
7  done
8}

Fixing the parallel testing nightmare

I did not give much thought to simulator management initially. Each agent would spin up simulators whenever and however it felt like it. Nothing ever shut them down. At one point I had 21 simulators staying booted, with about 5,900 processes, the load average hit 786 on 16 cores, and healthy builds and tests timing out. Sharing a simulator without coordination resulted in concurrent test runs fighting over the same device, and holding a simulator while xcodebuild compiles leaves it blocked for minutes while nothing is running on it.

Simulators are a scarce local resource. They need to be pooled, kept warm so runs skip boot time, and held only while tests actually execute.

The shape of the fix is as follows:

  • Keep a small fixed pool of named simulators (three is plenty) booted between runs.
  • Guard the pool with a lockfile lease using macOS's built-in shlock, stored in the shared git rev-parse --git-common-dir directory so every worktree shares the same pool and dead processes release their locks automatically.
  • Split build and test: run build-for-testing against generic/platform=iOS Simulator first, and only take a simulator lease for test-without-building.
  • Uninstall the app when the lease ends (and erase the simulator if a system daemon like PosterBoard wedged during the run) so the next session starts clean.

The same lockfile lease pattern works for any other shared local resource - a local database, a mock server, or a VM.

Example: Simulator lease pool - Bash
1# 1. Build first without holding a simulator
2xcodebuild -scheme MyApp -destination 'generic/platform=iOS Simulator' build-for-testing
3
4# 2. Lease one of N slots via shlock in the shared git common dir
5lease_dir="$(git rev-parse --path-format=absolute --git-common-dir)/simulator-leases"
6mkdir -p "$lease_dir"
7until slot=$(for i in 1 2 3; do shlock -f "$lease_dir/$i" -p $$ && echo "$i" && break; done) && [ -n "$slot" ]; do
8  sleep 5
9done
10
11# 3. Boot/reuse pool simulator, clean up app & lock on exit
12udid=$(find_or_create_simulator "app-test-$slot")
13trap 'xcrun simctl uninstall "$udid" com.example.app; rm -f "$lease_dir/$slot"' EXIT
14xcrun simctl bootstatus "$udid" -b > /dev/null
15
16# 4. Run tests without rebuilding
17xcodebuild -scheme MyApp -destination "platform=iOS Simulator,id=$udid" test-without-building

Hung builds and test runs

xcodebuild and simulator test hosts hang more often than you expect. When that happens in an unattended terminal session, an agent will wait indefinitely until you notice and kill the process by hand.

Every build and test command needs a hard ceiling so a stalled run turns into a clear failure the agent can recover from instead of a dead session.

Wrap every xcodebuild and swift test call in a small timeout helper (Perl's alarm ships with macOS, so you do not need GNU timeout) with sensible caps - a few minutes for builds, two minutes for tests. When the timer fires, print a clear timeout line and exit non-zero so the agent knows what happened.

Example: Timeout wrapper - Bash
1run_with_timeout() {
2  local seconds="$1"
3  shift
4  perl -e 'alarm shift; exec @ARGV' "$seconds" "$@"
5  local status=$?
6  if [ "$status" -eq 142 ]; then
7    echo "$* timed out after ${seconds}s" >&2
8  fi
9  return "$status"
10}
11
12run_with_timeout 180 xcodebuild ... build-for-testing
13run_with_timeout 120 xcodebuild ... test-without-building

Filtering the noise out of xcodebuild's output

Raw xcodebuild output dumps thousands of lines of compiler flags into an agent's context on every run. It burns tokens fast and buries the one error line that actually matters.

An agent only needs a quiet summary on success, and the relevant error tail on failure.

Capture the raw command output to a temp file, pipe it through xcbeautify --quieter, and print the last ~30 lines of the raw log only if the command exited non-zero. Roll linting, package tests, and app tests into a single check script and tell agents in AGENTS.md to run it only right before committing, not after every small edit.

Example: Quiet check wrapper - Bash
1quiet_run() {
2  local log=$(mktemp) status
3  "$@" > "$log" 2>&1
4  status=$?
5  xcbeautify --quieter --disable-logging < "$log"
6  if [ "$status" -ne 0 ]; then
7    tail -n 30 "$log"
8  fi
9  rm -f "$log"
10  return "$status"
11}
12
13# scripts/check.sh (run once before committing)
14swiftlint lint --quiet --strict || exit 1
15quiet_run swift test --package-path Core || exit 1
16scripts/run-tests.sh || exit 1

Enforcing performance, memory safety, and simplicity

Left to their own devices, agents write code that compiles while quietly growing 1,000-line views, force unwraps, try? swallows, singletons, and deep nesting. Asking for clean code in prose helps for ten minutes and then fades out of context.

Structural discipline works much better when the compiler and linter fail the build on violations instead of hoping a review pass catches them later.

A handful of rules kept my codebase surprisingly manageable:

  • Strict Swift compiler settings. Swift 6.2 with default MainActor isolation, strict concurrency, strictMemorySafety(), upcoming feature flags, and warnings treated as errors.
  • NASA's Power of Ten adapted to SwiftLint. Run SwiftLint in strict: true mode with caps on function length (50 lines), cyclomatic complexity (10), and nesting (2), plus errors on force unwraps, try?, discarded return values (_ = and @discardableResult), static let shared singletons, while true, and #if outside platform gates.
  • One View struct per file. Named after the struct, with no @ViewBuilder helper properties or view-returning functions. A view-builder helper is part of its parent's body, so it runs whenever the parent does and adds its dependencies to the parent. A real struct gets its own narrower dependencies, which lets SwiftUI skip it, and keeps files small and diffs local too.
  • A short architecture bar in AGENTS.md. Prefer less code, store each fact once with one writer, and write down State, Flow, and Deletes before changing stored state.
Example: .swiftlint.yml
1strict: true
2
3cyclomatic_complexity:
4  warning: 10
5function_body_length:
6  warning: 50
7
8custom_rules:
9  no_optional_try:
10    regex: '\btry\?'
11    message: Catch or propagate every error.
12    severity: error
13  no_discarded_result:
14    regex: '_\s*='
15    message: Handle the result explicitly.
16    severity: error
17  no_singleton:
18    regex: '\bstatic\s+(let|var)\s+shared\b'
19    message: Pass owned state explicitly.
20    severity: error
21  no_unbounded_loop:
22    regex: '\bwhile\s+true\b'
23    message: Use a finite collection or an explicit bound.
24    severity: error
25  platform_gates_only:
26    regex: '^\s*#(?:else)?if\s+(?!!?(?:os\(|canImport\(|targetEnvironment\())'
27    message: "#if is for platform gates only."
28    severity: error

Inline comments drifting out of sync with code

Agents love writing prose comments above functions, and those comments go stale two refactors later. Once a comment and the code disagree, the next agent picks one at random and the drift compounds.

If a fact belongs in code, it belongs in a name, an extracted helper, a type, or a test. If it describes product behavior, it belongs in one authoritative place rather than scattered across source files.

I ban inline comments outright with a custom SwiftLint rule (allowing only tool directives like swiftlint: and swift-tools-version:). Local intent moves into readable names (more on that in Hyper legible Swift), and product behavior moves into specloop - one living spec in the repo, bound to deterministic tests, that agents read before writing and propose changes to instead of editing directly (more in Code review is dead. Long live the spec review?).

Example: .swiftlint.yml - no_inline_documentation
1custom_rules:
2  no_inline_documentation:
3    name: Inline Documentation
4    regex: '//(?!\s*(?:swiftlint:|swift-tools-version))|/\*'
5    match_kinds:
6      - comment
7      - comment.mark
8      - comment.url
9      - docComment
10      - docComment.field
11    message: Say it in a name, a function, or a test.
12    severity: error

Teaching agents when to stop reporting issues

Ask a coding agent to review a branch and it will keep finding things indefinitely. Models do not have a good sense of what counts as a real product issue, so when nothing serious is evident they fall back to nitpicking, inventing improbable states, or re-flagging tradeoffs you already accepted.

Without an explicit bar for what is worth reporting, every review pass starts from zero and re-litigates the same edge cases.

My fix is a file I call rakes.md, read at the start of every session and before every review pass. It sets the bar for what counts as a finding - including that zero findings is a valid result - and keeps a list of settled decisions. When an agent brings up a non-issue, I tighten the bar or add it once instead of arguing in chat, and review loops actually stop.

Example: docs/rakes.md
1# Rakes
2
3Read this before any review pass. A finding counts only when it clears every line of the bar.
4
5## Bar
6
7- A user reaches it through normal use or a normal device state. Crafted or improbable states, simulator artifacts and Debug-only code do not count.
8- It is likely, and it costs the user something real: data loss, a crash, a wrong schedule, a blocked core flow, an App Review rejection, or a UI stuck with no way back. An error message that leaves everything else stable does not count.
9- You verified it in source, in the running app or against the live service.
10- An action that does what its label says is not a bug, even when it deletes data. A user cannot lose data they never saw.
11- Zero findings is a possible result.
12
13## Settled
14
15- <Stuff that models keep thinking is an issue but is actually not>

Avoiding token burn when navigating a large Swift repo

Once a Swift codebase passes a few hundred files, answering a basic question like "what calls this and what does changing it touch?" with grep burns tens of thousands of tokens and still misses indirect relationships.

Structural questions belong in an index; text search should be reserved for literals, configs, and reading the exact lines you are about to edit.

I use codebase-memory-mcp, indexing each worktree separately, with a rule in AGENTS.md to query the graph first (search_graph, trace_path, get_code_snippet) before reaching for grep or file reads. (On a related note for Apple APIs: agents can usually read markdown docs directly now, and sosumi.ai is a quick fallback if a developer.apple.com page gives them trouble.)

Example: AGENTS.md
1## Codebase memory
2
3Every structural question (where a symbol lives, what calls it, what a change
4touches) goes to the graph first - not grep or Read.
5
61. Match this worktree's absolute path in `list_projects` (or call
7   `index_repository` if missing), then `detect_changes`.
82. Use `search_graph` -> `trace_path` -> `get_code_snippet`.
93. Use grep and file reads only for literals, configs, and confirming edits.

Hot reloading

Parallel builds and test runs play very poorly with Xcode Previews. Previews pause, rebuild from scratch, or fail to render right when you are trying to tweak UI.

If Previews cannot coexist with a multi-agent workflow, you want live updates straight on your iPhone without waiting on a full build and reinstall for every layout tweak.

I wired InjectionNext into my Debug device builds. Saving any Swift file - whether I edited it or an agent did - updates the running app on my iPhone in about a second while keeping open sheets, scroll position, and state. It started as a workaround for broken Previews; it turned out that real hot reload on a device is just nicer. (One caveat: stock InjectionNext still has a couple of upstream bugs around pipe file descriptors and type size changes on a second save, so I run a small local patch.)

Example: scripts/xcode.sh
1# Debug build settings on the app target:
2#   OTHER_LDFLAGS = -Xlinker -interposable
3#   SWIFT_ENABLE_OPAQUE_TYPE_ERASURE = YES
4
5# scripts/xcode.sh - switch Xcode + InjectionNext to the current worktree
6osascript -e 'tell application "Xcode" to quit'
7osascript -e 'tell application "InjectionNext" to quit'
8defaults write com.johnholdsworth.InjectionNext projectPath "$PWD/MyApp.xcodeproj"
9open -a InjectionNext # launches Xcode with SourceKit logging attached

Installing builds on your phone remotely

When I have an agent working while I am away from my desk - steering a session from my phone - I still want to try the branch on my iPhone without plugging in a cable or waiting for a TestFlight build to process.

iOS already supports over-the-air installs for development builds via itms-services:// manifests. The only awkward requirement is valid HTTPS.

A small deploy script handles it in one command: archive and export a Debug IPA with xcodebuild, write an itms-services:// manifest and a five-line HTML page with an Install link, and serve that folder locally behind tailscale serve (which provides valid HTTPS on your tailnet automatically). Open the printed URL in Safari on your iPhone, tap Install, and the branch is on your home screen.

Example: scripts/deploy-iphone.sh
1host="$(tailscale status --json | jq -r '.Self.DNSName | rtrimstr(".")')"
2base="https://$host/myapp"
3
4# 1. Archive & export a Debug IPA with an itms-services manifest pointing at $base/myapp.ipa
5xcodebuild archive -scheme MyApp -configuration Debug -destination 'generic/platform=iOS' -archivePath .build/app.xcarchive
6xcodebuild -exportArchive -archivePath .build/app.xcarchive -exportOptionsPlist ExportOptions.plist -exportPath .build/site
7
8# 2. Write a minimal install page
9cat > .build/site/index.html <<HTML
10<a href="itms-services://?action=download-manifest&url=$base/manifest.plist">Install build</a>
11HTML
12
13# 3. Serve locally over HTTPS on your tailnet
14tailscale serve --bg --set-path=/myapp http://127.0.0.1:8642
15python3 -m http.server --bind 127.0.0.1 8642 --directory .build/site &
16echo "$base/"

Conclusion

None of this was designed up front. Almost every rule and script here was added after an agent hit the same failure mode more than once.

If you are just starting out with iOS and CLI agents, pick only the problems you are already feeling - usually strict lint rules, xcbeautify with a timeout, and a simulator lease once you run more than one session. Add the rest when the friction shows up.