@jamiefutch/pi-backup 1.1.11 → 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/README.md CHANGED
@@ -125,8 +125,8 @@ Backup: pi-backup-20260812-112019.7z
125
125
 
126
126
  | Action | Description |
127
127
  |--------|-------------|
128
- | **🔄 Restore** | Runs the platform restore script — overwrites all Pi config (requires confirmation) |
129
- | **📋 Copy to internal** | Copies external backup to `~/.pi/backups/` for quick access (external only) |
128
+ | **🔄 Restore** | After confirmation, shows (and copies, where possible) the exact restore command to run **after you exit Pi**. The TUI never restores in-process, because the running Pi owns the files being replaced |
129
+ | **📋 Copy to internal** | Extracts/copies an external backup into `~/.pi/backups/` as an uncompressed directory (external only) |
130
130
  | **📄 View manifest** | Opens `MANIFEST.txt` in editor (extracts from compressed archives) |
131
131
  | **🗑️ Delete** | Permanently removes backup (requires confirmation) |
132
132
 
@@ -151,11 +151,21 @@ Backup: pi-backup-20260812-112019.7z
151
151
  ./pi-clean-reinstall.sh
152
152
  ```
153
153
 
154
+ The clean reinstall is rollback-safe: it checks that a backup exists in `BACKUP_ROOT` (and asks for an extra `no backup` confirmation if not), **moves** `~/.pi` to `~/.pi.pre-reinstall-<timestamp>`, uninstalls and reinstalls Pi, verifies `pi --version`, and only then deletes the moved copy. If any step fails, the original `~/.pi` is moved back. Set `KEEP_OLD=1` to keep the moved-aside copy.
155
+
154
156
  #### 3. Restore a directory, `.7z` archive, or `.zip` archive
155
157
  ```bash
156
158
  ./restore-pi.sh ~/pi-backups/pi-backup-20260811-143000.7z
157
159
  ```
158
160
 
161
+ Exit Pi first: the script warns (but does not block) if it detects a running Pi process, because files restored under a running Pi can be overwritten when it exits. Restore asks for confirmation; it needs an interactive terminal and otherwise stops with a message. For scripted use, set `PI_BACKUP_ASSUME_YES=1`:
162
+
163
+ ```bash
164
+ PI_BACKUP_ASSUME_YES=1 ./restore-pi.sh ~/pi-backups/pi-backup-20260811-143000.7z
165
+ ```
166
+
167
+ Temporary extraction directories are always removed, including when you answer `n`, the archive is damaged, or a copy fails part-way.
168
+
159
169
  #### 4. Reinstall npm deps + verify
160
170
  ```bash
161
171
  cd ~/.pi/agent && npm install # or bun install
@@ -195,31 +205,52 @@ $env:PI_ROOT='C:\Users\you\.pi'; $env:BACKUP_ROOT='D:\pi-backups'; .\backup-pi.p
195
205
 
196
206
  ## What Gets Backed Up
197
207
 
208
+ The list lives in one file, [`backup-manifest.txt`](backup-manifest.txt), read by all four scripts; a test keeps this table in sync with it.
209
+
198
210
  | Category | Paths |
199
211
  |----------|-------|
200
212
  | **Core config** | `settings.json`, `auth.json`, `models.json`, `trust.json`, `keybindings.json`, `pix.json`, `optimizer.json`, `lmstudio.json.bak`, `hermes-memory-config.json`, `pi.code-workspace` |
201
213
  | **Extension configs** | `pi-hermes-memory-cleanup/scoped-memory.json`, `loop-police.json`, `pi-rtk/config.json`, `context-mode/config.json`, `pi-timeout/config.json`, `pi-context-viewer/config.json`, `pix-optimizer/config.json`, `pi-nvidia-nim/config.json` |
202
214
  | **Global skills** | `~/.pi/agent/skills/` |
203
215
  | **Project skills & memory** | `~/.pi/agent/projects-memory/<project>/` |
204
- | **Local extension source** | `$LOCAL_EXT_ROOT/pi-timeout/`, `pi-chunk/`, `pi-hermes-memory-cleanup/`, `pi-context-docs/` (defaults to `~/projects/`) |
205
- | **npm manifests** | `package.json`, `package-lock.json`, `npm-shrinkwrap.json` from `~/.pi/agent/npm/` |
206
- | **Hermes memory (active)** | `MEMORY.md`, `USER.md`, `failures.md`, `retired-*.md` |
207
- | **Cleanup backups** | Last 5 from `~/.pi/agent/hermes-cleanup/` |
216
+ | **Local extension source** | `$LOCAL_EXT_ROOT/pi-timeout/`, `pi-chunk/`, `pi-hermes-memory-cleanup/`, `pi-context-docs/` (defaults to `~/projects/`; `node_modules`, `dist`, `build`, `.git`, `coverage` and `*.log` are skipped) |
217
+ | **npm manifests** | `package.json`, `package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml` from `~/.pi/agent/npm/` (never `node_modules`) |
218
+ | **Hermes memory (active)** | `MEMORY.md`, `USER.md`, `failures.md`, `retired-failures.md`, `retired-memory.md` |
219
+ | **Cleanup backups** | Last 5 timestamped (`20*`) directories from `~/.pi/agent/hermes-cleanup/` |
208
220
 
209
- The backup script output:
221
+ Example output of `./backup-pi.sh` (captured from a real run, abridged):
210
222
  ```
211
- ════════════════════════════════════════════════════════════
212
- Pi Complete Backup
213
- ════════════════════════════════════════════════════════════
214
- Source: ~/.pi
215
- Destination: ~/pi-backups/pi-backup-20260811-143000
223
+ [INFO] ════════════════════════════════════════════════════════════
224
+ [INFO] Pi Complete Backup
225
+ [INFO] ════════════════════════════════════════════════════════════
226
+ [INFO] Source: ~/.pi
227
+ [INFO] Destination: ~/pi-backups/pi-backup-20261122-011819
228
+
229
+ [INFO] 1/8 Core configuration files...
230
+ [OK] settings.json
231
+ [OK] auth.json
232
+ [WARN] auth.json holds your API credentials and is included in this backup.
233
+ [WARN] Keep the backup private; set PI_BACKUP_EXCLUDE_AUTH=1 to leave it out.
234
+ [OK] models.json
235
+ [WARN] keybindings.json — not found, skipping
216
236
  ...
217
- Backup complete!
218
- Location: ~/pi-backups/pi-backup-20260811-143000
219
- Size: 12M
220
- Files: 347
237
+ [INFO] 8/8 Recent hermes-cleanup backups (last 5)...
238
+ [OK] 20260107/
239
+ ...
240
+ [INFO] 9/9 Compressing backup (zip)...
241
+ [OK] ~/pi-backups/pi-backup-20261122-011819.zip
242
+
243
+ [INFO] ════════════════════════════════════════════════════════════
244
+ [OK] Backup complete!
245
+ [INFO] Archive: ~/pi-backups/pi-backup-20261122-011819.zip
246
+ [INFO] Size: 12K
247
+
248
+ [INFO] To restore after reinstall:
249
+ [INFO] ./restore-pi.sh ~/pi-backups/pi-backup-20261122-011819.zip
221
250
  ```
222
251
 
