@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/restore-pi.ps1 CHANGED
@@ -4,8 +4,8 @@
4
4
  #
5
5
  # Usage:
6
6
  # .\restore-pi.ps1 <backup-directory-or-archive>
7
- # .\restore-pi.ps1 ~\projects\personal\pi-utils\backups\pi-backup-20260811-143000
8
- # .\restore-pi.ps1 ~\projects\personal\pi-utils\backups\pi-backup-20260811-143000.zip
7
+ # .\restore-pi.ps1 ~\pi-backups\pi-backup-20260811-143000
8
+ # .\restore-pi.ps1 ~\pi-backups\pi-backup-20260811-143000.zip
9
9
  # =============================================================
10
10
  [CmdletBinding()]
11
11
  param(
@@ -17,12 +17,41 @@ $ErrorActionPreference = 'Stop'
17
17
 
18
18
  # ─── Config ────────────────────────────────────────────────
19
19
  $PiRoot = if ($env:PI_ROOT) { $env:PI_ROOT } else { Join-Path $HOME '.pi' }
20
+ $LocalExtRoot = if ($env:LOCAL_EXT_ROOT) { $env:LOCAL_EXT_ROOT } else { Join-Path $HOME 'projects' }
20
21
 
21
22
  function Log { Write-Host "[INFO] $args" -ForegroundColor Cyan }
22
23
  function OK { Write-Host "[OK] $args" -ForegroundColor Green }
23
24
  function Warn { Write-Host "[WARN] $args" -ForegroundColor Yellow }
24
25
  function Err { Write-Host "[ERR] $args" -ForegroundColor Red }
25
26
 
27
+ # ─── Manifest ──────────────────────────────────────────────
28
+ # What gets backed up / restored is defined once, in backup-manifest.txt (shared with the bash scripts).
29
+ $ManifestFile = Join-Path $PSScriptRoot 'backup-manifest.txt'
30
+ if (-not (Test-Path -LiteralPath $ManifestFile)) {
31
+ Write-Host "[ERR] backup-manifest.txt not found next to this script" -ForegroundColor Red
32
+ exit 1
33
+ }
34
+
35
+ function Read-Manifest([string]$path) {
36
+ foreach ($line in [System.IO.File]::ReadAllLines($path)) {
37
+ $l = $line.TrimEnd("`r")
38
+ if ($l -eq '' -or $l.StartsWith('#')) { continue }
39
+ $p = $l.Split('|')
40
+ [pscustomobject]@{
41
+ Kind = $p[0]
42
+ A = if ($p.Count -gt 1) { $p[1] } else { '' }
43
+ B = if ($p.Count -gt 2) { $p[2] } else { '' }
44
+ C = if ($p.Count -gt 3) { $p[3] } else { '' }
45
+ }
46
+ }
47
+ }
48
+
49
+ # Manifest paths use "/"; join them under a root with the platform separator.
50
+ function P([string]$root, [string]$rel) {
51
+ Join-Path $root ($rel.Replace('/', [System.IO.Path]::DirectorySeparatorChar))
52
+ }
53
+
54
+
26
55
  function Show-Usage {
27
56
  Write-Host @"
28
57
  Usage: $($MyInvocation.MyCommand.Name) <backup-directory-or-archive>
@@ -30,8 +59,8 @@ Usage: $($MyInvocation.MyCommand.Name) <backup-directory-or-archive>
30
59
  Restores a Pi backup created by backup-pi.ps1
31
60
 
32
61
  Examples:
33
- .\$($MyInvocation.MyCommand.Name) ~\projects\personal\pi-utils\backups\pi-backup-20260811-143000
34
- .\$($MyInvocation.MyCommand.Name) ~\projects\personal\pi-utils\backups\pi-backup-20260811-143000.zip
62
+ .\$($MyInvocation.MyCommand.Name) ~\pi-backups\pi-backup-20260811-143000
63
+ .\$($MyInvocation.MyCommand.Name) ~\pi-backups\pi-backup-20260811-143000.zip
35
64
 
36
65
  Accepts either an uncompressed backup directory or a compressed zip/7z archive
37
66
  (as produced by backup-pi.ps1).
@@ -45,8 +74,30 @@ Prerequisites:
45
74
 
46
75
  if (-not $BackupArg) { Show-Usage }
47
76
 
48
- # ─── Archive handling ─────────────────────────────────────
77
+ function Test-PiRunning {
78
+ # Best-effort only: process names are unreliable, so callers warn rather than block.
79
+ if ($IsWindows -or $env:OS -eq 'Windows_NT') {
80
+ if (Get-Process -Name 'pi' -ErrorAction SilentlyContinue) { return $true }
81
+ try {
82
+ $procs = Get-CimInstance Win32_Process -Filter "Name='node.exe' OR Name='bun.exe'" -ErrorAction Stop
83
+ if ($procs | Where-Object { $_.CommandLine -like '*pi-coding-agent*' }) { return $true }
84
+ } catch {}
85
+ return $false
86
+ }
87
+ if (Get-Command pgrep -ErrorAction SilentlyContinue) {
88
+ & pgrep -x pi *> $null
89
+ if ($LASTEXITCODE -eq 0) { return $true }
90
+ & pgrep -f 'pi-coding-agent' *> $null
91
+ return ($LASTEXITCODE -eq 0)
92
+ }
93
+ return $false
94
+ }
95
+
96
+ # The extraction dir is removed in `finally`, so every exit path (abort, error,
97
+ # success) cleans up. `exit` inside `try` still runs `finally`.
49
98
  $STAGE = $null
99
+ try {
100
+ # ─── Archive handling ─────────────────────────────────────
50
101
  $BackupDir = $null
51
102
  $SevenZip = @('7zz', '7z', '7za') | ForEach-Object { Get-Command $_ -ErrorAction SilentlyContinue } | Select-Object -First 1
52
103
 
@@ -64,7 +115,7 @@ if (Test-Path -LiteralPath $BackupArg -PathType Container) {
64
115
  Err "7zip is required to extract .7z backups. Install 7-Zip and ensure it is on PATH."
65
116
  exit 1
66
117
  }
67
- $STAGE = Join-Path $env:TEMP ("pi-restore-" + [guid]::NewGuid().ToString('N'))
118
+ $STAGE = Join-Path ([System.IO.Path]::GetTempPath()) ("pi-restore-" + [guid]::NewGuid().ToString('N'))
68
119
  New-Item -ItemType Directory -Path $STAGE -Force | Out-Null
69
120
  Log "Extracting archive: $BackupArg"
70
121
  try {
@@ -76,12 +127,11 @@ if (Test-Path -LiteralPath $BackupArg -PathType Container) {
76
127
  }
77
128
  } catch {
78
129
  Err "Failed to extract archive: $($_.Exception.Message)"
79
- Remove-Item -LiteralPath $STAGE -Recurse -Force -ErrorAction SilentlyContinue
80
130
  exit 1
81
131
  }
82
132
  # The archive holds one top-level pi-backup-* dir
83
133
  $top = Get-ChildItem -LiteralPath $STAGE -Directory | Select-Object -First 1
84
- if (-not $top) { Err "No backup directory found inside archive."; Remove-Item $STAGE -Recurse -Force; exit 1 }
134
+ if (-not $top) { Err "No backup directory found inside archive."; exit 1 }
85
135
  $BackupDir = $top.FullName
86
136
  Log "Extracted to: $BackupDir"
87
137
  } else {
@@ -103,19 +153,38 @@ Warn "This will OVERWRITE all current Pi configuration."
103
153
  Warn "Backup source: $BackupDir"
104
154
  Warn "Target: $PiRoot"
105
155
  Warn "Pi must NOT be running."
156
+ if (Test-PiRunning) {
157
+ Warn "A Pi process appears to be running. Exit Pi first: files restored under a"
158
+ Warn "running Pi can be overwritten or corrupted when it exits."
159
+ }
106
160
  Write-Host ""
107
- $confirm = Read-Host "Continue? [y/N] "
108
- if ($confirm -notmatch '^[Yy]$') { Log "Aborted."; if ($STAGE) { Remove-Item $STAGE -Recurse -Force }; exit 0 }
161
+ if ($env:PI_BACKUP_ASSUME_YES -eq '1') {
162
+ Log "PI_BACKUP_ASSUME_YES=1 set; skipping confirmation."
163
+ } else {
164
+ $confirm = $null
165
+ try { $confirm = Read-Host "Continue? [y/N] " } catch { $confirm = $null }
166
+ if ($null -eq $confirm) {
167
+ Err "Cannot read a confirmation (stdin is not interactive)."
168
+ Err "Run this in a terminal, or set PI_BACKUP_ASSUME_YES=1 to skip the prompt."
169
+ exit 1
170
+ }
171
+ if ($confirm -notmatch '^[Yy]$') { Log "Aborted."; exit 0 }
172
+ }
109
173
 
110
174
  # ─── Helpers ──────────────────────────────────────────────
175
+ function Get-RelativeLabel([string]$path) {
176
+ if ($BackupDir -and $path.StartsWith($BackupDir)) { return $path.Substring($BackupDir.Length).TrimStart('\','/').Replace('\','/') }
177
+ return [System.IO.Path]::GetFileName($path)
178
+ }
179
+
111
180
  function Restore-File([string]$src, [string]$dst) {
112
181
  if (Test-Path -LiteralPath $src -PathType Leaf) {
113
182
  $dstDir = Split-Path $dst -Parent
114
183
  if (!(Test-Path -LiteralPath $dstDir)) { New-Item -ItemType Directory -Path $dstDir -Force | Out-Null }
115
184
  Copy-Item -LiteralPath $src -Destination $dst -Force
116
- OK " $([System.IO.Path]::GetFileName($src))"
185
+ OK " $(Get-RelativeLabel $src)"
117
186
  } else {
118
- Warn " $([System.IO.Path]::GetFileName($src)) - not in backup, skipping"
187
+ Warn " $(Get-RelativeLabel $src) - not in backup, skipping"
119
188
  }
120
189
  }
121
190
 
@@ -140,12 +209,17 @@ function Copy-Tree([string]$src, [string]$dst, [string[]]$excludeDirs = @(), [st
140
209
  $robocopyArgs += @('/NFL','/NDL','/NJH','/NJS')
141
210
  & robocopy @robocopyArgs | Out-Null
142
211
  } else {
143
- Get-ChildItem -LiteralPath $src | ForEach-Object {
212
+ # Fallback without robocopy: recurse so existing destination dirs are merged,
213
+ # not nested (Copy-Item of a dir onto an existing dir would create dst/dir/dir).
214
+ Get-ChildItem -LiteralPath $src -Force | ForEach-Object {
215
+ $item = $_
144
216
  $skip = $false
145
- if ($_.PSIsContainer -and $_.Name -in $excludeDirs) { $skip = $true }
146
- if (-not $_.PSIsContainer -and $_.Name -like $excludeFiles) { $skip = $true }
217
+ if ($item.PSIsContainer -and $item.Name -in $excludeDirs) { $skip = $true }
218
+ if (-not $item.PSIsContainer -and ($excludeFiles | Where-Object { $item.Name -like $_ })) { $skip = $true }
147
219
  if (-not $skip) {
148
- Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $dst $_.Name) -Recurse -Force
220
+ $target = Join-Path $dst $item.Name
221
+ if ($item.PSIsContainer) { Copy-Tree $item.FullName $target $excludeDirs $excludeFiles }
222
+ else { Copy-Item -LiteralPath $item.FullName -Destination $target -Force }
149
223
  }
150
224
  }
151
225
  }
@@ -158,93 +232,58 @@ Log " Restoring Pi from backup"
158
232
  Log "================================================================"
159
233
  Write-Host ""
160
234
 
161
- # ── 1. Core Config Files ──────────────────────────────────
162
- Log "1/8 Core configuration files..."
163
235
  $agentDir = Join-Path $PiRoot 'agent'
164
- Restore-File (Join-Path $BackupDir 'settings.json') (Join-Path $agentDir 'settings.json')
165
- Restore-File (Join-Path $BackupDir 'auth.json') (Join-Path $agentDir 'auth.json')
166
- Restore-File (Join-Path $BackupDir 'models.json') (Join-Path $agentDir 'models.json')
167
- Restore-File (Join-Path $BackupDir 'trust.json') (Join-Path $agentDir 'trust.json')
168
- Restore-File (Join-Path $BackupDir 'keybindings.json') (Join-Path $agentDir 'keybindings.json')
169
- Restore-File (Join-Path $BackupDir 'pix.json') (Join-Path $agentDir 'pix.json')
170
- Restore-File (Join-Path $BackupDir 'optimizer.json') (Join-Path $agentDir 'optimizer.json')
171
- Restore-File (Join-Path $BackupDir 'lmstudio.json.bak') (Join-Path $agentDir 'lmstudio.json.bak')
172
- Restore-File (Join-Path $BackupDir 'hermes-memory-config.json') (Join-Path $agentDir 'hermes-memory-config.json')
173
- Restore-File (Join-Path $BackupDir 'pi.code-workspace') (Join-Path $agentDir 'pi.code-workspace')
174
-
175
- # ── 2. Extension Configs ──────────────────────────────────
176
- Log "2/8 Extension configurations..."
177
- Restore-File (Join-Path $BackupDir 'pi-hermes-memory-cleanup\scoped-memory.json') (Join-Path $agentDir 'pi-hermes-memory-cleanup\scoped-memory.json')
178
- Restore-File (Join-Path $BackupDir 'loop-police.json') (Join-Path $agentDir 'loop-police.json')
179
- Restore-File (Join-Path $BackupDir 'pi-rtk\config.json') (Join-Path $agentDir 'pi-rtk\config.json')
180
- Restore-File (Join-Path $BackupDir 'context-mode\config.json') (Join-Path $agentDir 'context-mode\config.json')
181
- Restore-File (Join-Path $BackupDir 'pi-timeout\config.json') (Join-Path $agentDir 'pi-timeout\config.json')
182
- Restore-File (Join-Path $BackupDir 'pi-context-viewer\config.json') (Join-Path $agentDir 'pi-context-viewer\config.json')
183
- Restore-File (Join-Path $BackupDir 'pix-optimizer\config.json') (Join-Path $agentDir 'pix-optimizer\config.json')
184
- Restore-File (Join-Path $BackupDir 'pi-nvidia-nim\config.json') (Join-Path $agentDir 'pi-nvidia-nim\config.json')
185
-
186
- # ── 3. Global Skills ──────────────────────────────────────
187
- Log "3/8 Global skills..."
188
- Restore-Dir (Join-Path $BackupDir 'skills') (Join-Path $agentDir 'skills')
189
-
190
- # ── 4. Project Skills & Memory ────────────────────────────
191
- Log "4/8 Project skills & memory..."
192
- $projSrc = Join-Path $BackupDir 'projects-memory'
193
- if (Test-Path -LiteralPath $projSrc -PathType Container) {
194
- Restore-Dir $projSrc (Join-Path $agentDir 'projects-memory')
195
- OK " projects-memory/ restored"
196
- } else {
197
- Warn " No project memory in backup"
198
- }
199
-
200
- # ── 5. Local Extensions ───────────────────────────────────
201
- Log "5/8 Local extension source code..."
202
- $localSrc = Join-Path $BackupDir 'local-extensions'
203
- if (Test-Path -LiteralPath $localSrc -PathType Container) {
204
- foreach ($ext in Get-ChildItem -LiteralPath $localSrc -Directory) {
205
- $dst = Join-Path $HOME "projects\personal\$($ext.Name)"
206
- New-Item -ItemType Directory -Path $dst -Force | Out-Null
207
- Copy-Tree $ext.FullName $dst
208
- OK " $($ext.Name)/ restored"
209
- }
210
- } else {
211
- Warn " No local extensions in backup"
212
- }
213
-
214
- # ── 6. npm Extension Manifests ────────────────────────────
215
- Log "6/8 npm extension manifests..."
216
- $npmSrc = Join-Path $BackupDir 'npm-manifests'
217
- if (Test-Path -LiteralPath $npmSrc -PathType Container) {
218
- $npmDst = Join-Path $agentDir 'npm'
219
- New-Item -ItemType Directory -Path $npmDst -Force | Out-Null
220
- Copy-Tree $npmSrc $npmDst
221
- OK " npm manifests restored (run 'npm install' to reinstall deps)"
222
- } else {
223
- Warn " No npm manifests in backup"
224
- }
225
-
226
- # ── 7. Hermes Memory ──────────────────────────────────────
227
- Log "7/8 Hermes memory (active files)..."
228
- $hermesSrc = Join-Path $BackupDir 'pi-hermes-memory'
229
- if (Test-Path -LiteralPath $hermesSrc -PathType Container) {
230
- $hermesDst = Join-Path $agentDir 'pi-hermes-memory'
231
- New-Item -ItemType Directory -Path $hermesDst -Force | Out-Null
232
- foreach ($f in @('MEMORY.md','USER.md','failures.md','retired-failures.md','retired-memory.md')) {
233
- Restore-File (Join-Path $hermesSrc $f) (Join-Path $hermesDst $f)
234
- }
235
- } else {
236
- Warn " No Hermes memory in backup"
237
- }
238
-
239
- # ── 8. Hermes-cleanup Backups ─────────────────────────────
240
- Log "8/8 Hermes-cleanup backups..."
241
- $cleanupSrc = Join-Path $BackupDir 'hermes-cleanup'
242
- if (Test-Path -LiteralPath $cleanupSrc -PathType Container) {
243
- foreach ($d in Get-ChildItem -LiteralPath $cleanupSrc -Directory) {
244
- Restore-Dir $d.FullName (Join-Path $agentDir "hermes-cleanup\$($d.Name)")
236
+ $entries = @(Read-Manifest $ManifestFile)
237
+ $total = @($entries | Where-Object { $_.Kind -eq 'section' }).Count
238
+ $step = 0
239
+ foreach ($e in $entries) {
240
+ switch ($e.Kind) {
241
+ 'section' { $step++; Log "$step/$total $($e.A)..." }
242
+ 'file' {
243
+ $dst = P $PiRoot $e.A
244
+ $src = P $BackupDir $e.B
245
+ Restore-File $src $dst
246
+ # Credentials: keep a restored auth.json private to this user (Unix)
247
+ if ($e.B -eq 'auth.json' -and (Test-Path -LiteralPath $src) -and (Test-Path -LiteralPath $dst) -and -not ($IsWindows -or $env:OS -eq 'Windows_NT')) {
248
+ try { [System.IO.File]::SetUnixFileMode($dst, [System.IO.UnixFileMode]'UserRead,UserWrite') } catch { Warn " could not restrict permissions on auth.json: $($_.Exception.Message)" }
249
+ }
250
+ }
251
+ 'dir' { Restore-Dir (P $BackupDir $e.B) (P $PiRoot $e.A) }
252
+ { $_ -in 'dir-each','recent' } {
253
+ $src = P $BackupDir $e.B
254
+ if (Test-Path -LiteralPath $src -PathType Container) {
255
+ foreach ($sub in Get-ChildItem -LiteralPath $src -Directory) {
256
+ Restore-Dir $sub.FullName (Join-Path (P $PiRoot $e.A) $sub.Name)
257
+ }
258
+ OK " $($e.B)/ restored"
259
+ } else {
260
+ Warn " No $($e.B) in backup"
261
+ }
262
+ }
263
+ 'local-ext' {
264
+ $src = P $BackupDir "local-extensions/$($e.A)"
265
+ if (Test-Path -LiteralPath $src -PathType Container) {
266
+ $dst = Join-Path $LocalExtRoot $e.A
267
+ New-Item -ItemType Directory -Path $dst -Force | Out-Null
268
+ Copy-Tree $src $dst
269
+ OK " $($e.A)/ restored"
270
+ } else {
271
+ Warn " $($e.A) - not in backup, skipping"
272
+ }
273
+ }
274
+ 'npm' {
275
+ $src = P $BackupDir $e.B
276
+ if (Test-Path -LiteralPath $src -PathType Container) {
277
+ $dst = P $PiRoot $e.A
278
+ New-Item -ItemType Directory -Path $dst -Force | Out-Null
279
+ Copy-Tree $src $dst
280
+ OK " npm manifests restored (run 'npm install' to reinstall deps)"
281
+ } else {
282
+ Warn " No npm manifests in backup"
283
+ }
284
+ }
285
+ default { Warn "Unknown manifest entry type: $($e.Kind)" }
245
286
  }
246
- } else {
247
- Warn " No cleanup backups in backup"
248
287
  }
249
288
 
250
289
  # ── Verify ────────────────────────────────────────────────
@@ -263,8 +302,8 @@ Log " /scoped-memory-status"
263
302
  Log " 3. Restart Pi and verify everything works"
264
303
  Write-Host ""
265
304
 
266
- # ─── Cleanup ──────────────────────────────────────────────
267
- if ($STAGE -and (Test-Path -LiteralPath $STAGE)) {
268
- Remove-Item -LiteralPath $STAGE -Recurse -Force
269
- Log "Removed temp extraction dir."
305
+ } finally {
306
+ if ($STAGE -and (Test-Path -LiteralPath $STAGE)) {
307
+ Remove-Item -LiteralPath $STAGE -Recurse -Force -ErrorAction SilentlyContinue
308
+ }
270
309
  }
package/restore-pi.sh CHANGED
@@ -6,6 +6,7 @@ set -euo pipefail
6
6
 
7
7
  # ─── Config ──────────────────────────────────────────────────────
8
8
  PI_ROOT="${PI_ROOT:-$HOME/.pi}"
9
+ LOCAL_EXT_ROOT="${LOCAL_EXT_ROOT:-$HOME/projects}"
9
10
 
10
11
  # ─── Colors ──────────────────────────────────────────────────────
11
12
  RED='\033[0;31m'
@@ -19,6 +20,19 @@ ok() { echo -e "${GREEN}[OK]${NC} $*"; }
19
20
  warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
20
21
  err() { echo -e "${RED}[ERR]${NC} $*"; }
21
22
 
23
+ # ─── Cleanup ─────────────────────────────────────────────────────
24
+ # Registered before any temp dir is created, so every exit path (abort, error,
25
+ # success) removes the extraction dir.
26
+ STAGE=""
27
+ cleanup() {
28
+ local rc=$?
29
+ if [[ -n "$STAGE" && -d "$STAGE" ]]; then
30
+ rm -rf "$STAGE"
31
+ fi
32
+ return $rc
33
+ }
34
+ trap cleanup EXIT
35
+
22
36
  # ─── Usage ───────────────────────────────────────────────────────
23
37
  usage() {
24
38
  cat <<EOF
@@ -27,9 +41,9 @@ Usage: $0 <backup-directory-or-archive>
27
41
  Restores a Pi backup created by backup-pi.sh
28
42
 
29
43
  Examples:
30
- $0 ~/projects/personal/pi-utils/backups/pi-backup-20260811-143000
31
- $0 ~/projects/personal/pi-utils/backups/pi-backup-20260811-143000.7z
32
- $0 ~/projects/personal/pi-utils/backups/pi-backup-20260811-143000.zip
44
+ $0 ~/pi-backups/pi-backup-20260811-143000
45
+ $0 ~/pi-backups/pi-backup-20260811-143000.7z
46
+ $0 ~/pi-backups/pi-backup-20260811-143000.zip
33
47
 
34
48
  Accepts either an uncompressed backup directory or a compressed
35
49
  zip/7z archive (as produced by backup-pi.sh).
@@ -37,6 +51,9 @@ zip/7z archive (as produced by backup-pi.sh).
37
51
  Prerequisites:
38
52
  - Fresh Pi install completed (pi --version works)
39
53
  - Pi NOT running
54
+
55
+ Environment:
56
+ PI_BACKUP_ASSUME_YES=1 Skip the confirmation prompt (for scripted use)
40
57
  EOF
41
58
  exit 1
42
59
  }
@@ -55,10 +72,10 @@ BACKUP_ARG="$1"
55
72
  if [[ -d "$BACKUP_ARG" ]]; then
56
73
  # Uncompressed directory backup
57
74
  BACKUP_DIR="$BACKUP_ARG"
58
- STAGE=""
59
75
  elif [[ -f "$BACKUP_ARG" && "$BACKUP_ARG" =~ \.(zip|7z)$ ]]; then
60
76
  # Compressed archive: extract to a temp dir first
61
- STAGE="$(mktemp -d)"
77
+ # Explicit template: BSD mktemp ignores $TMPDIR when called without one.
78
+ STAGE="$(mktemp -d "${TMPDIR:-/tmp}/pi-restore.XXXXXX")"
62
79
  log "Extracting archive: $BACKUP_ARG"
63
80
  tool="$(pick_extract_tool)"
64
81
  if [[ -n "$tool" ]]; then
@@ -70,7 +87,7 @@ elif [[ -f "$BACKUP_ARG" && "$BACKUP_ARG" =~ \.(zip|7z)$ ]]; then
70
87
  fi
71
88
  # The archive holds one top-level pi-backup-* dir
72
89
  BACKUP_DIR="$(find "$STAGE" -mindepth 1 -maxdepth 1 -type d | head -1)"
73
- [[ -n "$BACKUP_DIR" ]] || { err "No backup directory found inside archive."; rm -rf "$STAGE"; exit 1; }
90
+ [[ -n "$BACKUP_DIR" ]] || { err "No backup directory found inside archive."; exit 1; }
74
91
  log "Extracted to: $BACKUP_DIR"
75
92
  else
76
93
  err "Backup not found: $BACKUP_ARG (need a directory, .zip, or .7z)"
@@ -87,20 +104,44 @@ warn "This will OVERWRITE all current Pi configuration."
87
104
  warn "Backup source: $BACKUP_DIR"
88
105
  warn "Target: $PI_ROOT"
89
106
  warn "Pi must NOT be running."
107
+
108
+ # Best-effort running-Pi check. It only warns: process names are unreliable.
109
+ if command -v pgrep >/dev/null 2>&1 && { pgrep -x pi >/dev/null 2>&1 || pgrep -f 'pi-coding-agent' >/dev/null 2>&1; }; then
110
+ warn "A Pi process appears to be running. Exit Pi first: files restored under a"
111
+ warn "running Pi can be overwritten or corrupted when it exits."
112
+ fi
90
113
  echo
91
- read -rp "Continue? [y/N] " -n 1
92
- echo
93
- [[ $REPLY =~ ^[Yy]$ ]] || { log "Aborted."; exit 0; }
114
+
115
+ if [[ "${PI_BACKUP_ASSUME_YES:-0}" == "1" ]]; then
116
+ log "PI_BACKUP_ASSUME_YES=1 set; skipping confirmation."
117
+ else
118
+ REPLY=""
119
+ if ! read -rp "Continue? [y/N] " -n 1 REPLY; then
120
+ echo
121
+ err "Cannot read a confirmation (stdin is not interactive)."
122
+ err "Run this in a terminal, or set PI_BACKUP_ASSUME_YES=1 to skip the prompt."
123
+ exit 1
124
+ fi
125
+ echo
126
+ [[ $REPLY =~ ^[Yy]$ ]] || { log "Aborted."; exit 0; }
127
+ fi
128
+
129
+ # ─── Manifest ────────────────────────────────────────────────────
130
+ # What gets restored is defined once, in backup-manifest.txt (shared with backup).
131
+ MANIFEST_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/backup-manifest.txt"
132
+ [[ -f "$MANIFEST_FILE" ]] || { err "backup-manifest.txt not found next to $0"; exit 1; }
94
133
 
95
134
  # ─── Helpers ─────────────────────────────────────────────────────
135
+ strip_cr() { printf '%s' "${1%$'\r'}"; }
136
+
96
137
  restore_file() {
97
138
  local src="$1" dst="$2"
98
139
  if [[ -f "$src" ]]; then
99
140
  mkdir -p "$(dirname "$dst")"
100
141
  cp "$src" "$dst"
101
- ok " $(basename "$src")"
142
+ ok " ${src#"$BACKUP_DIR"/}"
102
143
  else
103
- warn " $(basename "$src") — not in backup, skipping"
144
+ warn " ${src#"$BACKUP_DIR"/} — not in backup, skipping"
104
145
  fi
105
146
  }
106
147
 
@@ -116,6 +157,54 @@ restore_dir() {
116
157
  fi
117
158
  }
118
159
 
160
+ restore_manifest_entries() {
161
+ local total step=0 kind f1 f2 f3
162
+ total="$(grep -c '^section|' "$MANIFEST_FILE" || true)"
163
+ while IFS='|' read -r kind f1 f2 f3 || [[ -n "$kind" ]]; do
164
+ kind="$(strip_cr "$kind")"; f1="$(strip_cr "${f1:-}")"; f2="$(strip_cr "${f2:-}")"; f3="$(strip_cr "${f3:-}")"
165
+ case "$kind" in
166
+ ''|'#'*) continue ;;
167
+ section)
168
+ step=$((step+1)); log "$step/$total $f1..." ;;
169
+ file)
170
+ restore_file "$BACKUP_DIR/$f2" "$PI_ROOT/$f1"
171
+ # Credentials: keep a restored auth.json private to this user
172
+ if [[ "$f2" == "auth.json" && -f "$BACKUP_DIR/$f2" && -f "$PI_ROOT/$f1" ]]; then chmod 600 "$PI_ROOT/$f1"; fi ;;
173
+ dir)
174
+ restore_dir "$BACKUP_DIR/$f2" "$PI_ROOT/$f1" ;;
175
+ dir-each|recent)
176
+ if [[ -d "$BACKUP_DIR/$f2" ]]; then
177
+ local sub name
178
+ for sub in "$BACKUP_DIR/$f2"/*/; do
179
+ [[ -d "$sub" ]] || continue
180
+ name="$(basename "$sub")"
181
+ restore_dir "$sub" "$PI_ROOT/$f1/$name"
182
+ done
183
+ ok " $f2/ restored"
184
+ else
185
+ warn " No $f2 in backup"
186
+ fi ;;
187
+ local-ext)
188
+ if [[ -d "$BACKUP_DIR/local-extensions/$f1" ]]; then
189
+ mkdir -p "$LOCAL_EXT_ROOT/$f1"
190
+ cp -a "$BACKUP_DIR/local-extensions/$f1/." "$LOCAL_EXT_ROOT/$f1/"
191
+ ok " $f1/ restored"
192
+ else
193
+ warn " $f1 — not in backup, skipping"
194
+ fi ;;
195
+ npm)
196
+ if [[ -d "$BACKUP_DIR/$f2" ]]; then
197
+ mkdir -p "$PI_ROOT/$f1"
198
+ cp -a "$BACKUP_DIR/$f2/." "$PI_ROOT/$f1/"
199
+ ok " npm manifests restored (run 'npm install' or 'bun install' to reinstall deps)"
200
+ else
201
+ warn " No npm manifests in backup"
202
+ fi ;;
203
+ *) warn "Unknown manifest entry type: $kind" ;;
204
+ esac
205
+ done < "$MANIFEST_FILE"
206
+ }
207
+
119
208
  # ─── Main ────────────────────────────────────────────────────────
120
209
  main() {
121
210
  log "════════════════════════════════════════════════════════════"
@@ -123,95 +212,7 @@ main() {
123
212
  log "════════════════════════════════════════════════════════════"
124
213
  echo
125
214
 
126
- # ── 1. Core Config Files ──────────────────────────────────────
127
- log "1/8 Core configuration files..."
128
- restore_file "$BACKUP_DIR/settings.json" "$PI_ROOT/agent/settings.json"
129
- restore_file "$BACKUP_DIR/auth.json" "$PI_ROOT/agent/auth.json"
130
- restore_file "$BACKUP_DIR/models.json" "$PI_ROOT/agent/models.json"
131
- restore_file "$BACKUP_DIR/trust.json" "$PI_ROOT/agent/trust.json"
132
- restore_file "$BACKUP_DIR/keybindings.json" "$PI_ROOT/agent/keybindings.json"
133
- restore_file "$BACKUP_DIR/pix.json" "$PI_ROOT/agent/pix.json"
134
- restore_file "$BACKUP_DIR/optimizer.json" "$PI_ROOT/agent/optimizer.json"
135
- restore_file "$BACKUP_DIR/lmstudio.json.bak" "$PI_ROOT/agent/lmstudio.json.bak"
136
- restore_file "$BACKUP_DIR/hermes-memory-config.json" "$PI_ROOT/agent/hermes-memory-config.json"
137
- restore_file "$BACKUP_DIR/pi.code-workspace" "$PI_ROOT/agent/pi.code-workspace"
138
-
139
- # ── 2. Extension Configs ──────────────────────────────────────
140
- log "2/8 Extension configurations..."
141
- restore_file "$BACKUP_DIR/pi-hermes-memory-cleanup/scoped-memory.json" \
142
- "$PI_ROOT/agent/pi-hermes-memory-cleanup/scoped-memory.json"
143
- restore_file "$BACKUP_DIR/loop-police.json" "$PI_ROOT/agent/loop-police.json"
144
- restore_file "$BACKUP_DIR/pi-rtk/config.json" "$PI_ROOT/agent/pi-rtk/config.json"
145
- restore_file "$BACKUP_DIR/context-mode/config.json" "$PI_ROOT/agent/context-mode/config.json"
146
- restore_file "$BACKUP_DIR/pi-timeout/config.json" "$PI_ROOT/agent/pi-timeout/config.json"
147
- restore_file "$BACKUP_DIR/pi-context-viewer/config.json" "$PI_ROOT/agent/pi-context-viewer/config.json"
148
- restore_file "$BACKUP_DIR/pix-optimizer/config.json" "$PI_ROOT/agent/pix-optimizer/config.json"
149
- restore_file "$BACKUP_DIR/pi-nvidia-nim/config.json" "$PI_ROOT/agent/pi-nvidia-nim/config.json"
150
-
151
- # ── 3. Global Skills ──────────────────────────────────────────
152
- log "3/8 Global skills..."
153
- restore_dir "$BACKUP_DIR/skills" "$PI_ROOT/agent/skills"
154
-
155
- # ── 4. Project Skills & Memory ────────────────────────────────
156
- log "4/8 Project skills & memory..."
157
- if [[ -d "$BACKUP_DIR/projects-memory" ]]; then
158
- for proj in "$BACKUP_DIR/projects-memory"/*/; do
159
- [[ -d "$proj" ]] || continue
160
- name="$(basename "$proj")"
161
- restore_dir "$proj" "$PI_ROOT/agent/projects-memory/$name"
162
- done
163
- ok " projects-memory/ restored"
164
- else
165
- warn " No project memory in backup"
166
- fi
167
-
168
- # ── 5. Local Extensions ───────────────────────────────────────
169
- log "5/8 Local extension source code..."
170
- if [[ -d "$BACKUP_DIR/local-extensions" ]]; then
171
- for ext in "$BACKUP_DIR/local-extensions"/*/; do
172
- [[ -d "$ext" ]] || continue
173
- name="$(basename "$ext")"
174
- mkdir -p "$HOME/projects/personal/$name"
175
- rsync -a "$ext/" "$HOME/projects/personal/$name/"
176
- ok " $name/ restored"
177
- done
178
- else
179
- warn " No local extensions in backup"
180
- fi
181
-
182
- # ── 6. npm Extension Manifests ────────────────────────────────
183
- log "6/8 npm extension manifests..."
184
- if [[ -d "$BACKUP_DIR/npm-manifests" ]]; then
185
- mkdir -p "$PI_ROOT/agent/npm"
186
- cp -a "$BACKUP_DIR/npm-manifests/"* "$PI_ROOT/agent/npm/" 2>/dev/null || true
187
- ok " npm manifests restored (run 'npm install' or 'bun install' to reinstall deps)"
188
- else
189
- warn " No npm manifests in backup"
190
- fi
191
-
192
- # ── 7. Hermes Memory ──────────────────────────────────────────
193
- log "7/8 Hermes memory (active files)..."
194
- if [[ -d "$BACKUP_DIR/pi-hermes-memory" ]]; then
195
- mkdir -p "$PI_ROOT/agent/pi-hermes-memory"
196
- for f in MEMORY.md USER.md failures.md retired-failures.md retired-memory.md; do
197
- restore_file "$BACKUP_DIR/pi-hermes-memory/$f" "$PI_ROOT/agent/pi-hermes-memory/$f"
198
- done
199
- else
200
- warn " No Hermes memory in backup"
201
- fi
202
-
203
- # ── 8. Cleanup Backups ────────────────────────────────────────
204
- log "8/8 Hermes-cleanup backups..."
205
- if [[ -d "$BACKUP_DIR/hermes-cleanup" ]]; then
206
- mkdir -p "$PI_ROOT/agent/hermes-cleanup"
207
- for d in "$BACKUP_DIR/hermes-cleanup"/*/; do
208
- [[ -d "$d" ]] || continue
209
- name="$(basename "$d")"
210
- restore_dir "$d" "$PI_ROOT/agent/hermes-cleanup/$name"
211
- done
212
- else
213
- warn " No cleanup backups in backup"
214
- fi
215
+ restore_manifest_entries
215
216
 
216
217
  # ── Verify ────────────────────────────────────────────────────
217
218
  echo
@@ -230,10 +231,4 @@ main() {
230
231
  echo
231
232
  }
232
233
 
233
- main "$@"
234
-
235
- # ─── Cleanup ────────────────────────────────────────────────────
236
- if [[ -n "${STAGE:-}" && -d "$STAGE" ]]; then
237
- rm -rf "$STAGE"
238
- log "Removed temp extraction dir."
239
- fi
234
+ main "$@"