How Apache Maka's Graph Implementation Uses Isolated Git Worktrees for Agent Execution

Apache Maka leverages isolated Git worktrees to provide each sub-agent in its graph-based execution model with a lightweight, mutable sandbox that prevents cross-session contamination and enables deterministic replay.

Apache Maka is an open-source agentic framework that orchestrates complex workflows through a graph-based execution model called the agent-graph. At the core of this architecture, the system uses Git worktrees—lightweight, linked copies of a repository—to create isolated execution environments for each sub-agent session. This approach allows parallel, mutable execution without contaminating the host repository state.

The GitWorktreeChildExecutor Architecture

The isolation logic lives in the GitWorktreeChildExecutor class within packages/storage/src/git-worktree-child-executor.ts. This component acts as the central allocator for sub-agent workspaces, handling creation, validation, capture, and retirement of isolated worktrees.

Each worktree is a deterministic, lease-based binding tied to a specific graph execution session. The executor maintains a host-owned root directory (this.worktreeRoot) where all sub-agent worktrees reside, ensuring complete separation from the source repository.

Provisioning and Validating Isolated Worktrees

The executor follows a strict lifecycle to ensure each sub-agent receives a pristine, verified environment.

Eligibility Detection

Before provisioning, the isAvailable method verifies the source directory qualifies as a Git project by checking source.kind === 'git' && source.git !== undefined. In packages/storage/src/project-catalog.ts, the catalog resolves the Git worktree root to ensure the executor targets the correct repository location.

Deterministic Allocation

The provisionOnce method creates a unique, deterministic workspace using the lease ID:

const suffix = leaseSuffix(input.leaseId);
const worktreePath = join(root, suffix);
const branch = `maka/subagent/${suffix}`;

This generates a unique branch name under the maka/subagent/ namespace and constructs a dedicated path under the host-owned worktree root. If a worktree already exists at that path, the executor adopts it; otherwise, it executes git worktree add to create a fresh copy at the current HEAD, followed by git switch to activate the dedicated branch.

Lease Recording and Verification

To guarantee integrity, the executor stores metadata in custom Git config keys:

  • branchLeaseConfigKey: Stores the lease ID
  • branchBaseConfigKey: Stores the base commit SHA

The setBranchLease function persists these values during provisioning. Later, the ensure method re-reads this config and validates that the worktree, branch, and base commit match the stored lease. If tampering is detected, the system throws an error before any agent code executes.

Capturing Session State for Deterministic Replay

When a graph session completes, the capturePatch method serializes the entire worktree state. The process stages all current changes into a temporary Git index using git add, then generates a binary diff via git diff --cached.

This diff represents the exact delta between the original base commit and the final sub-agent state. The host can later replay this patch to reconstruct the session's output, enabling deterministic state reconstruction without preserving the temporary worktree indefinitely.

Cleanup and Fault Recovery

Isolation requires rigorous cleanup to prevent disk bloat and security leaks.

Orphaned Worktree Recovery

The recover method scans the host-owned worktree root directory. For each entry, it attempts to re-attach live bindings or invokes retireOrphan to remove stale worktrees left by crashed sessions. This self-healing mechanism ensures the system remains clean even after failures.

Explicit Retirement

When a session ends normally, the retire method explicitly deletes the worktree directory and removes the associated Git metadata. Because each worktree is isolated, retiring a crashed or compromised sub-agent workspace cannot harm the host repository or other concurrent sessions.

Runtime Integration

The executor integrates with the broader Apache Maka runtime through packages/runtime-host/src/server/execution-composition.ts. Here, the host creates the executor instance:

import { createGitWorktreeChildExecutor } from '@maka/storage/git-worktree-child-executor';
const worktreeChildExecutor = createGitWorktreeChildExecutor({ storageRoot });

The managed-workspace-owner.ts component declares a workspace mode of 'managed_worktree', bridging the executor to the agent-graph supervisor. When the graph scheduler spawns a child session, it provisions a worktree through this executor, executes the agent task against the isolated path, captures the resulting patch, and retires the workspace—all before the next scheduling cycle begins.

Practical Implementation Example

Below is a complete workflow demonstrating how to provision, utilize, and retire an isolated worktree:

import { createGitWorktreeChildExecutor } from '@maka/storage/git-worktree-child-executor';
import type { ProvisionSubagentWorktreeInput } from '@maka/core/subagent-workspace';

// Initialize the executor with a host-owned storage root
const executor = createGitWorktreeChildExecutor({ storageRoot: '/var/maka/storage' });

// Provision a deterministic worktree for a new sub-agent session
const provisionInput: ProvisionSubagentWorktreeInput = {
  leaseId: '1234abcd',
  sourceCwd: '/repo/my-project',
  sourceProjectId: 'proj-123',
  sourceSessionId: 'session-42',
};
const binding = await executor.provision(provisionInput);

// Execute agent logic against the isolated worktree path
await runYourTaskAgainst(binding.worktreePath);

// Capture the state diff and retire the workspace
const patch = await executor.capturePatch(binding);
await storePatchForReplay(patch);
await executor.retire(binding);

Summary

  • Isolated Git worktrees provide each Apache Maka sub-agent with a lightweight, independent file system view derived from the host repository's HEAD.
  • Deterministic provisioning uses lease IDs to generate unique branch names (maka/subagent/<suffix>) and worktree paths, ensuring repeatable workspace allocation.
  • Integrity verification through custom Git config keys (branchLeaseConfigKey, branchBaseConfigKey) prevents execution on tampered worktrees.
  • State capture via capturePatch creates replayable binary diffs, enabling reconstruction of agent outputs without persistent workspaces.
  • Fault isolation allows crashes in one sub-agent to be contained and cleaned via recover and retire without affecting the host repository or parallel sessions.

Frequently Asked Questions

How does Apache Maka ensure complete isolation between sub-agent worktrees?

Each sub-agent receives a distinct Git worktree created via git worktree add in a host-controlled directory separate from the source repository. The provisionOnce method generates unique branch names and paths based on cryptographically-derived lease suffixes, while the ensure validation step verifies Git config metadata before execution. This guarantees that file system mutations, branch switches, or commits within one worktree remain invisible to others.

What happens if a sub-agent crashes before retiring its worktree?

The recover method in git-worktree-child-executor.ts periodically scans the worktree root for orphaned directories. When it detects a worktree without an active lease binding, it either re-attaches the binding if the session is resumable or invokes retireOrphan to remove the directory and clean up associated Git references. This prevents zombie worktrees from consuming disk space or leaking sensitive intermediate states.

Can captured patches be reapplied to repositories other than the original host?

Captured patches are standard Git binary diffs generated by git diff --cached within the isolated worktree. While designed for replay against the original base commit stored in branchBaseConfigKey, these patches can technically apply to any repository sharing that commit history. However, Apache Maka's execution model specifically targets the original host repository to maintain deterministic lineage and traceability within the agent-graph timeline.

Where is the Git worktree root configured in an Apache Maka deployment?

The worktree root is configured during executor initialization in packages/runtime-host/src/server/execution-composition.ts, where createGitWorktreeChildExecutor receives a storageRoot parameter. This root directory is typically resolved through the project catalog (packages/storage/src/project-catalog.ts), which maps project IDs to their Git worktree locations, ensuring the executor always operates within the correct repository context.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →