In the previous chapter, Chapter 3: Worktree Lifecycle Actions, we learned how to physically delete or preserve the temporary folder on the hard drive.
However, we have created a dangerous situation. Imagine this scenario:
If the AI tries to run a command like ls (list files) immediately after deleting the folder, the system will crash because the directory it thinks it is in no longer exists.
In this chapter, we will build the Session Context Restoration logic. This acts like a "teleport" button that instantly transports the AI's mind back to the original project after the temporary work is done.
When our AI works in a temporary environment, it builds up "state" (memory):
/tmp/fix-bug-123."file.ts in this folder."If we simply delete the folder but don't wipe this memory, the AI might hallucinate. It might try to read a file it remembers, only to find it gone.
User: "Exit the session and go back to main." Action: The tool deletes the folder. Goal:
This process happens automatically right after the folder is handled.
restoreSessionToOriginalCwd FunctionWe encapsulate all this cleanup logic in a single helper function. Let's build it step-by-step.
The most urgent task is to move the current working directory (CWD).
// ExitWorktreeTool.ts
function restoreSessionToOriginalCwd(originalCwd: string, ...) {
// 1. Physically change the process directory
setCwd(originalCwd)
// 2. Update the internal tracker for "Original CWD"
setOriginalCwd(originalCwd)
// ... continued below
}
Explanation: setCwd performs the actual cd command. setOriginalCwd updates the variable that tracks where the user started the application.
The "Project Root" is the main folder of the repository. When entering a worktree, the root changes to the temporary folder. We must change it back.
// ... inside restoreSessionToOriginalCwd
if (projectRootIsWorktree) {
// Restore the root to the main project
setProjectRoot(originalCwd)
// Reload configuration hooks (like pre-commit hooks)
// from the main project
updateHooksConfigSnapshot()
}
Explanation: We check projectRootIsWorktree (a boolean passed in). If the root was indeed pointing to the temp folder, we reset it. We also reload any project-specific settings (Hooks).
Finally, we clear the AI's caches. This forces the AI to re-read files from the disk the next time it needs them, ensuring it sees the original project files, not the temporary ones.
// ... inside restoreSessionToOriginalCwd
// 1. Forget the active session ID
saveWorktreeState(null)
// 2. Clear prompt sections specific to the session
clearSystemPromptSections()
// 3. Clear file content caches and plan caches
clearMemoryFileCaches()
getPlansDirectory.cache.clear?.()
}
Explanation:
saveWorktreeState(null): Tells the system "We are no longer in a session."clearMemoryFileCaches(): Discards all "remembered" file contents.Now, let's look at how we call this function from the main tool logic (which we built in Chapter 3).
We need to calculate projectRootIsWorktree before we run the restoration.
// Inside call() method
// Did the "Project Root" point to our worktree?
// If getProjectRoot() == getOriginalCwd(), usually yes.
const projectRootIsWorktree = getProjectRoot() === getOriginalCwd()
// ... perform delete or keep action ...
// Now run the restoration
restoreSessionToOriginalCwd(originalCwd, projectRootIsWorktree)
projectRootIsWorktree needed?You might ask: Why don't we always just set the project root to the original CWD?
The Edge Case:
Imagine the user started the tool in /Users/me/projects/my-app.
Then, before entering the worktree, they cd'd into /Users/me/Desktop.
Then they entered a worktree.
When they exit, we want to put them back in /Users/me/projects/my-app (where the tool started), but we don't want to accidentally mess up the "Project Root" if it was set to something complex.
The boolean check ensures we only reset the root if the root was the temporary session. It preserves "Stable Project Identity."
In this chapter, we handled the invisible but critical part of exiting a session: State Management.
At this point, the tool has fully executed. The files are handled, and the AI is back home. The only thing left to do is tell the user (and the AI) that we succeeded.
How do we format a nice message that explains exactly what happened?
Generated by Code IQ