252
+ An internal backup (`KEEP_UNCOMPRESSED=1`, what the TUI's **Create internal backup** runs) skips the compression step and prints `Staging: <directory>` instead of `Archive:`.
253
+
223
254
  ## What Does NOT Get Backed Up (Regeneratable)
224
255
 
225
256
  | Excluded | Why |
@@ -232,6 +263,18 @@ Files: 347
232
263
 
233
264
  ---
234
265
 
266
+ ## Security
267
+
268
+ > **Backups contain `auth.json`, which holds your API keys and tokens.** Treat every backup (directory, `.zip`, `.7z`) as a secret.
269
+
270
+ - Backups are created private to your user: `umask 077` on macOS/Linux, `auth.json` is `chmod 600`, and archives are `600` (on Windows, rely on your profile folder's ACLs and avoid shared drives).
271
+ - Set `PI_BACKUP_EXCLUDE_AUTH=1` to leave `auth.json` out entirely (you will need to sign in to providers again after a restore).
272
+ - Restore sets a restored `auth.json` back to `600`.
273
+ - There is intentionally no built-in encryption: passing a password to `7z` on the command line leaks it through `ps`. If you need encryption, encrypt the finished archive yourself (for example with `age` or `gpg`) or store backups on an encrypted volume.
274
+ - Never commit or share backups. They are also in `.gitignore` (`*.7z`, `*.zip`, `backups/`).
275
+
276
+ ---
277
+
235
278
  ## Backup Location
236
279
 
237
280
  ```
@@ -277,6 +320,8 @@ Use the **⚙️ Configure external backup directory** option in `/pi-backup` to
277
320
  - **📝 Change directory** — prompt to type a path, saved to `settings.json`
278
321
  - **🔄 Reset to default** — removes the `settings.json` value, falls back to env var / default
279
322
 
323
+ If `settings.json` is corrupt (not valid JSON), the manager never overwrites it: read-only screens fall back to the default directory with one warning, and changes are refused with an error. Successful saves are written atomically and keep the previous file as `settings.json.bak-<timestamp>` (last 3 kept).
324
+
280
325
  ### When the prompt appears
281
326
 
282
327
  The configure prompt only appears when creating an external backup if **both** of these are true:
@@ -294,7 +339,10 @@ If the default directory already contains backups, it is treated as configured a
294
339
  | `PI_ROOT` | `~/.pi` | Override Pi root directory |
295
340
  | `BACKUP_ROOT` | `~/pi-backups` | Override backup destination (highest priority for the TUI too) |
296
341
  | `LOCAL_EXT_ROOT` | `~/projects` | Override the directory containing local extension source repositories |
297
- | `KEEP_UNCOMPRESSED` | `0` | Keep the uncompressed staging directory after external backup; the TUI sets this automatically for internal backups |
342
+ | `KEEP_UNCOMPRESSED` | `0` | `1` makes a plain, uncompressed staging directory and skips compression (no `zip`/7-Zip needed); the TUI sets this for internal backups. With `0` the staging directory is compressed and removed |
343
+ | `PI_BACKUP_ASSUME_YES` | unset | Set to `1` to skip the restore confirmation prompt (scripted use). Without it, restore needs an interactive terminal and exits with a clear message otherwise |
344
+ | `PI_BACKUP_EXCLUDE_AUTH` | unset | Set to `1` to leave `auth.json` (API credentials) out of the backup |
345
+ | `KEEP_OLD` | unset | Set to `1` to keep `~/.pi.pre-reinstall-<timestamp>` after a successful clean reinstall |
298
346
  | `PKG_MANAGER` | `bun` | Package manager used by the clean-reinstall scripts (`bun`, `npm`, etc.) |
299
347
 
300
348
  ```bash
@@ -324,7 +372,10 @@ PI_ROOT=/custom/.pi BACKUP_ROOT=/mnt/backups ./backup-pi.sh
324
372
  | "npm install fails" | Check Node.js version (need ≥22), try `bun install` |
325
373
  | "Skills not loading" | Verify `settings.json` has correct `packages` paths after restore |
326
374
  | "Models not found" | Check `models.json` restored correctly, restart Pi |
327
- | "Auth failed" | Verify `auth.json` restored, API keys valid |
375
+ | "Auth failed" | Verify `auth.json` restored, API keys valid (it is absent if the backup was made with `PI_BACKUP_EXCLUDE_AUTH=1`) |
376
+ | Restore says "Cannot read a confirmation" | stdin is not a terminal (cron, CI, pipe). Run it in a terminal or set `PI_BACKUP_ASSUME_YES=1` |
377
+ | Backup says "Compression ... failed" | The staging directory is kept (it is intact). Fix 7-Zip/zip and re-run, or restore directly from the staging directory |
378
+ | TUI says `settings.json could not be parsed` | The file is never overwritten. Fix the JSON (or delete the file) and retry; `settings.json.bak-*` copies are kept from earlier saves |
328
379
 
329
380
  ---
330
381
 
@@ -0,0 +1,61 @@
1
+ # pi-backup manifest: the single source of truth for what is backed up and restored.
2
+ # Read by backup-pi.sh, restore-pi.sh, backup-pi.ps1 and restore-pi.ps1.
3
+ # LF line endings only (enforced by .gitattributes). Paths use "/" on every platform.
4
+ # Paths on the left are relative to PI_ROOT (default ~/.pi); the right side is relative to the backup.
5
+ #
6
+ # section|<title> starts a numbered step in the script output
7
+ # file|<pi path>|<backup path> one file; missing files are skipped with a warning
8
+ # dir|<pi path>|<backup path> a whole directory; replaced on restore
9
+ # dir-each|<pi path>|<backup path> each sub-directory is backed up / replaced separately
10
+ # local-ext|<name> source tree under LOCAL_EXT_ROOT (node_modules, dist, build, .git, coverage, *.log excluded)
11
+ # npm|<pi path>|<backup path> package.json and lockfiles only (max depth 3), never node_modules
12
+ # recent|<pi path>|<backup path>|<n> the n newest sub-directories whose name starts with "20" (timestamps)
13
+ #
14
+ # Keep README.md "What Gets Backed Up" in sync; tests/sh/manifest.test.sh checks it.
15
+
16
+ section|Core configuration files
17
+ file|agent/settings.json|settings.json
18
+ file|agent/auth.json|auth.json
19
+ file|agent/models.json|models.json
20
+ file|agent/trust.json|trust.json
21
+ file|agent/keybindings.json|keybindings.json
22
+ file|agent/pix.json|pix.json
23
+ file|agent/optimizer.json|optimizer.json
24
+ file|agent/lmstudio.json.bak|lmstudio.json.bak
25
+ file|agent/hermes-memory-config.json|hermes-memory-config.json
26
+ file|agent/pi.code-workspace|pi.code-workspace
27
+
28
+ section|Extension configurations
29
+ file|agent/pi-hermes-memory-cleanup/scoped-memory.json|pi-hermes-memory-cleanup/scoped-memory.json
30
+ file|agent/loop-police.json|loop-police.json
31
+ file|agent/pi-rtk/config.json|pi-rtk/config.json
32
+ file|agent/context-mode/config.json|context-mode/config.json
33
+ file|agent/pi-timeout/config.json|pi-timeout/config.json
34
+ file|agent/pi-context-viewer/config.json|pi-context-viewer/config.json
35
+ file|agent/pix-optimizer/config.json|pix-optimizer/config.json
36
+ file|agent/pi-nvidia-nim/config.json|pi-nvidia-nim/config.json
37
+
38
+ section|Global skills
39
+ dir|agent/skills|skills
40
+
41
+ section|Project skills & memory
42
+ dir-each|agent/projects-memory|projects-memory
43
+
44
+ section|Local extension source code
45
+ local-ext|pi-timeout
46
+ local-ext|pi-chunk
47
+ local-ext|pi-hermes-memory-cleanup
48
+ local-ext|pi-context-docs
49
+
50
+ section|npm extension manifests
51
+ npm|agent/npm|npm-manifests
52
+
53
+ section|Hermes memory (active files)
54
+ file|agent/pi-hermes-memory/MEMORY.md|pi-hermes-memory/MEMORY.md
55
+ file|agent/pi-hermes-memory/USER.md|pi-hermes-memory/USER.md
56
+ file|agent/pi-hermes-memory/failures.md|pi-hermes-memory/failures.md
57
+ file|agent/pi-hermes-memory/retired-failures.md|pi-hermes-memory/retired-failures.md
58
+ file|agent/pi-hermes-memory/retired-memory.md|pi-hermes-memory/retired-memory.md
59
+
60
+ section|Recent hermes-cleanup backups (last 5)
61
+ recent|agent/hermes-cleanup|hermes-cleanup|5
package/backup-pi.ps1 CHANGED
@@ -29,14 +29,70 @@ function OK { Write-Host "[OK] $args" -ForegroundColor Green }
29
29
  function Warn { Write-Host "[WARN] $args" -ForegroundColor Yellow }
30
30
  function Err { Write-Host "[ERR] $args" -ForegroundColor Red; exit 1 }
31
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
+
32
88
  function Copy-IfExists([string]$src, [string]$dst) {
33
89
  if (Test-Path -LiteralPath $src) {
34
90
  $dstDir = Split-Path $dst -Parent
35
91
  if (!(Test-Path -LiteralPath $dstDir)) { New-Item -ItemType Directory -Path $dstDir -Force | Out-Null }
36
92
  Copy-Item -LiteralPath $src -Destination $dst -Recurse -Force
37
- OK " $([System.IO.Path]::GetFileName($src))"
93
+ OK " $(Get-RelativeLabel $dst)"
38
94
  } else {
39
- Warn " $([System.IO.Path]::GetFileName($src)) - not found, skipping"
95
+ Warn " $(Get-RelativeLabel $dst) - not found, skipping"
40
96
  }
41
97
  }
42
98
 
@@ -60,20 +116,29 @@ function Copy-Tree([string]$src, [string]$dst, [string[]]$excludeDirs = @(), [st
60
116
  $robocopyArgs += @('/NFL','/NDL','/NJH','/NJS')
61
117
  & robocopy @robocopyArgs | Out-Null
62
118
  } else {
63
- # Fallback: manual recursive copy with exclusions
64
- 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 {
65
121
  $item = $_
66
122
  $skip = $false
67
123
  if ($item.PSIsContainer -and $item.Name -in $excludeDirs) { $skip = $true }
68
124
  if (-not $item.PSIsContainer -and ($excludeFiles | Where-Object { $item.Name -like $_ })) { $skip = $true }
69
125
  if (-not $skip) {
70
- 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 }
71
129
  }
72
130
  }
73
131
  }
74
132
  }
75
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 {
76
140
  New-Item -ItemType Directory -Path $ArchiveDir -Force | Out-Null
141
+ Set-PrivateMode $ArchiveDir $true
77
142
 
78
143
  Write-Host ""
79
144
  Log "================================================================"
@@ -83,109 +148,81 @@ Log "Source: $PiRoot"
83
148
  Log "Destination: $ArchiveDir"
84
149
  Write-Host ""
85
150
 
86
- # ── 1. Core Config Files ──────────────────────────────────
87
- Log "1/8 Core configuration files..."
88
151
  $agentDir = Join-Path $PiRoot 'agent'
89
- Copy-IfExists (Join-Path $agentDir 'settings.json') (Join-Path $ArchiveDir 'settings.json')
90
- Copy-IfExists (Join-Path $agentDir 'auth.json') (Join-Path $ArchiveDir 'auth.json')
91
- Copy-IfExists (Join-Path $agentDir 'models.json') (Join-Path $ArchiveDir 'models.json')
92
- Copy-IfExists (Join-Path $agentDir 'trust.json') (Join-Path $ArchiveDir 'trust.json')
93
- Copy-IfExists (Join-Path $agentDir 'keybindings.json') (Join-Path $ArchiveDir 'keybindings.json')
94
- Copy-IfExists (Join-Path $agentDir 'pix.json') (Join-Path $ArchiveDir 'pix.json')
95
- Copy-IfExists (Join-Path $agentDir 'optimizer.json') (Join-Path $ArchiveDir 'optimizer.json')
96
- Copy-IfExists (Join-Path $agentDir 'lmstudio.json.bak') (Join-Path $ArchiveDir 'lmstudio.json.bak')
97
- Copy-IfExists (Join-Path $agentDir 'hermes-memory-config.json') (Join-Path $ArchiveDir 'hermes-memory-config.json')
98
- Copy-IfExists (Join-Path $agentDir 'pi.code-workspace') (Join-Path $ArchiveDir 'pi.code-workspace')
99
-
100
- # ── 2. Extension Configs ──────────────────────────────────
101
- Log "2/8 Extension configurations..."
102
- Copy-IfExists (Join-Path $agentDir 'pi-hermes-memory-cleanup\scoped-memory.json') (Join-Path $ArchiveDir 'pi-hermes-memory-cleanup\scoped-memory.json')
103
- Copy-IfExists (Join-Path $agentDir 'loop-police.json') (Join-Path $ArchiveDir 'loop-police.json')
104
- Copy-IfExists (Join-Path $agentDir 'pi-rtk\config.json') (Join-Path $ArchiveDir 'pi-rtk\config.json')
105
- Copy-IfExists (Join-Path $agentDir 'context-mode\config.json') (Join-Path $ArchiveDir 'context-mode\config.json')
106
- Copy-IfExists (Join-Path $agentDir 'pi-timeout\config.json') (Join-Path $ArchiveDir 'pi-timeout\config.json')
107
- Copy-IfExists (Join-Path $agentDir 'pi-context-viewer\config.json') (Join-Path $ArchiveDir 'pi-context-viewer\config.json')
108
- Copy-IfExists (Join-Path $agentDir 'pix-optimizer\config.json') (Join-Path $ArchiveDir 'pix-optimizer\config.json')
109
- Copy-IfExists (Join-Path $agentDir 'pi-nvidia-nim\config.json') (Join-Path $ArchiveDir 'pi-nvidia-nim\config.json')
110
-
111
- # ── 3. Global Skills ──────────────────────────────────────
112
- Log "3/8 Global skills..."
113
- Copy-DirIfExists (Join-Path $agentDir 'skills') (Join-Path $ArchiveDir 'skills')
114
-
115
- # ── 4. Project Skills & Memory ────────────────────────────
116
- Log "4/8 Project skills & memory..."
117
- $projMem = Join-Path $agentDir 'projects-memory'
118
- if (Test-Path -LiteralPath $projMem) {
119
- $projDst = Join-Path $ArchiveDir 'projects-memory'
120
- Copy-DirIfExists $projMem $projDst
121
- $count = @(Get-ChildItem -LiteralPath $projDst -Directory -ErrorAction SilentlyContinue).Count
122
- OK " projects-memory/ ($count projects)"
123
- } else {
124
- Warn " projects-memory/ - not found"
125
- }
126
-
127
- # ── 5. Local Extensions (source code only, no node_modules) ─
128
- Log "5/8 Local extension source code..."
129
- $localExts = @('pi-timeout', 'pi-chunk', 'pi-hermes-memory-cleanup', 'pi-context-docs')
130
- foreach ($ext in $localExts) {
131
- $src = Join-Path $LocalExtRoot $ext
132
- if (Test-Path -LiteralPath $src) {
133
- $dst = Join-Path $ArchiveDir "local-extensions\$ext"
134
- $extDstDir = Join-Path $ArchiveDir 'local-extensions'
135
- if (!(Test-Path -LiteralPath $extDstDir)) { New-Item -ItemType Directory -Path $extDstDir -Force | Out-Null }
136
- # Copy source, exclude node_modules, dist, build, .git, coverage, logs
137
- Copy-Tree $src $dst -excludeDirs @('node_modules','dist','build','coverage','.git') -excludeFiles @('*.log')
138
- OK " $ext/ (source only)"
139
- } else {
140
- Warn " $ext - not found at $LocalExtRoot/$ext"
141
- }
142
- }
143
-
144
- # ── 6. npm Extension Manifests (package.json + lock) ─────
145
- Log "6/8 npm extension manifests..."
146
- $npmDir = Join-Path $agentDir 'npm'
147
- if (Test-Path -LiteralPath $npmDir) {
148
- # Only copy package.json and lockfiles, not node_modules
149
- $manifests = Get-ChildItem -LiteralPath $npmDir -Recurse -Depth 3 -Include @('package.json','package-lock.json','npm-shrinkwrap.json','pnpm-lock.yaml') -ErrorAction SilentlyContinue
150
- foreach ($m in $manifests) {
151
- $rel = $m.FullName.Substring($npmDir.Length).TrimStart('\')
152
- $dstDir = Join-Path $ArchiveDir "npm-manifests\$($rel | Split-Path -Parent)"
153
- if (!(Test-Path -LiteralPath $dstDir)) { New-Item -ItemType Directory -Path $dstDir -Force | Out-Null }
154
- Copy-Item -LiteralPath $m.FullName -Destination (Join-Path $dstDir $m.Name) -Force
155
- }
156
- OK " npm manifests (package.json, lockfiles)"
157
- } else {
158
- Warn " npm/ - not found"
159
- }
160
-
161
- # ── 7. Hermes Memory (active files only, not sessions DB) ─
162
- Log "7/8 Hermes memory (active files)..."
163
- $hermes = Join-Path $agentDir 'pi-hermes-memory'
164
- if (Test-Path -LiteralPath $hermes) {
165
- $hermesDst = Join-Path $ArchiveDir 'pi-hermes-memory'
166
- New-Item -ItemType Directory -Path $hermesDst -Force | Out-Null
167
- foreach ($f in @('MEMORY.md','USER.md','failures.md','retired-failures.md','retired-memory.md')) {
168
- Copy-IfExists (Join-Path $hermes $f) (Join-Path $hermesDst $f)
169
- }
170
- } else {
171
- Warn " pi-hermes-memory/ - not found"
172
- }
173
-
174
- # ── 8. Recent hermes-cleanup Backups (last 5) ─────────────
175
- Log "8/8 Recent hermes-cleanup backups (last 5)..."
176
- $cleanup = Join-Path $agentDir 'hermes-cleanup'
177
- if (Test-Path -LiteralPath $cleanup) {
178
- $recent = Get-ChildItem -LiteralPath $cleanup -Directory | Where-Object { $_.Name -match '^\d{4}' } | Sort-Object Name -Descending | Select-Object -First 5
179
- foreach ($d in $recent) {
180
- 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)" }
181
219
  }
182
- } else {
183
- Warn " hermes-cleanup/ - not found"
184
220
  }
185
221
 
186
222
  # ── Manifest ──────────────────────────────────────────────
187
223
  Log "Creating manifest..."
188
- $piVersion = (& pi --version 2>$null) -join ''
224
+ $piVersion = ''
225
+ try { $piVersion = (& pi --version 2>$null) -join '' } catch { $piVersion = '' }
189
226
  if (-not $piVersion) { $piVersion = 'unknown' }
190
227
  $manifest = @"
191
228
  Pi Complete Backup Manifest
@@ -202,8 +239,7 @@ $relFiles = Get-ChildItem -LiteralPath $ArchiveDir -Recurse -File | ForEach-Obje
202
239
  $manifest += ($relFiles -join "`n") + "`n"
203
240
  Set-Content -LiteralPath (Join-Path $ArchiveDir 'MANIFEST.txt') -Value $manifest -Encoding UTF8
204
241
 
205
- # ── 9. Compress ───────────────────────────────────────────
206
- $archivePath = $null
242
+ # ── 9. Compress (external backups only) ───────────────────
207
243
  if ($KeepUncompressed) {
208
244
  Log "9/9 Skipping compression for internal backup"
209
245
  } else {
@@ -211,23 +247,30 @@ if ($KeepUncompressed) {
211
247
  $archivePath = Join-Path $BackupRoot ($ArchiveBase + ".$ArchiveExtension")
212
248
  try {
213
249
  if ($SevenZip) {
214
- & $SevenZip.Source a -t7z -mx=9 $archivePath $ArchiveDir | Out-Null
215
- 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())" }
216
260
  } else {
217
261
  Compress-Archive -LiteralPath $ArchiveDir -DestinationPath $archivePath -CompressionLevel Optimal -Force
218
262
  }
263
+ Set-PrivateMode $archivePath
219
264
  OK " $archivePath"
220
265
  } catch {
221
- Warn " Compress-Archive failed: $_.Exception.Message"
266
+ Warn " Compression ($ArchiveExtension) failed: $($_.Exception.Message)"
222
267
  Warn " Keeping uncompressed staging dir: $ArchiveDir"
268
+ if (Test-Path -LiteralPath $archivePath) { Remove-Item -LiteralPath $archivePath -Force -ErrorAction SilentlyContinue }
223
269
  $archivePath = $null
270
+ $KeepStagingOnFail = $true
271
+ exit 1
224
272
  }
225
- }
226
-
227
- # ── 10. Clean up staging dir (unless told to keep it) ─────
228
- if ($KeepUncompressed) {
229
- Log "Keeping uncompressed staging dir: $ArchiveDir"
230
- } elseif ($archivePath) {
273
+ # ── 10. Clean up staging dir ──────────────────────────
231
274
  Remove-Item -LiteralPath $ArchiveDir -Recurse -Force
232
275
  }
233
276
 
@@ -235,12 +278,22 @@ if ($KeepUncompressed) {
235
278
  Write-Host ""
236
279
  Log "================================================================"
237
280
  OK "Backup complete!"
238
- if ($archivePath) {
281
+ if ($KeepUncompressed) {
282
+ $result = $ArchiveDir
283
+ Log "Staging: $ArchiveDir"
284
+ } else {
285
+ $result = $archivePath
239
286
  Log "Archive: $archivePath"
240
287
  Log "Size: $([math]::Round((Get-Item -LiteralPath $archivePath).Length / 1MB, 1)) MB"
241
288
  }
242
- if ($KeepUncompressed) { Log "Staging: $ArchiveDir" }
243
289
  Write-Host ""
244
290
  Log "To restore after reinstall:"
245
- Log " .\restore-pi.ps1 $archivePath"
291
+ Log " .\restore-pi.ps1 $result"
246
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
+ }