Incremental Xcode builds for agentic workflows
Keep build state local to each worktree
Incremental Xcode builds for agentic workflows break down when Xcode and the agent write to different locations. Build through the agent, open Xcode, and unchanged code compiles again.
Give both the same build paths inside each worktree. Keep mutable outputs separate across branches.
<worktree>/
├── Build/
│ ├── Products/
│ └── Intermediates.noindex/
└── DerivedData/
├── Trailnote/
├── ModuleCache.noindex/
├── SDKExplicitPrecompiledModules/
└── CompilationCache.noindex → shared cache for this Xcode build
Products, intermediates, indexes, and package state belong to the worktree. The compilation cache is content-addressed — matching entries can be reused without sharing the mutable build graph.
Building on Serg Dort’s path-alignment approach and my Worktrunk workflow, this example keeps build state local and shares compilation results across worktrees. It uses a fictional project, Trailnote, with setup automated through Codex startup hooks.
What you need
- Full Xcode 26 or later, selected through
xcode-selectorDEVELOPER_DIR. Compilation caching arrived as an opt-in feature in the Xcode 26 release notes. - XcodeBuildMCP with project-local YAML configuration,
derivedDataPath, andextraArgs, as shown in its v2.7.0 configuration example. Run the server from the active worktree root, or setXCODEBUILDMCP_CWDto that root. - Bash, Git,
plutil, and ripgrep (rg) for the setup script below.
Worktrunk and Codex hooks automate setup. Neither is required to run the script manually. Replace Trailnote, its schemes, and the simulator name with your project’s values. These examples assume a root-level .xcodeproj; a standalone .xcworkspace needs its own workspace settings path and MCP workspacePath instead.
Give Xcode and the agent the same paths
Xcode’s per-user workspace settings select relative DerivedData at DerivedData, with custom products at Build/Products and intermediates at Build/Intermediates.noindex. For Trailnote, the project data lands in DerivedData/Trailnote.
Save this as .xcodebuildmcp/config.yaml.template. The setup script renders it into the ignored .xcodebuildmcp/config.yaml:
schemaVersion: 1
incrementalBuildsEnabled: false
sessionDefaults:
projectPath: Trailnote.xcodeproj
scheme: Trailnote
configuration: Debug
derivedDataPath: DerivedData/Trailnote
simulatorName: iPhone 17
useLatestOS: true
extraArgs: &trailnoteBuildPathArgs
- "SYMROOT=__TRAILNOTE_WORKTREE_ROOT__/Build/Products"
- "OBJROOT=__TRAILNOTE_WORKTREE_ROOT__/Build/Intermediates.noindex"
- "BUILD_DIR=__TRAILNOTE_WORKTREE_ROOT__/Build/Products"
- "BUILD_ROOT=__TRAILNOTE_WORKTREE_ROOT__/Build/Products"
- "CLANG_PROFILE_DATA_DIRECTORY=__TRAILNOTE_WORKTREE_ROOT__/Build/Intermediates.noindex/CodeCoverage/ProfileData"
- "COMPILATION_CACHE_CAS_PATH=__TRAILNOTE_WORKTREE_ROOT__/DerivedData/CompilationCache.noindex"
- "MODULE_CACHE_DIR=__TRAILNOTE_WORKTREE_ROOT__/DerivedData/ModuleCache.noindex"
- "SDK_EXPLICIT_MODULES_OUTPUT_PATH=__TRAILNOTE_WORKTREE_ROOT__/DerivedData/SDKExplicitPrecompiledModules"
- "CLANG_MODULES_BUILD_SESSION_FILE=__TRAILNOTE_WORKTREE_ROOT__/DerivedData/ModuleCache.noindex/Session.modulevalidation"
- "SDK_STAT_CACHE_DIR=__TRAILNOTE_WORKTREE_ROOT__/DerivedData"
sessionDefaultsProfiles:
app:
projectPath: Trailnote.xcodeproj
scheme: Trailnote
configuration: Debug
derivedDataPath: DerivedData/Trailnote
simulatorName: iPhone 17
useLatestOS: true
extraArgs: *trailnoteBuildPathArgs
unit-tests:
projectPath: Trailnote.xcodeproj
scheme: UnitTests
configuration: Debug
derivedDataPath: DerivedData/Trailnote
simulatorName: iPhone 17
useLatestOS: true
extraArgs: *trailnoteBuildPathArgs
activeSessionDefaultsProfile: app
incrementalBuildsEnabled: false disables XcodeBuildMCP’s optional xcodemake wrapper. Xcode still builds incrementally. In XcodeBuildMCP 2.7.0, the wrapper runs xcodebuild clean when capturing commands for its generated Makefile, discarding the state this layout preserves.
CLANG_PROFILE_DATA_DIRECTORY also needs an explicit path. Passing -derivedDataPath otherwise places coverage data under DerivedData/Trailnote/Build/ProfileData, while the workspace settings use Build/Intermediates.noindex/CodeCoverage/ProfileData.
__TRAILNOTE_WORKTREE_ROOT__ is a template marker replaced with the current worktree’s absolute path. It must be rendered before use. Project paths stay relative so the agent opens this checkout’s project.
The output overrides apply to the whole dependency graph. Generated Swift-package projects do not inherit the app’s xcconfig, and their PROJECT_DIR can point inside a dependency checkout. Using the rendered worktree root keeps their outputs in the same locations as native Xcode.
Each selectable MCP profile repeats derivedDataPath and references the same build arguments through a YAML anchor. Profiles replace global defaults, so configuring only the top-level defaults leaves a gap.
Share the compilation cache, keep module caches local
Create Configurations/Shared/BuildCache.xcconfig:
TRAILNOTE_XCODE_CACHE_ROOT = $(PROJECT_DIR)/DerivedData
COMPILATION_CACHE_ENABLE_CACHING = YES
COMPILATION_CACHE_CAS_PATH = $(TRAILNOTE_XCODE_CACHE_ROOT)/CompilationCache.noindex
SWIFT_ENABLE_PREFIX_MAPPING = YES
SWIFT_ENABLE_PROJECT_PREFIX_MAPPING = YES
MODULE_CACHE_DIR = $(TRAILNOTE_XCODE_CACHE_ROOT)/ModuleCache.noindex
SDK_EXPLICIT_MODULES_OUTPUT_PATH = $(TRAILNOTE_XCODE_CACHE_ROOT)/SDKExplicitPrecompiledModules
SDK_STAT_CACHE_DIR = $(TRAILNOTE_XCODE_CACHE_ROOT)
Include it from both Configurations/Debug/Debug.xcconfig and Configurations/Release/Release.xcconfig, with those files assigned to the corresponding project build configurations:
#include "../Shared/BuildCache.xcconfig"
Keep COMPILATION_CACHE_ENABLE_CACHING and Swift prefix mapping in the app xcconfig. Passing them through MCP’s extraArgs also changes generated package compiler commands, making agent and IDE builds differ. Prefix mapping reduces checkout-specific paths in compiler outputs.
SnapshotTesting locates reference images relative to #filePath. Prefix mapping can redirect that lookup outside the checkout and cause read-only-volume errors. For snapshot-test targets, override both settings to NO in Debug and Release:
SWIFT_ENABLE_PREFIX_MAPPING = NO
SWIFT_ENABLE_PROJECT_PREFIX_MAPPING = NO
The setup script symlinks CompilationCache.noindex to ~/Library/Developer/Xcode/TrailnoteSharedCaches/<Xcode-build-version>/CompilationCache.noindex. CAS means content-addressable storage. The key comes from the build version reported by xcodebuild -version, separating cache roots when the selected Xcode build changes.
Module caches stay local. Clang can treat a precompiled module (PCM) reached through a symlink and its canonical path as two module definitions. Sharing the entire DerivedData directory also exposes mutable XCBuildData, package state, products, and intermediates to concurrent builds and cleans.
This layout lets matching compilation-cache entries cross worktree boundaries. It does not guarantee that every compile from branch A replays in branch B: dependency and output graph details can affect cache keys. Each branch still owns its incremental build state.
Write the workspace settings and link the cache
Save this as scripts/configure-worktree-build-cache.sh:
#!/bin/bash
set -euo pipefail
script_directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
project_root="$(cd "${script_directory}/.." && pwd -P)"
project_path="${project_root}/Trailnote.xcodeproj"
workspace_settings_directory="${project_path}/project.xcworkspace/xcuserdata/$(id -un).xcuserdatad"
workspace_settings_path="${workspace_settings_directory}/WorkspaceSettings.xcsettings"
mcp_template_path="${project_root}/.xcodebuildmcp/config.yaml.template"
mcp_config_path="${project_root}/.xcodebuildmcp/config.yaml"
refresh_mcp_config=false
resolve_xcode_build_version() {
local developer_directory
if [[ -n "${DEVELOPER_DIR:-}" && -x "${DEVELOPER_DIR}/usr/bin/xcodebuild" ]]; then
developer_directory="${DEVELOPER_DIR}"
else
developer_directory="$(env -u DEVELOPER_DIR /usr/bin/xcode-select -p)"
fi
DEVELOPER_DIR="${developer_directory}" /usr/bin/xcodebuild -version \
| awk '/^Build version / { print $3; exit }'
}
link_shared_cache() {
local cache_name="$1"
local local_cache_path="${project_root}/DerivedData/${cache_name}"
local shared_cache_path="${shared_cache_root}/${cache_name}"
mkdir -p "${shared_cache_path}"
if [[ -L "${local_cache_path}" ]]; then
local existing_target
existing_target="$(readlink "${local_cache_path}")"
if [[ "${existing_target}" == "${shared_cache_path}" ]]; then
return
fi
if [[ "${existing_target}" == *'/Library/Developer/Xcode/TrailnoteSharedCaches/'* ]]; then
ln -sfn "${shared_cache_path}" "${local_cache_path}"
return
fi
elif [[ ! -e "${local_cache_path}" ]]; then
ln -s "${shared_cache_path}" "${local_cache_path}"
return
fi
printf 'Preserving existing cache path (not shared): %s\n' "${local_cache_path}" >&2
}
render_mcp_config() {
escaped_project_root="$(printf '%s' "${project_root}" | sed 's/[\\&|]/\\&/g')"
sed -e "s|__TRAILNOTE_WORKTREE_ROOT__|${escaped_project_root}|g" \
"${mcp_template_path}" > "${mcp_config_path}"
if rg -q '__TRAILNOTE_WORKTREE_ROOT__' "${mcp_config_path}"; then
printf 'Failed to render the XcodeBuildMCP path markers\n' >&2
exit 1
fi
}
case "${1:-}" in
"") ;;
--refresh-mcp-config)
refresh_mcp_config=true
;;
*)
printf 'Usage: %s [--refresh-mcp-config]\n' "${0}" >&2
exit 64
;;
esac
xcode_build_version="$(resolve_xcode_build_version)"
if [[ -z "${xcode_build_version}" ]]; then
printf 'Unable to determine the selected Xcode build version\n' >&2
exit 1
fi
shared_cache_root="${HOME}/Library/Developer/Xcode/TrailnoteSharedCaches/${xcode_build_version}"
mkdir -p "${workspace_settings_directory}"
if [[ ! -f "${workspace_settings_path}" ]]; then
plutil -create xml1 "${workspace_settings_path}"
fi
plutil -replace BuildLocationStyle -string CustomLocation "${workspace_settings_path}"
plutil -replace CustomBuildLocationType -string RelativeToWorkspace "${workspace_settings_path}"
plutil -replace CustomBuildProductsPath -string Build/Products "${workspace_settings_path}"
plutil -replace CustomBuildIntermediatesPath -string Build/Intermediates.noindex "${workspace_settings_path}"
plutil -replace DerivedDataLocationStyle -string WorkspaceRelativePath "${workspace_settings_path}"
plutil -replace DerivedDataCustomLocation -string DerivedData "${workspace_settings_path}"
plutil -lint "${workspace_settings_path}" >/dev/null
if [[ ! -f "${mcp_config_path}" || "${refresh_mcp_config}" == true ]]; then
render_mcp_config
if [[ "${refresh_mcp_config}" == true ]]; then
mcp_config_status="refreshed"
else
mcp_config_status="created"
fi
else
mcp_config_status="preserved"
fi
mkdir -p \
"${project_root}/DerivedData/Trailnote" \
"${project_root}/DerivedData/ModuleCache.noindex" \
"${project_root}/DerivedData/SDKExplicitPrecompiledModules" \
"${project_root}/Build/Products" \
"${project_root}/Build/Intermediates.noindex"
module_validation_file="${project_root}/DerivedData/ModuleCache.noindex/Session.modulevalidation"
if [[ ! -e "${module_validation_file}" ]]; then
touch "${module_validation_file}"
fi
link_shared_cache CompilationCache.noindex
printf 'Configured worktree-local Xcode build paths in %s\n' "${project_root}"
printf 'Shared Xcode cache root: %s\n' "${shared_cache_root}"
printf 'XcodeBuildMCP config: %s (%s)\n' "${mcp_config_path}" "${mcp_config_status}"
The script aligns Xcode’s workspace settings with MCP, preserves existing configuration and caches, and repoints recognized shared-cache symlinks when Xcode changes. It creates the module-validation file only once to avoid invalidating it on startup.
Make the script executable, then run it before opening Xcode or starting the MCP server:
chmod +x scripts/configure-worktree-build-cache.sh
scripts/configure-worktree-build-cache.sh
Commit the script, template, and xcconfig files. Add the generated paths to .gitignore:
/Build/
/DerivedData/
/.xcodebuildmcp/config.yaml
xcuserdata/
The template stays tracked; rendered configuration contains absolute paths for one checkout. If Xcode was already open, reopen the project. If the MCP server already loaded its configuration, restart it after first-time setup or a configuration refresh.
Initialize the cache before the agent builds
Add a blocking hook to .config/wt.toml:
[pre-start]
configure-xcode-cache = "scripts/configure-worktree-build-cache.sh"
After the project hook is approved, setup finishes before wt switch --create returns. But opening Codex in an existing worktree does not create a worktree. A startup hook covers that route with .codex/hooks.json:
{
"description": "Initialize Trailnote's worktree-local Xcode build paths when a Codex session starts.",
"hooks": {
"SessionStart": [
{
"matcher": "^(startup|resume)$",
"hooks": [
{
"type": "command",
"command": "root=\"$(/usr/bin/env -u DEVELOPER_DIR git rev-parse --show-toplevel 2>/dev/null)\" || exit 0; [ -d \"$root/Trailnote.xcodeproj\" ] || exit 0; script=\"$root/scripts/configure-worktree-build-cache.sh\"; [ -x \"$script\" ] || exit 0; \"$script\" >/dev/null",
"timeout": 30,
"statusMessage": "Configuring Xcode worktree cache"
}
]
}
]
}
}
The command checks for the Trailnote project and executable setup script before running. Root discovery clears DEVELOPER_DIR because a stale toolchain selection can break the Apple git shim. The script receives the original environment: it honors a valid alternate Xcode directory and falls back to xcode-select when that directory is invalid.
Codex requires a trusted project layer and review of the current hook definition. Use /hooks to review it; changed definitions need renewed trust. Command hooks run synchronously by default, so this setup completes before the agent continues. Those behaviors are documented in the official Codex hooks reference.
A build phase runs too late. Xcode has already resolved DerivedData, products, and intermediate paths for that build. Startup is the point where configuration can affect the first build.
Migrate existing worktrees without deleting their caches
If setup reports Preserving existing cache path (not shared) for a real directory, that worktree still has a local compilation cache. Stop all builds using it, move the directory to a unique backup name, and rerun setup:
mv DerivedData/CompilationCache.noindex \
"DerivedData/CompilationCache.noindex.backup.$(uuidgen)"
scripts/configure-worktree-build-cache.sh
The old cache stays recoverable. Leave an unrelated symlink alone until you know what owns it.
Older MCP configuration needs an explicit refresh:
scripts/configure-worktree-build-cache.sh --refresh-mcp-config
That replaces local profile selections and device identifiers, so neither hook refreshes it automatically. Restore your local values afterward and restart the MCP server. Rerun setup after selecting a new Xcode build; a new empty shared root is expected.
Check scripts that locate package checkouts
Moving products out of DerivedData can break scripts that infer a package checkout from BUILD_DIR. A Crashlytics upload phase might look for firebase-ios-sdk alongside the products even though Xcode keeps the checkout under DerivedData/Trailnote/SourcePackages.
Use the known checkout location for this layout:
upload_symbols="${PROJECT_DIR}/DerivedData/Trailnote/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/upload-symbols"
if [[ ! -x "$upload_symbols" ]]; then
printf 'Missing Crashlytics upload tool: %s\n' "$upload_symbols" >&2
exit 1
fi
This replaces the path lookup in an existing upload phase; keep its simulator guards, configuration checks, and upload arguments. Check other build scripts for the same assumption before changing output locations.
Verify reuse without cleaning
Check the resolved settings and shared-cache link first:
set -o pipefail
xcodebuild -project Trailnote.xcodeproj -scheme Trailnote -configuration Debug \
-showBuildSettings \
| rg 'BUILD_DIR|BUILD_ROOT|SYMROOT|OBJROOT|COMPILATION_CACHE_ENABLE_CACHING|COMPILATION_CACHE_CAS_PATH|MODULE_CACHE_DIR'
readlink DerivedData/CompilationCache.noindex
xcodebuild -version
The outputs should stay under this worktree’s Build/ and DerivedData/. The symlink should point into TrailnoteSharedCaches under the selected Xcode build version. In XcodeBuildMCP, use session_show_defaults to confirm the active profile’s project, DerivedData path, and rendered arguments too.
Use the same Xcode build, scheme, configuration, simulator, and architecture throughout. Run IDE and agent builds sequentially inside a worktree:
- Build twice through Xcode without edits. The second build establishes the amount of work an unchanged IDE build performs.
- Build through XcodeBuildMCP with the same settings. Compare compile tasks with that baseline, then repeat through MCP. Switching tools should not trigger broad recompilation.
- Build again in Xcode without edits. Compare compile tasks with the unchanged IDE baseline. This checks the MCP-to-Xcode handoff too; neither direction should trigger broad recompilation.
- Initialize a second worktree at the same commit and build it. Both cache symlinks should reach the same shared root, while products and intermediates stay separate. Inspect compiler task details in the build log for cache hits; a compile task appearing in the timeline does not by itself prove a cache miss.
Task skipping inside one worktree measures incremental reuse. Compiler cache hits in the second worktree measure reuse of cached compilation results. A shorter elapsed time alone does not distinguish them. Keep the logs from each route for comparison, and do not clean between measurements.
Environment differences such as PATH can still trigger linking and signing. Plugins such as Prefire may also regenerate sources. Compare compile tasks and cache hits against the unchanged-build baseline; elapsed time alone cannot establish reuse.
What to keep
Inside one worktree: align Xcode and agent build paths so both routes can reuse the same incremental state.
Across worktrees: share the Xcode-versioned compilation CAS; keep mutable outputs and module caches local.
Before the first build: run one idempotent setup script from blocking Worktrunk and Codex startup hooks. Instructions in AGENTS.md describe the workflow; hooks execute it.