In the previous chapter, Tool Definition, we built the "outer shell" of our tool. We defined its name, description, and the interface for the AI.
Now, we are going to open the hood and build the engine. Welcome to the Worktree Session Logic.
Imagine you are a painter working on a masterpiece (your main code branch). Someone asks you to quickly sketch a rough idea, but you don't want to mess up your canvas. You need a separate easel in a separate room to experiment safely.
Worktree Session Logic is the machinery that:
The Scenario: The user says, "I want to rewrite the database layer, but keep it experimental."
The Goal: The tool must create a folder named rewrite-db-layer (backed by Git) and move the AI's execution context into that folder.
Before we look at the code, let's understand the three pillars of this logic.
You cannot create a sandbox inside a sandbox. The logic must ensure the AI isn't already inside a temporary worktree. If it is, we stop the operation to prevent confusion.
chdir)
When a computer program runs, it has a "Current Working Directory" (CWD). It's like the program's "feet." If the AI needs to edit files in the new worktree, we must physically move its feet to the new path using process.chdir.
The AI has "caches" (memory) of the files it has read. When we switch directories, that memory becomes stale. We must wipe the cache so the AI sees the new files, not the old ones.
Let's look at how the call method in EnterWorktreeTool.ts handles this, step-by-step.
First, we verify we aren't already in a session. Then, we ensure we are anchoring our worktree from the true root of the repository, not a random subfolder.
// Check if we are already in a worktree
if (getCurrentWorktreeSession()) {
throw new Error('Already in a worktree session')
}
// Find the true 'main' folder of the project
const mainRepoRoot = findCanonicalGitRoot(getCwd())
// Move to the root before starting
if (mainRepoRoot && mainRepoRoot !== getCwd()) {
process.chdir(mainRepoRoot)
setCwd(mainRepoRoot)
}
Explanation: We use helper functions (like findCanonicalGitRoot) to orient ourselves. We don't want to create a worktree inside a nested folder src/components/, so we move to the root first.
We determine the name for our folder. If the AI provided a name (validated in Input Validation Schema), we use it. Otherwise, we generate a default one.
// 'slug' is the folder name (e.g., "rewrite-db-layer")
const slug = input.name ?? getPlanSlug()
// This function performs the heavy Git operations
const worktreeSession = await createWorktreeForSession(
getSessionId(),
slug
)
Explanation: createWorktreeForSession is a utility that runs the actual git worktree add commands. It returns an object containing the path to the new directory.
This is the most critical part. We physically move the process and save the state.
// 1. Change the Node.js process directory
process.chdir(worktreeSession.worktreePath)
// 2. Update the internal application state
setCwd(worktreeSession.worktreePath)
// 3. Save the original location so we can go back later
setOriginalCwd(getCwd())
// 4. Persist this session to disk
saveWorktreeState(worktreeSession)
Explanation: process.chdir moves us. saveWorktreeState ensures that if the application crashes and restarts, it knows it's currently inside a worktree.
Now that we are in a new folder, the AI's previous knowledge of the file system is wrong. We need to clear it.
// Re-calculate the system prompt (env_info) for the new folder
clearSystemPromptSections()
// Forget contents of files read in the old folder
clearMemoryFileCaches()
// Clear other caches related to plans
getPlansDirectory.cache.clear?.()
Explanation: If we don't do this, the AI might hallucinate files from the main branch that don't exist in the new worktree, or vice versa.
Let's visualize the flow of data and control when this logic runs.
Finally, the logic packages the result to send back to the AI. This uses the schema we will define in Input Validation Schema and formats the output.
// Construct a helpful message explaining what happened
const branchInfo = worktreeSession.worktreeBranch
? ` on branch ${worktreeSession.worktreeBranch}`
: ''
return {
data: {
worktreePath: worktreeSession.worktreePath,
worktreeBranch: worktreeSession.worktreeBranch,
message: `Created worktree at ${worktreeSession.worktreePath}${branchInfo}.`,
},
}
Explanation: The message is crucial because the AI reads it to understand its new reality. It explicitly tells the AI: "You are now working in the worktree."
In this chapter, we explored the Worktree Session Logic, the engine that powers our tool. We learned how to:
process.chdir) so the AI acts on the correct files.
However, we have been assuming the input.name provided by the AI is always correct. But what if the AI tries to name the worktree ../../dangerous-folder? We need to validate inputs rigorously.
Next Chapter: Input Validation Schema
Generated by Code IQ