Created
July 22, 2026 09:14
-
-
Save ZhiLin-Sam/552a6454704e31be0164cf9c6cbe70fd to your computer and use it in GitHub Desktop.
OpenCode session auto-cleanup — deletes sessions untouched for 7+ days
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # OpenCode session cleanup — deletes sessions untouched for 7+ days | |
| # Run with: pwsh -File cleanup-sessions.ps1 | |
| param([int]$RetentionDays = 7) | |
| $dbPath = "$env:USERPROFILE\.local\share\opencode\opencode.db" | |
| $sqlite3 = "C:\Tools\sqlite3.exe" | |
| $cutoffMs = [int64]((Get-Date).AddDays(-$RetentionDays) - (Get-Date "1970-01-01")).TotalMilliseconds | |
| # Safety: skip if opencode is running | |
| $oc = Get-Process -Name "opencode" -ErrorAction SilentlyContinue | |
| if ($oc) { | |
| Write-Host "[SKIP] opencode is running — close it first to avoid DB corruption" | |
| exit 1 | |
| } | |
| Write-Host "Deleting sessions older than $RetentionDays days (updated before $((Get-Date).AddDays(-$RetentionDays).ToString('yyyy-MM-dd')))..." | |
| $before = (Get-Item $dbPath).Length / 1MB | |
| $count = & $sqlite3 $dbPath "SELECT COUNT(*) FROM session WHERE time_updated < $cutoffMs;" | |
| Write-Host "Sessions to delete: $count" | |
| if ($count -eq 0) { | |
| Write-Host "Nothing to clean." | |
| exit 0 | |
| } | |
| & $sqlite3 $dbPath "PRAGMA foreign_keys = ON; DELETE FROM session WHERE time_updated < $cutoffMs;" | |
| Write-Host "Deleted. Vacuuming..." | |
| & $sqlite3 $dbPath "VACUUM;" | |
| $after = (Get-Item $dbPath).Length / 1MB | |
| Write-Host "DB: $([math]::Round($before,1)) MB → $([math]::Round($after,1)) MB (freed $([math]::Round($before-$after,1)) MB)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment