@jamiefutch/pi-backup 1.1.10 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/backup-pi.ps1 CHANGED
@@ -15,7 +15,8 @@ $ErrorActionPreference = 'Stop'
15
15
 
16
16
  # ─── Config ────────────────────────────────────────────────
17
17
  $PiRoot = if ($env:PI_ROOT) { $env:PI_ROOT } else { Join-Path $HOME '.pi' }
18
- $BackupRoot = if ($env:BACKUP_ROOT) { $env:BACKUP_ROOT } else { Join-Path $HOME 'projects\personal\pi-utils\backups' }
18
+ $BackupRoot = if ($env:BACKUP_ROOT) { $env:BACKUP_ROOT } else { Join-Path $HOME 'pi-backups' }
19
+ $LocalExtRoot = if ($env:LOCAL_EXT_ROOT) { $env:LOCAL_EXT_ROOT } else { Join-Path $HOME 'projects' }
19
20
  $Timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
20
21
  $ArchiveBase = "pi-backup-$Timestamp"
21
22
  $ArchiveDir = Join-Path $BackupRoot $ArchiveBase
@@ -28,14 +29,70 @@ function OK { Write-Host "[OK] $args" -ForegroundColor Green }
28
29
  function Warn { Write-Host "[WARN] $args" -ForegroundColor Yellow }
29
30
  function Err { Write-Host "[ERR] $args" -ForegroundColor Red; exit 1 }
30
31
 
