Skip to content

perf(worktree): accelerate worktree creation & worktree-on-send across Git, main process, renderer, and native file I/O - #868

Merged
sambitcreate merged 23 commits into
mainfrom
worktree_performance_optimization
Nov 23, 2026
Merged

sambitcreate merged 23 commits into
mainfrom
worktree_performance_optimization

Conversation

@sambitcreate

@sambitcreate sambitcreate commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements Tier 1 and Tier 2 worktree creation performance optimizations across four phases—making explicit worktree creation, worktree-on-send, and .worktreeinclude provisioning dramatically faster and visually smoother while preserving every ownership, admission, TOCTOU, snapshot, and disk-capacity safety invariant.

Each phase was independently audited by two adversarial review passes, with every finding fixed and covered by behavioral tests before advancing.

Before vs. After Performance Benchmarks

Measured head-to-head on aiden-macos (6,497 tracked files, Apple Silicon APFS, 5-run uncontended medians, origin/main 6555f1767 vs. this PR):

Operation Before (origin/main) After (this PR) Time / Work Saved % Reduction Speedup
Explicit Create (createIn + createWorktree) 1,417 ms (1.42 s · 127 git spawns) 744 ms (0.74 s · 8 git spawns) −673 ms (−0.67 s · −119 spawns) −47.5% (−93.7% spawns) 1.90×
Worktree-on-Send Backend (local base → ready for LLM) 1,915 ms (1.92 s · 144 git spawns) 711 ms (0.71 s · 12 git spawns) −1,204 ms (−1.20 s · −132 spawns) −62.9% (−91.7% spawns) 2.69×
Post-Create git.info(worktreePath) 172.82 ms (0.17 s · 6 git spawns) 0.77 ms (0.0008 s · 0 git spawns) −172.05 ms (−6 spawns) −99.6% (−100% spawns) 224×
Per-Operation Admission (managedWorktreeUsable) 15.28 ms (0.015 s · 4 git spawns) 0.58 ms (0.0006 s · 0 git spawns) −14.70 ms (−4 spawns) −96.2% (−100% spawns) 26.3×
.worktreeinclude (31 ignored files, clean repo) 100 ms (0.10 s · 31 helper spawns + 62 fsyncs) 40 ms (0.04 s · 1 batched CoW spawn) −60 ms (−30 spawns) −60.0% 2.50×
.worktreeinclude (31 ignored files + 5,000-file node_modules) Crashed (output_limit > 1 MiB) 44 ms (0.04 s · 0 crashes) Crash eliminated 100% crash fix ∞

Changes by Phase

Phase 1 — Backend Git Core & .worktreeinclude Fast Path

  • Collapsed GitService.repository() from 3 rev-parse spawns (2 serial rounds) to 1 spawn (rev-parse --is-inside-work-tree --show-toplevel --git-common-dir) with newline-in-path fallback.
  • Replaced the 128-path sequential git check-attr loop (~102 spawns) in managedWorktreeCheckoutBytes with 1 streaming git check-attr --cached -z --all --stdin parser on raw Buffer slices (O(1) memory, immune to 1 MiB buffer overflow, still honors info/attributes, global config, and includeIf).
  • Deduplicated outer vs. inner checkout-bytes and capacity admission by passing additionalAllocationBytes into git.createWorktree (enforced atomically inside enqueueMutation(repo.commonDir) before mkdir/worktree add).
  • Enabled APFS-tuned parallel checkout (checkout.workers = min(4, cpus), checkout.thresholdForParallelism = 50) on all worktree add sites.
  • Added direct <wt>/.git ↔ <admin>/{gitdir,commondir,HEAD} inspection in inspectNewlyCreatedWorktree() (with fallback), parallelized independent base-ref / branch reads with linked AbortController cleanup, and streamed for-each-ref in resolveWorktreeBase.
  • Inverted .worktreeinclude discovery (ls-files --exclude-from=.worktreeinclude → short-circuit if empty → git check-ignore -z --stdin with ./-prefixing to neutralize : pathspec magic), eliminating the node_modules output_limit crash.

Phase 2 — Main-Process 0-Spawn Admission, Cached Skills, Pi dirIndex & Store Gating

  • Implemented live 0-spawn pure-FS managedWorktreeUsable (O_RDONLY | O_NOFOLLOW | O_NONBLOCK, loose + packed-refs, reftable fallback, fenced with while (this.mutations.has(commonDir)) + mutationEpochs).
  • Seeded display-only repositoryCache / infoCache / repositoryIdentities for newly created worktrees (fenced by pre/post repoRemoteHintSignature and mutationEpochs).
  • Split global vs. workspace skill candidate discovery with a 5 s global cache (discoverSkillCandidatesWithCachedGlobals) keyed on [home, aidenDir, globalPluginConfigs] while keeping resolveFresh() uncached.
  • Added per-file lstat-signatured dirIndex + monotonic dirMutationVersion concurrency fence in PiCompactionSessionStore so brand-new chats skip migration/list scans.
  • Gated redundant protectLocal() rescans on warm portable-config-core loads when ownedPaths.length === 0 && archivePublicationPaths.size === 0 while keeping ensurePrivateDirectory(root) live and checking lstat (nlink === 1n, mode, uid, mtime/ctime) on config.json and recorded secondary files.

Phase 3 — Renderer Perceived Speed, IPC Coalescing & Smooth Transitions

  • Extended FirstMessageWorktreeResult with optional workspace and narrowed workspaces:changed on creation ({ kind: "created", workspace }), sharing upsertCreatedWorkspaceInCache across root-view.tsx and chat-pane.tsx to skip blocking workspaces:list / redundant chats:list refetches on worktree addition (keeping full invalidation for removals/restores).
  • Pipelined read-only global skill warmup in chats:createWithFirstMessage when skillsEnabled !== false (without touching workspace folders).
  • Added StrictMode-safe one-shot markChatRecentlyPromoted freshness in useChat so draft → live promotion reuses the seeded snapshot without a redundant chats:get IPC, while leaving and revisiting always re-reads.
  • Rendered pending worktree-on-send state inside MessageList (keepForkWrapper + "draft-prompt" key handoff) for zero-remount bubble promotion; bypassed blocking pre-send folderPresence IPC when cached presence is not missing (still re-checking live if cached "missing"); added frame-0 seedDraftWorktreeFromGitInfo seeding for ⌥↵ and /worktree.
  • Isolated volatile useWorkspaceArtifacts state into EnvironmentArtifactsContext (useEnvironmentPanelCore() for ChatPane, ChatSidebar, RootView, HistoryNavButtons, DesignLayout) and gated useGitWorktrees in GitBranchPicker.

Phase 4 — Native Batched CoW provision (native/worktree-file-io/main.c)

  • Preserved copy and restore (with SHA-256) untouched for snapshot capture/restore.
  • Added dedicated provision subcommand reading NUL-delimited paths from stdin (1 spawn for all .worktreeinclude files), using APFS fclonefileat(..., CLONE_NOFOLLOW | CLONE_NOOWNERCOPY) into a random temp file when eligible, clearing fchflags(cloned, 0) before fchmod(cloned, mode & 0777), verifying flistxattr(cloned) == 0 + same_provision_source, installing atomically with renameatx_np(..., RENAME_EXCL), falling back to read/write on EXDEV/ENOTSUP/EACCES/EPERM, and deduplicating parent directory fsyncs (capped at 64 open FDs).
  • Wired SIGTERM handling in main.c + close-gated AbortSignal settlement in provisionManagedWorktreeFilesBatch so disk installs stay strictly 1:1 with onProvisioned rollback tracking.

Verification

  • npx tsc --noEmit — pass
  • npm run lint — pass (0 errors, 0 warnings)
  • node --test scripts/worktree-file-io.test.mjs — 19/19 pass
  • npx tsx --test main/services/git.test.ts main/services/managed-worktree-admission.test.ts — 123/123 pass
  • npx tsx --test main/services/managed-worktree-lifecycle.test.ts main/services/workspace-worktree-application-service.test.ts — 57/57 pass
  • npm run test:aiden-service-boundary — pass
  • npm run test:worktree-on-send — pass
  • npm run test:aiden-remote — 1,268/1,268 + 7/7 pass
  • npm run test:cli — pass
  • Docs & memory updated: docs/plans/worktree-creation-performance.md, docs/plans/README.md, .memory/worktree-creation-performance.md

