Skip to content

Cleaning Up After Claude Worktrees

Calculating...

TL;DR. If you copied the one-database-per-worktree hook from my last post, you've probably got a few databases sitting on your SQL Server that belong to worktrees that no longer exist. A reader spotted it, I went digging, and there were two reasons. The sweep now checks git worktree list, tags the databases it owns, and has a dry run. Upgrade steps are at the bottom.

  1. The problem
  2. Why it happened
  3. The fix
  4. A word of warning
  5. How to upgrade

The problem

A reader (Dave Woestenborghs) got in touch to say their SQL Server was filling up with *_wt_* databases. Each one was a copy of their main site database, and none of them had a worktree any more. The chats were archived, the folders were gone, and the databases were still there.

I checked mine. Same story. More of them than I'd like to admit.

Why it happened

Archiving a chat doesn't fire WorktreeRemove. I'd assumed it did. The Claude Code hooks docs say WorktreeRemove "Runs when Claude Code cleans up a worktree that your WorktreeCreate hook created", and then list when that happens:

  • you exit a worktree session and choose to remove the worktree when prompted (or it's unnamed and has no changed or untracked files)
  • you delete a background session that runs in the worktree
  • you ask Claude to exit and remove the worktree, and it uses the ExitWorktree tool
  • a claude remote-control session in worktree mode ends without crashing, or you stop claude remote-control while such sessions are running, and the worktree has no changes and no new commits

Archiving isn't on that list. So for anyone who works the way I do (finish the feature, merge the PR, archive the chat), the remove hook never ran. That leaves the SessionStart sweep as the only clean-up, which is fine, as long as the sweep works.

The sweep only looked at one prefix. It matched <current source db>_wt_*. If you ever renamed your main database (I did, part way through a project), every worktree database copied before the rename has the old prefix, and the sweep never looks at it again. Orphaned for good.

The fix

The sweep now works like this:

  • It compares against git worktree list. Any database with _wt_ in its name is a candidate. It's kept if its name ends in _wt_<slug> for a worktree git still lists, or if a listed worktree's appsettings.Local.json names it. A folder git no longer lists counts as gone.
  • Databases are tagged. Every worktree database the hook creates gets a SQL Server extended property, claude_worktree_repo, holding the main checkout's path. Live databases that are untagged but clearly ours get tagged at session start.
  • It only drops what belongs to this repo. A tagged database is dropped only if the tag names this repo. An untagged one is dropped only if its prefix is the current source database or one on a legacy list you pass in with -LegacySourceDbs. Anything else (another repo's tag, an unknown prefix, a tag it can't read) is skipped and logged. This matters if, like me, you reuse the script in more than one project against the same SQL Server. Without it, project B's sweep would happily drop project A's live databases.
  • There's a dry run. -DryRun logs what would be dropped, kept and skipped, and drops nothing. -Sweep runs only the sweep, so you can clean up from the main checkout by hand.
  • Hard stops. It never drops the main database or anything without _wt_ in the name, Remove-Db refuses those even if the decision logic gets it wrong, and if git worktree list comes back empty the sweep does nothing at all. Every drop, keep and skip is logged.

A word of warning

This one caught me out. A hook runs from the worktree you're in. If you edit worktree-db.ps1 inside a worktree, the edited version runs at that worktree's next session start, before you've reviewed anything, merged anything or even thought about it. If your change to the sweep is wrong, the databases are gone at the next session start.

So: change the script, run the dry run by hand, read the list, and only then start a new session. Dropped databases don't come back.

How to upgrade

1. Grab the updated script.

The full script is on the updated Gist. The original Gist from my last post still has the old version. If you've customised yours, these are the pieces to replace or add.

Two new parameters, two new switches, and an environment variable for the dry run:

param(
    [string]$LegacySourceDbs = 'none',
    [string]$RepoTagName = 'claude_worktree_repo',
    [string]$WebProject = 'MySite',
    [string]$LocalConfigName = 'appsettings.Local.json',
    [string]$ConnectionStringName = 'umbracoDbDSN',
    [string]$MediaRootSetting = 'Umbraco:CMS:Global:UmbracoMediaPhysicalRootPath',
    [string]$MediaFolder = 'wwwroot\media',
    [switch]$NoMediaSetting,
    [string]$Cwd,
    [string]$Remove,
    [switch]$Sweep,
    [switch]$DryRun
)
if ($NoMediaSetting) { $MediaRootSetting = '' }
if ($env:WT_SWEEP_DRYRUN -eq '1') { $DryRun = $true }

Get-SqlTarget returns one more thing, the repo id the tag is checked against:

RepoId     = [System.IO.Path]::GetFullPath($MainRoot).TrimEnd('\')

Reading and writing the tag:

function Get-RepoTag($Target, [string]$Name) {
    # Returns the tag value, '' when untagged, or $null when it can't be read
    # (no access, offline, single user): the caller must then leave it alone.
    $q = $Name.Replace(']', ']]'); $t = $RepoTagName.Replace("'", "''")
    try {
        $r = @(Invoke-Sql $Target "SELECT CAST(value AS nvarchar(4000)) FROM [$q].sys.extended_properties WHERE class = 0 AND name = N'$t';")
        if ($r.Count -eq 0) { return '' }
        return $r[0].Trim()
    } catch { return $null }
}

function Set-RepoTag($Target, [string]$Name) {
    $q = $Name.Replace(']', ']]'); $t = $RepoTagName.Replace("'", "''"); $v = $Target.RepoId.Replace("'", "''")
    Invoke-Sql $Target ("USE [$q]; IF EXISTS (SELECT 1 FROM sys.extended_properties WHERE class = 0 AND name = N'$t') " +
        "EXEC sys.sp_updateextendedproperty @name = N'$t', @value = N'$v'; " +
        "ELSE EXEC sys.sp_addextendedproperty @name = N'$t', @value = N'$v';") | Out-Null
}

The heart of it is one function that decides what happens to each candidate. It doesn't touch SQL Server, so it's easy to reason about:

function Get-SweepDecision {
    # Pure: decides one '_wt_' candidate. Returns Action = Drop | Keep | Skip,
    # Reason, and Tag = $true when a live, untagged, known database should be tagged.
    param([string]$Name, $Tag, [string]$RepoId, [string]$SourceDb, [string[]]$KnownSourceDbs, [string[]]$LiveSlugs, [hashtable]$NamedLive)
    $result = { param($a, $r, $t = $false) [pscustomobject]@{ Action = $a; Reason = $r; Tag = $t } }
    if ($Name -ieq $SourceDb) { return & $result 'Keep' 'main checkout database' }
    if ($Name.IndexOf('_wt_', [StringComparison]::OrdinalIgnoreCase) -lt 0) { return & $result 'Keep' "no '_wt_' in name" }
    if ($null -eq $Tag) { return & $result 'Skip' "repo tag unreadable" }

    $known = $KnownSourceDbs | Where-Object { $Name.StartsWith("$($_)_wt_", [StringComparison]::OrdinalIgnoreCase) } | Select-Object -First 1
    $live = $null
    if ($NamedLive -and $NamedLive.ContainsKey($Name)) { $live = "named in a listed worktree's local config" }
    else {
        $slug = $LiveSlugs | Where-Object { $Name.EndsWith("_wt_$_", [StringComparison]::OrdinalIgnoreCase) } | Select-Object -First 1
        if ($slug) { $live = "slug '$slug' matches a listed worktree" }
    }

    if ($Tag) {
        if ($Tag -ine $RepoId) { return & $result 'Skip' "tagged for another repo ($Tag)" }
        if ($live) { return & $result 'Keep' $live }
        return & $result 'Drop' 'tagged for this repo, no listed worktree'
    }
    if (-not $known) { return & $result 'Skip' "untagged, prefix not one of this repo's ($($KnownSourceDbs -join ', '))" }
    if ($live) { return & $result 'Keep' "$live; untagged" $true }
    return & $result 'Drop' "untagged, prefix '$known', no listed worktree"
}

Invoke-Sweep then lists every *_wt_* database, asks Get-SweepDecision about each one, and drops, keeps (tagging if asked) or skips it, or just logs it when -DryRun is on:

$candidates = @(Invoke-Sql $Target "SELECT name FROM sys.databases WHERE name LIKE '%\_wt\_%' ESCAPE '\' ORDER BY name;")

Remove-Db loosens its guard from "starts with the current prefix" to "isn't the main database and has _wt_ in it", because the old prefix check is exactly what stopped the old databases being dropped.

Last piece: in Invoke-SessionStart, tag the worktree's own database after it's created or found. A restored copy carries whatever tag the source had, so re-set it when it's missing or different.

2. Set your legacy prefixes.

If you've never renamed your main database, leave -LegacySourceDbs as none. If you have, list the old names in the hook command in settings.json:

"command": "powershell -NoProfile -ExecutionPolicy Bypass -File \"$env:CLAUDE_PROJECT_DIR\\.claude\\hooks\\worktree-db.ps1\" -LegacySourceDbs oldsite,oldersite"

If you run the script in more than one project against the same SQL Server, give each project only its own old names. Two projects claiming the same prefix is how you lose someone else's database.

3. Dry-run it.

From the main checkout, not a worktree:

powershell -NoProfile -ExecutionPolicy Bypass -File .claude\hooks\worktree-db.ps1 -Sweep -DryRun

You'll get a line per database, "would drop", "kept" or "skipped", each with a reason, and a total at the end. Read every line. Anything in the "would drop" list that you want to keep, stop here and work out why.

4. Clean up the orphans.

When the list looks right, run it for real:

powershell -NoProfile -ExecutionPolicy Bypass -File .claude\hooks\worktree-db.ps1 -Sweep

Then check for folders under .claude/worktrees/ that git worktree list doesn't show. Those are leftovers from archived chats too, and can be deleted by hand.

5. Commit it.

From then on, every session start does the same sweep. Archive away.

That's it. The reader who reported it saved me a fair bit of disk space, so thank you. If your server still has a few strays after this, the dry run will tell you why it kept them, which is more than the old version ever did.