32
+ # ─── Manifest ──────────────────────────────────────────────
33
+ # What gets backed up / restored is defined once, in backup-manifest.txt (shared with the bash scripts).
34
+ $ManifestFile = Join-Path $PSScriptRoot 'backup-manifest.txt'
35
+ if (-not (Test-Path -LiteralPath $ManifestFile)) {
36
+ Write-Host "[ERR] backup-manifest.txt not found next to this script" -ForegroundColor Red
37
+ exit 1
38
+ }
39
+
40
+ function Read-Manifest([string]$path) {
41
+ foreach ($line in [System.IO.File]::ReadAllLines($path)) {
42
+ $l = $line.TrimEnd("`r")
43
+ if ($l -eq '' -or $l.StartsWith('#')) { continue }
44
+ $p = $l.Split('|')
45
+ [pscustomobject]@{
46
+ Kind = $p[0]
47
+ A = if ($p.Count -gt 1) { $p[1] } else { '' }
48
+ B = if ($p.Count -gt 2) { $p[2] } else { '' }
49
+ C = if ($p.Count -gt 3) { $p[3] } else { '' }
50
+ }
51
+ }
52
+ }
53
+
54
+ # Manifest paths use "/"; join them under a root with the platform separator.
55
+ function P([string]$root, [string]$rel) {
56
+ Join-Path $root ($rel.Replace('/', [System.IO.Path]::DirectorySeparatorChar))
57
+ }
58
+
59
+
60
+ # Restrict a path to the current user on Unix (no-op on Windows, where ACLs apply).
61
+ function Set-PrivateMode([string]$path, [bool]$isDir = $false) {
62
+ if ($IsWindows -or $env:OS -eq 'Windows_NT') { return }
63
+ try {
64
+ $mode = if ($isDir) { 'UserRead,UserWrite,UserExecute' } else { 'UserRead,UserWrite' }
65
+ [System.IO.File]::SetUnixFileMode($path, [System.IO.UnixFileMode]$mode)
66
+ } catch { Warn " could not restrict permissions on ${path}: $($_.Exception.Message)" }
67
+ }
68
+
69
+ function Get-RelativeLabel([string]$path) {
70
+ if ($path.StartsWith($ArchiveDir)) { return $path.Substring($ArchiveDir.Length).TrimStart('\','/').Replace('\','/') }
71
+ return [System.IO.Path]::GetFileName($path)
72
+ }
73
+
74
+ # auth.json holds credentials: optionally excluded, always private, always flagged.
75
+ function Backup-Auth([string]$src, [string]$dst) {
76
+ if ($env:PI_BACKUP_EXCLUDE_AUTH -eq '1') {
77
+ Warn " auth.json - excluded (PI_BACKUP_EXCLUDE_AUTH=1)"
78
+ return
79
+ }
80
+ Copy-IfExists $src $dst
81
+ if (Test-Path -LiteralPath $dst) {
82
+ Set-PrivateMode $dst
83
+ Warn " auth.json holds your API credentials and is included in this backup."
84
+ Warn " Keep the backup private; set PI_BACKUP_EXCLUDE_AUTH=1 to leave it out."
85
+ }
86
+ }
87
+
31
88
  function Copy-IfExists([string]$src, [string]$dst) {
32
89
  if (Test-Path -LiteralPath $src) {
33
90
  $dstDir = Split-Path $dst -Parent
34
91
  if (!(Test-Path -LiteralPath $dstDir)) { New-Item -ItemType Directory -Path $dstDir -Force | Out-Null }
35
92
  Copy-Item -LiteralPath $src -Destination $dst -Recurse -Force
36
- OK " $([System.IO.Path]::GetFileName($src))"
93
+ OK " $(Get-RelativeLabel $dst)"
37
94
  } else {
38
- Warn " $([System.IO.Path]::GetFileName($src)) - not found, skipping"
95
+ Warn " $(Get-RelativeLabel $dst) - not found, skipping"
39
96
  }
40
97
  }
41
98
 
@@ -59,20 +116,29 @@ function Copy-Tree([string]$src, [string]$dst, [string[]]$excludeDirs = @(), [st
59
116
  $robocopyArgs += @('/NFL','/NDL','/NJH','/NJS')
60
117
  & robocopy @robocopyArgs | Out-Null
61
118
  } else {
62
- # Fallback: manual recursive copy with exclusions
63
- Get-ChildItem -LiteralPath $src | ForEach-Object {
119
+ # Fallback without robocopy: recurse so existing destination dirs are merged, not nested.
120
+ Get-ChildItem -LiteralPath $src -Force | ForEach-Object {
64
121
  $item = $_
65
122
  $skip = $false
66
123
  if ($item.PSIsContainer -and $item.Name -in $excludeDirs) { $skip = $true }
67
124
  if (-not $item.PSIsContainer -and ($excludeFiles | Where-Object { $item.Name -like $_ })) { $skip = $true }
68
125
  if (-not $skip) {
69
- Copy-Item -LiteralPath $item.FullName -Destination (Join-Path $dst $item.Name) -Recurse -Force
126
+ $target = Join-Path $dst $item.Name
127
+ if ($item.PSIsContainer) { Copy-Tree $item.FullName $target $excludeDirs $excludeFiles }
128
+ else { Copy-Item -LiteralPath $item.FullName -Destination $target -Force }
70
129
  }
71
130
  }
72
131
  }
73
132
  }
74
133
 
134
+ # A half-built staging dir (or partial archive) is removed if the script fails.
135
+ # A successful run, or a failed compression (staging is intact), keeps it.
136
+ $Completed = $false
137
+ $KeepStagingOnFail = $false
138
+ $archivePath = $null
139
+ try {
75
140
  New-Item -ItemType Directory -Path $ArchiveDir -Force | Out-Null
141
+ Set-PrivateMode $ArchiveDir $true
76
142
 
77
143
  Write-Host ""
78
144
  Log "================================================================"
@@ -82,109 +148,81 @@ Log "Source: $PiRoot"
82
148
  Log "Destination: $ArchiveDir"
83
149
  Write-Host ""
84
150
 
85
- # ── 1. Core Config Files ──────────────────────────────────
86
- Log "1/8 Core configuration files..."
87
151
  $agentDir = Join-Path $PiRoot 'agent'
88
- Copy-IfExists (Join-Path $agentDir 'settings.json') (Join-Path $ArchiveDir 'settings.json')
89
- Copy-IfExists (Join-Path $agentDir 'auth.json') (Join-Path $ArchiveDir 'auth.json')
90
- Copy-IfExists (Join-Path $agentDir 'models.json') (Join-Path $ArchiveDir 'models.json')
91
- Copy-IfExists (Join-Path $agentDir 'trust.json') (Join-Path $ArchiveDir 'trust.json')
92
- Copy-IfExists (Join-Path $agentDir 'keybindings.json') (Join-Path $ArchiveDir 'keybindings.json')
93
- Copy-IfExists (Join-Path $agentDir 'pix.json') (Join-Path $ArchiveDir 'pix.json')
94
- Copy-IfExists (Join-Path $agentDir 'optimizer.json') (Join-Path $ArchiveDir 'optimizer.json')
95
- Copy-IfExists (Join-Path $agentDir 'lmstudio.json.bak') (Join-Path $ArchiveDir 'lmstudio.json.bak')
96
- Copy-IfExists (Join-Path $agentDir 'hermes-memory-config.json') (Join-Path $ArchiveDir 'hermes-memory-config.json')
97
- Copy-IfExists (Join-Path $agentDir 'pi.code-workspace') (Join-Path $ArchiveDir 'pi.code-workspace')
98
-
99
- # ── 2. Extension Configs ──────────────────────────────────
100
- Log "2/8 Extension configurations..."
101
- Copy-IfExists (Join-Path $agentDir 'pi-hermes-memory-cleanup\scoped-memory.json') (Join-Path $ArchiveDir 'pi-hermes-memory-cleanup\scoped-memory.json')
102
- Copy-IfExists (Join-Path $agentDir 'loop-police.json') (Join-Path $ArchiveDir 'loop-police.json')
103
- Copy-IfExists (Join-Path $agentDir 'pi-rtk\config.json') (Join-Path $ArchiveDir 'pi-rtk\config.json')
104
- Copy-IfExists (Join-Path $agentDir 'context-mode\config.json') (Join-Path $ArchiveDir 'context-mode\config.json')
105
- Copy-IfExists (Join-Path $agentDir 'pi-timeout\config.json') (Join-Path $ArchiveDir 'pi-timeout\config.json')
106
- Copy-IfExists (Join-Path $agentDir 'pi-context-viewer\config.json') (Join-Path $ArchiveDir 'pi-context-viewer\config.json')
107
- Copy-IfExists (Join-Path $agentDir 'pix-optimizer\config.json') (Join-Path $ArchiveDir 'pix-optimizer\config.json')
108
- Copy-IfExists (Join-Path $agentDir 'pi-nvidia-nim\config.json') (Join-Path $ArchiveDir 'pi-nvidia-nim\config.json')
109
-
110
- # ── 3. Global Skills ──────────────────────────────────────
111
- Log "3/8 Global skills..."
112
- Copy-DirIfExists (Join-Path $agentDir 'skills') (Join-Path $ArchiveDir 'skills')
113
-
114
- # ── 4. Project Skills & Memory ────────────────────────────
115
- Log "4/8 Project skills & memory..."
116
- $projMem = Join-Path $agentDir 'projects-memory'
117
- if (Test-Path -LiteralPath $projMem) {
118
- $projDst = Join-Path $ArchiveDir 'projects-memory'
119
- Copy-DirIfExists $projMem $projDst
120
- $count = @(Get-ChildItem -LiteralPath $projDst -Directory -ErrorAction SilentlyContinue).Count
121
- OK " projects-memory/ ($count projects)"
122
- } else {
123
- Warn " projects-memory/ - not found"
124
- }
125
-
126
- # ── 5. Local Extensions (source code only, no node_modules) ─
127
- Log "5/8 Local extension source code..."
128
- $localExts = @('pi-timeout', 'pi-chunk', 'pi-hermes-memory-cleanup', 'pi-context-docs')
129
- foreach ($ext in $localExts) {
130
- $src = Join-Path $HOME "projects\personal\$ext"
131
- if (Test-Path -LiteralPath $src) {
132
- $dst = Join-Path $ArchiveDir "local-extensions\$ext"
133
- $extDstDir = Join-Path $ArchiveDir 'local-extensions'
134
- if (!(Test-Path -LiteralPath $extDstDir)) { New-Item -ItemType Directory -Path $extDstDir -Force | Out-Null }
135
- # Copy source, exclude node_modules, dist, build, .git, coverage, logs
136
- Copy-Tree $src $dst -excludeDirs @('node_modules','dist','build','coverage','.git') -excludeFiles @('*.log')
137
- OK " $ext/ (source only)"
138
- } else {
139
- Warn " $ext - not found at ~/projects/personal/$ext"
140
- }
141
- }
142
-
143
- # ── 6. npm Extension Manifests (package.json + lock) ─────
144
- Log "6/8 npm extension manifests..."
145
- $npmDir = Join-Path $agentDir 'npm'
146
- if (Test-Path -LiteralPath $npmDir) {
147
- # Only copy package.json and lockfiles, not node_modules
148
- $manifests = Get-ChildItem -LiteralPath $npmDir -Recurse -Depth 3 -Include @('package.json','package-lock.json','npm-shrinkwrap.json','pnpm-lock.yaml') -ErrorAction SilentlyContinue
149
- foreach ($m in $manifests) {
150
- $rel = $m.FullName.Substring($npmDir.Length).TrimStart('\')
151
- $dstDir = Join-Path $ArchiveDir "npm-manifests\$($rel | Split-Path -Parent)"
152
- if (!(Test-Path -LiteralPath $dstDir)) { New-Item -ItemType Directory -Path $dstDir -Force | Out-Null }
153
- Copy-Item -LiteralPath $m.FullName -Destination (Join-Path $dstDir $m.Name) -Force
154
- }
155
- OK " npm manifests (package.json, lockfiles)"
156
- } else {
157
- Warn " npm/ - not found"
158
- }
159
-
160
- # ── 7. Hermes Memory (active files only, not sessions DB) ─
161
- Log "7/8 Hermes memory (active files)..."
162
- $hermes = Join-Path $agentDir 'pi-hermes-memory'
163
- if (Test-Path -LiteralPath $hermes) {
164
- $hermesDst = Join-Path $ArchiveDir 'pi-hermes-memory'
165
- New-Item -ItemType Directory -Path $hermesDst -Force | Out-Null
166
- foreach ($f in @('MEMORY.md','USER.md','failures.md','retired-failures.md','retired-memory.md')) {
167
- Copy-IfExists (Join-Path $hermes $f) (Join-Path $hermesDst $f)
168
- }
169
- } else {
170
- Warn " pi-hermes-memory/ - not found"
171
- }
172
-
173
- # ── 8. Recent hermes-cleanup Backups (last 5) ─────────────
174
- Log "8/8 Recent hermes-cleanup backups (last 5)..."
175
- $cleanup = Join-Path $agentDir 'hermes-cleanup'
176
- if (Test-Path -LiteralPath $cleanup) {
177
- $recent = Get-ChildItem -LiteralPath $cleanup -Directory | Where-Object { $_.Name -match '^\d{4}' } | Sort-Object Name -Descending | Select-Object -First 5
178
- foreach ($d in $recent) {
179
- Copy-DirIfExists $d.FullName (Join-Path $ArchiveDir "hermes-cleanup\$($d.Name)")
152
+ $entries = @(Read-Manifest $ManifestFile)
153
+ $total = @($entries | Where-Object { $_.Kind -eq 'section' }).Count
154
+ $step = 0
155
+ foreach ($e in $entries) {
156
+ switch ($e.Kind) {
157
+ 'section' { $step++; Log "$step/$total $($e.A)..." }
158
+ 'file' {
159
+ if ($e.B -eq 'auth.json') { Backup-Auth (P $PiRoot $e.A) (P $ArchiveDir $e.B) }
160
+ else { Copy-IfExists (P $PiRoot $e.A) (P $ArchiveDir $e.B) }
161
+ }
162
+ 'dir' { Copy-DirIfExists (P $PiRoot $e.A) (P $ArchiveDir $e.B) }
163
+ 'dir-each' {
164
+ $src = P $PiRoot $e.A
165
+ if (Test-Path -LiteralPath $src -PathType Container) {
166
+ $dst = P $ArchiveDir $e.B
167
+ New-Item -ItemType Directory -Path $dst -Force | Out-Null
168
+ foreach ($sub in Get-ChildItem -LiteralPath $src -Directory) {
169
+ Copy-DirIfExists $sub.FullName (Join-Path $dst $sub.Name)
170
+ }
171
+ $count = @(Get-ChildItem -LiteralPath $dst -Directory -ErrorAction SilentlyContinue).Count
172
+ OK " $($e.B)/ ($count projects)"
173
+ } else {
174
+ Warn " $($e.B)/ - not found"
175
+ }
176
+ }
177
+ 'local-ext' {
178
+ $src = Join-Path $LocalExtRoot $e.A
179
+ if (Test-Path -LiteralPath $src) {
180
+ $dst = P $ArchiveDir "local-extensions/$($e.A)"
181
+ Copy-Tree $src $dst -excludeDirs @('node_modules','dist','build','coverage','.git') -excludeFiles @('*.log')
182
+ OK " $($e.A)/ (source only)"
183
+ } else {
184
+ Warn " $($e.A) - not found at $LocalExtRoot/$($e.A)"
185
+ }
186
+ }
187
+ 'npm' {
188
+ $src = P $PiRoot $e.A
189
+ if (Test-Path -LiteralPath $src -PathType Container) {
190
+ # Only package.json and lockfiles, never node_modules (depth matches the bash script)
191
+ $names = @('package.json','package-lock.json','npm-shrinkwrap.json','pnpm-lock.yaml')
192
+ $found = Get-ChildItem -LiteralPath $src -Recurse -Depth 2 -File -ErrorAction SilentlyContinue |
193
+ Where-Object { $names -contains $_.Name -and $_.FullName -notmatch '[\\/]node_modules[\\/]' }
194
+ foreach ($m in $found) {
195
+ $rel = $m.FullName.Substring($src.Length).TrimStart('\','/')
196
+ $target = P $ArchiveDir "$($e.B)/$($rel.Replace('\','/'))"
197
+ $targetDir = Split-Path $target -Parent
198
+ if (!(Test-Path -LiteralPath $targetDir)) { New-Item -ItemType Directory -Path $targetDir -Force | Out-Null }
199
+ Copy-Item -LiteralPath $m.FullName -Destination $target -Force
200
+ }
201
+ OK " npm manifests (package.json, lockfiles)"
202
+ } else {
203
+ Warn " npm/ - not found"
204
+ }
205
+ }
206
+ 'recent' {
207
+ $src = P $PiRoot $e.A
208
+ if (Test-Path -LiteralPath $src -PathType Container) {
209
+ $dst = P $ArchiveDir $e.B
210
+ New-Item -ItemType Directory -Path $dst -Force | Out-Null
211
+ $n = if ($e.C) { [int]$e.C } else { 5 }
212
+ $recent = Get-ChildItem -LiteralPath $src -Directory | Where-Object { $_.Name -like '20*' } | Sort-Object Name -Descending | Select-Object -First $n
213
+ foreach ($d in $recent) { Copy-DirIfExists $d.FullName (Join-Path $dst $d.Name) }
214
+ } else {
215
+ Warn " $($e.A)/ - not found"
216
+ }
217
+ }
218
+ default { Warn "Unknown manifest entry type: $($e.Kind)" }
180
219
  }
181
- } else {
182
- Warn " hermes-cleanup/ - not found"
183
220
  }
184
221
 
185
222
  # ── Manifest ──────────────────────────────────────────────
186
223
  Log "Creating manifest..."
187
- $piVersion = (& pi --version 2>$null) -join ''
224
+ $piVersion = ''
225
+ try { $piVersion = (& pi --version 2>$null) -join '' } catch { $piVersion = '' }
188
226
  if (-not $piVersion) { $piVersion = 'unknown' }
189
227
  $manifest = @"
190
228
  Pi Complete Backup Manifest
@@ -201,8 +239,7 @@ $relFiles = Get-ChildItem -LiteralPath $ArchiveDir -Recurse -File | ForEach-Obje
201
239
  $manifest += ($relFiles -join "`n") + "`n"
202
240
  Set-Content -LiteralPath (Join-Path $ArchiveDir 'MANIFEST.txt') -Value $manifest -Encoding UTF8
203
241
 
204
- # ── 9. Compress ───────────────────────────────────────────
205
- $archivePath = $null
242
+ # ── 9. Compress (external backups only) ───────────────────
206
243
  if ($KeepUncompressed) {
207
244
  Log "9/9 Skipping compression for internal backup"
208
245
  } else {
@@ -210,23 +247,30 @@ if ($KeepUncompressed) {
210
247
  $archivePath = Join-Path $BackupRoot ($ArchiveBase + ".$ArchiveExtension")
211
248
  try {
212
249
  if ($SevenZip) {
213
- & $SevenZip.Source a -t7z -mx=9 $archivePath $ArchiveDir | Out-Null
214
- if ($LASTEXITCODE -ne 0) { throw "7zip exited with code $LASTEXITCODE" }
250
+ # Run from $BackupRoot with relative names so the archive has a single
251
+ # top-level pi-backup-*/ entry (same layout as the bash script).
252
+ Push-Location -LiteralPath $BackupRoot
253
+ try {
254
+ $sevenOut = & $SevenZip.Source a -t7z -mx=9 "$ArchiveBase.7z" $ArchiveBase 2>&1
255
+ $sevenRc = $LASTEXITCODE
256
+ } finally {
257
+ Pop-Location
258
+ }
259
+ if ($sevenRc -ne 0) { throw "7zip exited with code ${sevenRc}: $(($sevenOut | Out-String).Trim())" }
215
260
  } else {
216
261
  Compress-Archive -LiteralPath $ArchiveDir -DestinationPath $archivePath -CompressionLevel Optimal -Force
217
262
  }
263
+ Set-PrivateMode $archivePath
218
264
  OK " $archivePath"
219
265
  } catch {
220
- Warn " Compress-Archive failed: $_.Exception.Message"
266
+ Warn " Compression ($ArchiveExtension) failed: $($_.Exception.Message)"
221
267
  Warn " Keeping uncompressed staging dir: $ArchiveDir"
268
+ if (Test-Path -LiteralPath $archivePath) { Remove-Item -LiteralPath $archivePath -Force -ErrorAction SilentlyContinue }
222
269
  $archivePath = $null
270
+ $KeepStagingOnFail = $true
271
+ exit 1
223
272
  }
224
- }
225
-
226
- # ── 10. Clean up staging dir (unless told to keep it) ─────
227
- if ($KeepUncompressed) {
228
- Log "Keeping uncompressed staging dir: $ArchiveDir"
229
- } elseif ($archivePath) {
273
+ # ── 10. Clean up staging dir ──────────────────────────
230
274
  Remove-Item -LiteralPath $ArchiveDir -Recurse -Force
231
275
  }
232
276
 
@@ -234,12 +278,22 @@ if ($KeepUncompressed) {
234
278
  Write-Host ""
235
279
  Log "================================================================"
236
280
  OK "Backup complete!"
237
- if ($archivePath) {
281
+ if ($KeepUncompressed) {
282
+ $result = $ArchiveDir
283
+ Log "Staging: $ArchiveDir"
284
+ } else {
285
+ $result = $archivePath
238
286
  Log "Archive: $archivePath"
239
287
  Log "Size: $([math]::Round((Get-Item -LiteralPath $archivePath).Length / 1MB, 1)) MB"
240
288
  }
241
- if ($KeepUncompressed) { Log "Staging: $ArchiveDir" }
242
289
  Write-Host ""
243
290
  Log "To restore after reinstall:"
244
- Log " ~/projects/personal/pi-backup/restore-pi.ps1 $archivePath"
291
+ Log " .\restore-pi.ps1 $result"
245
292
  Write-Host ""
293
+ $Completed = $true
294
+ } finally {
295
+ if (-not $Completed -and -not $KeepStagingOnFail) {
296
+ if (Test-Path -LiteralPath $ArchiveDir) { Remove-Item -LiteralPath $ArchiveDir -Recurse -Force -ErrorAction SilentlyContinue }
297
+ if ($archivePath -and (Test-Path -LiteralPath $archivePath)) { Remove-Item -LiteralPath $archivePath -Force -ErrorAction SilentlyContinue }
298
+ }
299
+ }