Flaky CI Observations

  • On commit e78f45b55, tests/e2e/crash-reporting.spec.ts:41 (uncaught errors, process deaths and a fatal main crash are reported, sanitized, across a relaunch) failed attempt 1 with Error: Target crashed / electronApplication.evaluate: Target page, context or browser has been closed and passed on retry Use catalog-driven runtime model limits #1 (run 44978492821 / job 137082618807). Unrelated to worktree creation; passed cleanly on ba55fa2ce.
  • On commit 84717cdd1, Desktop tests (runtime-subagents) hung after aiden-remote-sealed-envelope.test.ts (X25519 agreement refuses low-order peer keys) and hit the 25-minute job cancellation timeout (run 44990828956 / job 137111372226). Unrelated to worktree creation; passed cleanly on ba55fa2ce and e78f45b55.
  • On commit 5a7137063, Desktop tests (renderer-other) failed in untouched renderer/components/workspace-picker.test.tsx (closing the menu mid-clone cancels the clone, Unable to find a label with the text of: Git URL or owner/repo, run 45002201436 / job 137146069694). Passes 21/21 locally and passed on ba55fa2ce, e78f45b55, and 84717cdd1.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Three correctness regressions should be addressed before merging: provisioned file data is no longer durably flushed, pre-hook clean-status seeds can hide setup changes, and zero-spawn admission can bypass repository-config revocation.

Reviewed changes Reviewed the complete 40-file change set across Git, main-process orchestration, renderer cache/transition behavior, native file I/O, and focused tests.

  • Git and admission — Combined discovery and streamed Git output, parallelized worktree creation, moved capacity admission under the mutation queue, seeded post-create metadata, and added pure-filesystem managed-worktree validation.
  • Provisioning and lifecycle — Narrowed .worktreeinclude discovery, introduced the batched APFS clone/read-write helper protocol, and threaded rollback/provision reserves through desktop and CLI worktree creation.
  • Main-process fast paths — Added cached global skill discovery, Pi journal directory indexing, portable-config hardening signatures, and inline workspace returns from first-message creation.
  • Renderer transitions — Coalesced workspace/chat reads, added one-shot promoted-chat freshness, seeded draft worktree defaults, moved pending sends into MessageList, and split artifact state from core environment context.
  • Verification surfaces — Reviewed the changed Git, admission, lifecycle, native-helper, and renderer tests, including whether their assertions exercise the claimed safety properties.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread native/worktree-file-io/main.c Resolved
Comment thread main/services/git.ts Resolved
Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The config-gated admission fix is incomplete for Git configuration loaded through existing include files, so one managed-worktree capability check can still bypass repository revocation.

Reviewed changes Reviewed the two commits added since the prior Pullfrog review, including the three corrective paths and the merge reconciliation.

  • Restored provision durability — Added file-level fsync barriers for both APFS clone and read/write provisioning before parent-directory synchronization and success reporting.

  • Invalidated post-hook status — Returned executed hook names, invalidated main and CLI Git display caches after awaited setup hooks, and removed renderer-side clean-status seeds.

  • Gated pure-FS admission — Added a Git-verified repository identity signature, per-worktree config fallback, and a focused direct .git/config revocation test.

  • Reconciled current main — Merged the latest base changes around the MessageList visual context without changing the worktree-send behavior.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The include-free proof still misses custom global and system config filenames, so zero-spawn admission can continue past repository-config revocation.

Reviewed changes Reviewed the config-proof commit added since the prior Pullfrog review, including its production path and focused admission coverage.

  • Expanded config proof: Added signatures for local, global, and system Git config paths and disabled pure-FS admission when recognized config files contain include directives.

  • Extended revocation coverage: Added a regression case for a local include.path target changing after Git-verified admission.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The latest config-proof fix still misses system config files selected by alternate Git installations, so zero-spawn admission can survive repository revocation.

Reviewed changes Reviewed the two commits added since the prior Pullfrog review, including the config-proof correction and current-main merge.

  • Generalized config scanning: Separated config files from routing identity paths so arbitrary GIT_CONFIG_GLOBAL and GIT_CONFIG_SYSTEM filenames are inspected for include directives.
  • Scoped proof publication: Moved verified proof publication to managed-worktree admission and creation, with environment-selected path and signature rechecks before pure-FS returns.
  • Extended regression coverage: Added a custom-named global config include case that exercises fallback after its included target changes.
  • Merged current main: Reconciled the branch with the latest base without altering the incremental worktree behavior.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The system-config origin cache can retain a stale path after the active Git executable changes, so zero-spawn admission can still survive system-config revocation.

Reviewed changes Reviewed the system-config-origin correction added in 5a7137063 since the prior Pullfrog review.

  • Probed active system config: Replaced hard-coded platform guesses with git config --system --list --show-origin -z and signed the reported origins into the pure-filesystem admission proof.
  • Expanded alternate-installation coverage: Added behavioral cases for existing, initially missing, and empty system config files selected by a custom Git executable.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The executable-identity fix still lets dynamic wrappers or shims retain a stale system-config proof, so the admission bypass remains for a supported Git binary shape.

Reviewed changes Reviewed the executable-identity and system-config proof correction added in f26db8f34 since the prior Pullfrog review.

  • Reprobed system origins: Removed the process-lifetime origin cache so each fresh proof asks the active Git command for its system-config origins.
  • Bound proofs to executable identity: Added before/after executable filesystem signatures during proof construction and rechecked the signature before every pure-filesystem admission.
  • Expanded rerouting coverage: Added a behavioral case that rewrites a direct-path wrapper from config A to config B and verifies that corrupting B falls back to Git.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved
@pullfrog

pullfrog Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Run failed. View the logs →

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Rerun failed job ➔ | View workflow run | via Pullfrog | Using GPT Sol | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The new direct-binary proof disables zero-spawn admission on a stock Debian/Ubuntu Git layout and fails the focused admission suite. The prior delegated-routing concern also remains open for native shims placed at an allowlisted path.

Reviewed changes Reviewed the executable-proof hardening and current-main merge added since the prior Pullfrog review.

  • Restricted proof eligibility — Limited proof publication to standard install paths, native Mach-O/ELF files, signed symlink chains, and environments without selected executable-routing overrides.
  • Verified direct Git identity — Added fresh-versus-memoized resolution checks and required the selected binary to self-identify through its Git exec path.
  • Expanded adversarial coverage — Added cases for mutable wrappers, compiled shims, spoofed exec paths, repointed multi-hop symlinks, and GIT_EXEC_PATH overrides.
  • Merged current main — Reconciled the branch with current transcript activity-transition behavior.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread main/services/git.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes Reviewed the trusted-Git identity correction added in 17f288474 since the prior Pullfrog review, with the complete PR diff checked for context.

  • Authenticated trusted Git installs — Restricted pure-filesystem proof publication to Apple-signed CLT/Xcode Git or root-owned, non-writable Linux /usr/bin/git installations, closing the remaining native-shim routing gap.
  • Restored stock Linux admission — Added bounded SHA-256 equivalence for Debian/Ubuntu's distinct-inode /usr/bin/git and exec-path copy, restoring the advertised zero-spawn path while preserving fail-closed wrapper behavior.
  • Verified focused behavior — Confirmed the executable/admission suite passes 33/33, TypeScript and focused lint pass, and both previously open Pullfrog threads are resolved.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | View workflow run | Using GPT Sol | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes Reviewed the test-only dc0456e40 delta that landed after the prior Pullfrog review.

  • Pinned Apple Git coverage — Selected /usr/bin/git on macOS so Homebrew-first hosts still exercise the Apple-signed CLT/Xcode zero-spawn admission path.
  • Preserved cross-platform coverage — Kept Linux behavior unchanged and retained explicit wrapper, shim, config-revocation, and GIT_EXEC_PATH assertions; the focused suite still passes 33/33 and focused lint is clean.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | View workflow run | Using GPT Sol | 𝕏

…e-3c19a5bf

# Conflicts:
#	docs/plans/README.md
…e-3c19a5bf

# Conflicts:
#	renderer/components/message-list.tsx
#	renderer/lib/chat-draft.ts
#	renderer/main/chat-transition.test.tsx
#	renderer/main/root-view.tsx

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes Reviewed the two merge commits added since the prior Pullfrog review, including every conflict resolution and the complete PR diff for context.

  • Preserved plan inventory — Kept both the worktree performance entry and the newly merged iPhone Duo entry while reconciling docs/plans/README.md.
  • Reconciled draft state — Combined Quick Chat's ephemeral and attachment handoff state with the PR's seeded worktree draft options without allowing the unsupported ephemeral + worktree request.
  • Reconciled transcript rendering — Preserved compact Quick Chat layout and handoff coverage alongside the pending worktree row and zero-remount prompt promotion.
  • Verified exact-head behavior — Confirmed the focused draft, Quick Chat contract, and transition tests pass 68/68; TypeScript and focused ESLint are clean.

Pullfrog  | ⚠️ this action is pinned to a commit SHA, which freezes the cleanup step — switch to @v0 or keep the SHA fresh with Dependabot | View workflow run | Using GPT Sol | 𝕏

@sambitcreate
sambitcreate merged commit 540eb78 into main Nov 23, 2026
31 of 32 checks passed
@sambitcreate
sambitcreate deleted the worktree_performance_optimization branch November 23, 2026 08:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant