@jamiefutch/pi-backup 1.1.6 → 1.1.7

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
@@ -11,7 +11,7 @@ Complete backup/restore for Pi coding agent. Backs up **everything** needed to r
11
11
  pi install npm:@jamiefutch/pi-backup@latest
12
12
 
13
13
  # From git
14
- pi install git:github.com/jamiefutch/pi-backup@main
14
+ pi install git:github.com/jamiefutch/pi-backup@master
15
15
 
16
16
  # From local path
17
17
  pi install /path/to/pi-backup
@@ -0,0 +1 @@
1
+ export { default as piBackupManager } from "./pi-backup-manager.js";
@@ -0,0 +1,566 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { execSync } from "node:child_process";
3
+ import { join, dirname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, writeFileSync, rmSync, cpSync } from "node:fs";
6
+
7
+ const PI_ROOT = join(process.env.HOME || "", ".pi");
8
+ const INTERNAL_BACKUP_DIR = join(PI_ROOT, "backups");
9
+ const SETTINGS_FILE = join(PI_ROOT, "agent", "settings.json");
10
+ const DEFAULT_EXTERNAL_DIR = join(process.env.HOME || "", "projects", "personal", "pi-utils", "backups");
11
+ const PACKAGE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
12
+
13
+ interface BackupInfo {
14
+ name: string;
15
+ path: string;
16
+ timestamp: string;
17
+ size: string;
18
+ files: number;
19
+ isCompressed: boolean;
20
+ location: "internal" | "external";
21
+ }
22
+
23
+ function readSettings(): any {
24
+ try {
25
+ if (existsSync(SETTINGS_FILE)) {
26
+ return JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
27
+ }
28
+ } catch {}
29
+ return {};
30
+ }
31
+
32
+ function writeSettings(settings: any): void {
33
+ mkdirSync(dirname(SETTINGS_FILE), { recursive: true });
34
+ writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2), "utf-8");
35
+ }
36
+
37
+ function getExternalBackupDir(ctx?: any): string {
38
+ // 1. Environment variable (highest priority)
39
+ if (process.env.BACKUP_ROOT) {
40
+ return process.env.BACKUP_ROOT;
41
+ }
42
+
43
+ // 2. settings.json
44
+ const settings = readSettings();
45
+ if (settings.externalBackupDir) {
46
+ return settings.externalBackupDir;
47
+ }
48
+
49
+ // 3. Default fallback
50
+ return DEFAULT_EXTERNAL_DIR;
51
+ }
52
+
53
+ async function promptForExternalBackupDir(ctx: any): Promise<string | null> {
54
+ const currentDefault = getExternalBackupDir();
55
+ const source = process.env.BACKUP_ROOT ? "BACKUP_ROOT env var"
56
+ : readSettings().externalBackupDir ? "settings.json"
57
+ : "default";
58
+ const input = await ctx.ui.input(
59
+ `Configure external backup directory\n\nCurrent: ${currentDefault}\nSource: ${source}\n\nEnter a new path or press Enter to keep the current value:`,
60
+ currentDefault,
61
+ );
62
+
63
+ if (input === undefined) return null; // User cancelled
64
+
65
+ const chosenPath = input.trim() || currentDefault;
66
+
67
+ // Save to settings.json
68
+ const settings = readSettings();
69
+ settings.externalBackupDir = chosenPath;
70
+ writeSettings(settings);
71
+ ctx.ui.notify(`Saved external backup directory to settings.json:\n${chosenPath}`, "info");
72
+
73
+ // Ensure directory exists
74
+ mkdirSync(chosenPath, { recursive: true });
75
+
76
+ return chosenPath;
77
+ }
78
+
79
+ function resolveExternalBackupDir(ctx?: any): string {
80
+ return getExternalBackupDir(ctx);
81
+ }
82
+
83
+ function getBackupScriptPath(): string {
84
+ return join(PACKAGE_ROOT, "backup-pi.sh");
85
+ }
86
+
87
+ function getRestoreScriptPath(): string {
88
+ return join(PACKAGE_ROOT, "restore-pi.sh");
89
+ }
90
+
91
+ function ensureDirs(externalDir: string) {
92
+ if (!existsSync(INTERNAL_BACKUP_DIR)) mkdirSync(INTERNAL_BACKUP_DIR, { recursive: true });
93
+ if (!existsSync(externalDir)) mkdirSync(externalDir, { recursive: true });
94
+ }
95
+
96
+ function parseTimestamp(name: string): string {
97
+ const match = name.match(/pi-backup-(\d{8}-\d{6})/);
98
+ return match ? match[1] : "unknown";
99
+ }
100
+
101
+ function formatTimestamp(ts: string): string {
102
+ if (ts === "unknown") return "unknown";
103
+ return `${ts.slice(0,4)}-${ts.slice(4,6)}-${ts.slice(6,8)} ${ts.slice(9,11)}:${ts.slice(11,13)}:${ts.slice(13,15)}`;
104
+ }
105
+
106
+ function getDirSize(path: string): { size: string; files: number } {
107
+ let totalSize = 0;
108
+ let fileCount = 0;
109
+ try {
110
+ const entries = readdirSync(path, { withFileTypes: true });
111
+ for (const entry of entries) {
112
+ const full = join(path, entry.name);
113
+ if (entry.isDirectory()) {
114
+ const sub = getDirSize(full);
115
+ totalSize += parseSize(sub.size);
116
+ fileCount += sub.files;
117
+ } else {
118
+ const stat = statSync(full);
119
+ totalSize += stat.size;
120
+ fileCount++;
121
+ }
122
+ }
123
+ } catch {}
124
+ return { size: formatBytes(totalSize), files: fileCount };
125
+ }
126
+
127
+ function getFileSize(path: string): { size: string; files: number } {
128
+ try {
129
+ const stat = statSync(path);
130
+ return { size: formatBytes(stat.size), files: 1 };
131
+ } catch {
132
+ return { size: "0 B", files: 0 };
133
+ }
134
+ }
135
+
136
+ function parseSize(str: string): number {
137
+ const match = str.match(/^([\d.]+)\s*(\w+)$/);
138
+ if (!match) return 0;
139
+ const num = parseFloat(match[1]);
140
+ const unit = match[2].toUpperCase();
141
+ const multipliers: Record<string, number> = { B: 1, KB: 1024, MB: 1024**2, GB: 1024**3, TB: 1024**4 };
142
+ return num * (multipliers[unit] || 1);
143
+ }
144
+
145
+ function formatBytes(bytes: number): string {
146
+ if (bytes === 0) return "0 B";
147
+ const k = 1024;
148
+ const sizes = ["B", "KB", "MB", "GB", "TB"];
149
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
150
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
151
+ }
152
+
153
+ function discoverBackups(ctx?: any): BackupInfo[] {
154
+ const externalDir = resolveExternalBackupDir(ctx);
155
+ ensureDirs(externalDir);
156
+ const backups: BackupInfo[] = [];
157
+
158
+ if (existsSync(INTERNAL_BACKUP_DIR)) {
159
+ for (const entry of readdirSync(INTERNAL_BACKUP_DIR, { withFileTypes: true })) {
160
+ if (entry.isDirectory() && entry.name.startsWith("pi-backup-")) {
161
+ const path = join(INTERNAL_BACKUP_DIR, entry.name);
162
+ const { size, files } = getDirSize(path);
163
+ backups.push({
164
+ name: entry.name,
165
+ path,
166
+ timestamp: parseTimestamp(entry.name),
167
+ size,
168
+ files,
169
+ isCompressed: false,
170
+ location: "internal",
171
+ });
172
+ }
173
+ }
174
+ }
175
+
176
+ if (existsSync(externalDir)) {
177
+ for (const entry of readdirSync(externalDir, { withFileTypes: true })) {
178
+ if (entry.name.startsWith("pi-backup-")) {
179
+ const path = join(externalDir, entry.name);
180
+ const isCompressed = entry.name.endsWith(".zip") || entry.name.endsWith(".7z");
181
+ const { size, files } = isCompressed ? getFileSize(path) : getDirSize(path);
182
+ backups.push({
183
+ name: entry.name,
184
+ path,
185
+ timestamp: parseTimestamp(entry.name),
186
+ size,
187
+ files,
188
+ isCompressed,
189
+ location: "external",
190
+ });
191
+ }
192
+ }
193
+ }
194
+
195
+ return backups.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
196
+ }
197
+
198
+ function runBackup(internal: boolean, ctx?: any): { success: boolean; output: string; backupPath?: string } {
199
+ try {
200
+ const externalDir = resolveExternalBackupDir(ctx);
201
+ const env = { ...process.env };
202
+ if (internal) {
203
+ env.BACKUP_ROOT = INTERNAL_BACKUP_DIR;
204
+ env.KEEP_UNCOMPRESSED = "1"; // keep staging dir for fast rollback
205
+ } else {
206
+ env.BACKUP_ROOT = externalDir;
207
+ env.KEEP_UNCOMPRESSED = "0"; // external: compressed archive only
208
+ }
209
+ const output = execSync(getBackupScriptPath(), { env, encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
210
+ const match = output.match(/Staging:\s+(.+)$/m) || output.match(/Archive:\s+(.+)$/m);
211
+ const backupPath = match ? match[1].trim() : undefined;
212
+ return { success: true, output, backupPath };
213
+ } catch (e: any) {
214
+ return { success: false, output: e.stdout || e.stderr || e.message };
215
+ }
216
+ }
217
+
218
+ function runRestore(backupPath: string): { success: boolean; output: string } {
219
+ try {
220
+ const output = execSync(`${getRestoreScriptPath()} "${backupPath}"`, { encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
221
+ return { success: true, output };
222
+ } catch (e: any) {
223
+ return { success: false, output: e.stdout || e.stderr || e.message };
224
+ }
225
+ }
226
+
227
+ function copyBackupToInternal(backup: BackupInfo): { success: boolean; output: string } {
228
+ if (backup.location === "internal") return { success: true, output: "Already in internal storage" };
229
+ try {
230
+ const destName = backup.name;
231
+ const destPath = join(INTERNAL_BACKUP_DIR, destName);
232
+ if (backup.isCompressed) {
233
+ const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-${Date.now()}`);
234
+ mkdirSync(tmpDir, { recursive: true });
235
+ if (backup.name.endsWith(".zip")) {
236
+ execSync(`unzip -q "${backup.path}" -d "${tmpDir}"`);
237
+ } else {
238
+ execSync(`7z x -o"${tmpDir}" "${backup.path}" >/dev/null`);
239
+ }
240
+ const extracted = readdirSync(tmpDir)[0];
241
+ cpSync(join(tmpDir, extracted), destPath, { recursive: true });
242
+ rmSync(tmpDir, { recursive: true, force: true });
243
+ } else {
244
+ cpSync(backup.path, destPath, { recursive: true });
245
+ }
246
+ return { success: true, output: `Copied to ${destPath}` };
247
+ } catch (e: any) {
248
+ return { success: false, output: e.message };
249
+ }
250
+ }
251
+
252
+ function deleteBackup(backup: BackupInfo): { success: boolean; output: string } {
253
+ try {
254
+ rmSync(backup.path, { recursive: true, force: true });
255
+ return { success: true, output: `Deleted ${backup.name}` };
256
+ } catch (e: any) {
257
+ return { success: false, output: e.message };
258
+ }
259
+ }
260
+
261
+ function formatBackupLine(b: BackupInfo): string {
262
+ const locIcon = b.location === "internal" ? "📁" : "💾";
263
+ const comp = b.isCompressed ? " • compressed" : "";
264
+ return `${locIcon} ${b.name} │ ${formatTimestamp(b.timestamp)} │ ${b.size} │ ${b.files} files${comp}`;
265
+ }
266
+
267
+ function findFile(dir: string, name: string): string | null {
268
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
269
+ const full = join(dir, entry.name);
270
+ if (entry.isDirectory()) {
271
+ const found = findFile(full, name);
272
+ if (found) return found;
273
+ } else if (entry.name === name) {
274
+ return full;
275
+ }
276
+ }
277
+ return null;
278
+ }
279
+
280
+ export default function piBackupManagerExtension(pi: ExtensionAPI) {
281
+ console.error("[pi-backup-manager] Extension loaded");
282
+ pi.registerCommand("pi-backup", {
283
+ description: "Manage Pi backups - create, restore, view, copy, delete",
284
+ handler: async (_args, ctx) => {
285
+ if (ctx.mode !== "tui") {
286
+ ctx.ui.notify("Backup manager only available in TUI mode", "error");
287
+ return;
288
+ }
289
+ await showMainMenu(ctx);
290
+ },
291
+ });
292
+ }
293
+
294
+ async function showMainMenu(ctx: any) {
295
+ while (true) {
296
+ const externalDir = resolveExternalBackupDir(ctx);
297
+ const backups = discoverBackups(ctx);
298
+ const internalCount = backups.filter(b => b.location === "internal").length;
299
+ const externalCount = backups.filter(b => b.location === "external").length;
300
+
301
+ const choice = await ctx.ui.select(
302
+ `Pi Backup Manager — ${backups.length} backups (${internalCount} internal, ${externalCount} external)\nExternal dir: ${externalDir}`,
303
+ [
304
+ "📦 Create internal backup (~/.pi/backups/ — quick rollback)",
305
+ "💾 Create external backup (survives reinstall)",
306
+ "📋 List all backups",
307
+ "⚙️ Configure external backup directory",
308
+ "❓ Help",
309
+ "← Exit",
310
+ ],
311
+ );
312
+
313
+ if (!choice || choice.startsWith("←")) return;
314
+
315
+ if (choice.startsWith("📦")) await createBackup(ctx, true);
316
+ else if (choice.startsWith("💾")) await createBackup(ctx, false);
317
+ else if (choice.startsWith("📋")) await showBackupList(ctx);
318
+ else if (choice.startsWith("⚙️")) await configureExternalDir(ctx);
319
+ else if (choice.startsWith("❓")) await showHelp(ctx);
320
+ }
321
+ }
322
+
323
+ async function createBackup(ctx: any, internal: boolean) {
324
+ // For external backup, ensure directory is configured.
325
+ // Only prompt if no env/settings value AND the default dir is empty/missing.
326
+ if (!internal) {
327
+ const externalDir = getExternalBackupDir(ctx);
328
+ const settings = readSettings();
329
+ const explicitlyConfigured = process.env.BACKUP_ROOT || settings.externalBackupDir;
330
+ const defaultHasContent = existsSync(externalDir) && readdirSync(externalDir).length > 0;
331
+ if (!explicitlyConfigured && !defaultHasContent) {
332
+ const configured = await promptForExternalBackupDir(ctx);
333
+ if (!configured) return;
334
+ }
335
+ }
336
+
337
+ ctx.ui.notify(`Creating ${internal ? "internal" : "external"} backup...`, "info");
338
+ const result = runBackup(internal, ctx);
339
+ if (result.success) {
340
+ ctx.ui.notify(`Backup created successfully${result.backupPath ? `\n${result.backupPath}` : ""}`, "info");
341
+ } else {
342
+ ctx.ui.notify(`Backup failed:\n${result.output}`, "error");
343
+ }
344
+ }
345
+
346
+ async function showBackupList(ctx: any) {
347
+ let backups = discoverBackups(ctx);
348
+ if (backups.length === 0) {
349
+ ctx.ui.notify("No backups found", "info");
350
+ return;
351
+ }
352
+
353
+ while (true) {
354
+ const lines = backups.map(formatBackupLine);
355
+ lines.push("🔄 Refresh");
356
+ lines.push("← Back");
357
+
358
+ const selected = await ctx.ui.select(`Backups (${backups.length} total)`, lines);
359
+ if (!selected || selected.startsWith("←")) return;
360
+ if (selected.startsWith("🔄")) { backups = discoverBackups(ctx); continue; }
361
+
362
+ const backup = backups.find(b => selected.includes(b.name));
363
+ if (!backup) continue;
364
+
365
+ await showBackupActions(ctx, backup);
366
+ backups = discoverBackups(ctx);
367
+ }
368
+ }
369
+
370
+ async function showBackupActions(ctx: any, backup: BackupInfo) {
371
+ const isInternal = backup.location === "internal";
372
+ const actions = [
373
+ `🔄 Restore this backup (${formatTimestamp(backup.timestamp)})`,
374
+ ];
375
+
376
+ if (!isInternal) {
377
+ actions.push("📋 Copy to internal (~/.pi/backups/)");
378
+ }
379
+
380
+ actions.push(
381
+ "📄 View manifest",
382
+ "🗑️ Delete",
383
+ "← Back",
384
+ );
385
+
386
+ const choice = await ctx.ui.select(`Backup: ${backup.name}`, actions);
387
+ if (!choice || choice.startsWith("←")) return;
388
+
389
+ if (choice.startsWith("🔄")) await confirmRestore(ctx, backup);
390
+ else if (choice.startsWith("📋")) {
391
+ const result = copyBackupToInternal(backup);
392
+ ctx.ui.notify(result.success ? result.output : `Failed: ${result.output}`, result.success ? "info" : "error");
393
+ } else if (choice.startsWith("📄")) await viewManifest(ctx, backup);
394
+ else if (choice.startsWith("🗑️")) await confirmDelete(ctx, backup);
395
+ }
396
+
397
+ async function confirmRestore(ctx: any, backup: BackupInfo) {
398
+ // Restore uses the backup's direct path, so no directory config is needed here.
399
+ const confirmed = await ctx.ui.confirm(
400
+ `Restore ${backup.name}?`,
401
+ `⚠️ This will OVERWRITE all current Pi configuration!\n` +
402
+ `Backup: ${formatTimestamp(backup.timestamp)} • ${backup.size} • ${backup.files} files\n` +
403
+ `Pi must NOT be running during restore.\n\n` +
404
+ `Are you sure?`,
405
+ );
406
+ if (!confirmed) return;
407
+
408
+ ctx.ui.notify("Restoring... (this may take a moment)", "info");
409
+ const result = runRestore(backup.path);
410
+ if (result.success) {
411
+ ctx.ui.notify("Restore complete!\n\nNext steps:\n1. cd ~/.pi/agent && npm install\n2. pi --version\n3. /ctx-doctor", "info");
412
+ } else {
413
+ ctx.ui.notify(`Restore failed:\n${result.output}`, "error");
414
+ }
415
+ }
416
+
417
+ async function confirmDelete(ctx: any, backup: BackupInfo) {
418
+ const confirmed = await ctx.ui.confirm(
419
+ `Delete ${backup.name}?`,
420
+ `This cannot be undone.\n${formatTimestamp(backup.timestamp)} • ${backup.size} • ${backup.files} files`,
421
+ );
422
+ if (!confirmed) return;
423
+
424
+ const result = deleteBackup(backup);
425
+ ctx.ui.notify(result.success ? result.output : `Failed: ${result.output}`, result.success ? "info" : "error");
426
+ }
427
+
428
+ async function viewManifest(ctx: any, backup: BackupInfo) {
429
+ let manifestPath: string;
430
+ if (backup.isCompressed) {
431
+ const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-manifest-${Date.now()}`);
432
+ mkdirSync(tmpDir, { recursive: true });
433
+ try {
434
+ if (backup.name.endsWith(".zip")) {
435
+ execSync(`unzip -q "${backup.path}" "*/MANIFEST.txt" -d "${tmpDir}"`);
436
+ } else {
437
+ execSync(`7z x -o"${tmpDir}" "${backup.path}" "*/MANIFEST.txt" >/dev/null`);
438
+ }
439
+ const found = findFile(tmpDir, "MANIFEST.txt");
440
+ if (found) manifestPath = found;
441
+ else throw new Error("MANIFEST.txt not found in archive");
442
+ } catch (e: any) {
443
+ ctx.ui.notify(`Failed to extract manifest: ${e.message}`, "error");
444
+ rmSync(tmpDir, { recursive: true, force: true });
445
+ return;
446
+ }
447
+ rmSync(tmpDir, { recursive: true, force: true });
448
+ } else {
449
+ manifestPath = join(backup.path, "MANIFEST.txt");
450
+ }
451
+
452
+ if (!existsSync(manifestPath)) {
453
+ ctx.ui.notify("No manifest found in backup", "warning");
454
+ return;
455
+ }
456
+
457
+ const content = readFileSync(manifestPath, "utf-8");
458
+ await ctx.ui.editor(`MANIFEST — ${backup.name}`, content);
459
+ }
460
+
461
+ async function configureExternalDir(ctx: any) {
462
+ const current = getExternalBackupDir(ctx);
463
+ const source = process.env.BACKUP_ROOT ? "environment variable (BACKUP_ROOT)"
464
+ : readSettings().externalBackupDir ? "settings.json"
465
+ : "default (not yet saved)";
466
+
467
+ const choice = await ctx.ui.select(
468
+ `Current external backup directory:\n${current}\n\nSource: ${source}`,
469
+ [
470
+ "📝 Change directory",
471
+ "🔄 Reset to default",
472
+ "← Back",
473
+ ],
474
+ );
475
+
476
+ if (!choice || choice.startsWith("←")) return;
477
+
478
+ if (choice.startsWith("📝")) {
479
+ await promptForExternalBackupDir(ctx);
480
+ } else if (choice.startsWith("🔄")) {
481
+ const settings = readSettings();
482
+ delete settings.externalBackupDir;
483
+ writeSettings(settings);
484
+ ctx.ui.notify("Reset to default. Will use environment variable or default path.", "info");
485
+ }
486
+ }
487
+
488
+ async function showHelp(ctx: any) {
489
+ const externalDir = resolveExternalBackupDir(ctx);
490
+ const help = `# Pi Backup Manager Help
491
+
492
+ ## Backup Locations
493
+
494
+ ### 📁 Internal (~/.pi/backups/)
495
+ - **Purpose**: Quick rollback during normal use
496
+ - **Survives**: Pi updates, extension installs, config changes
497
+ - **Does NOT survive**: Clean reinstall (\`rm -rf ~/.pi\`)
498
+ - **Format**: Uncompressed directories (fast access)
499
+
500
+ ### 💾 External (${externalDir})
501
+ - **Purpose**: Disaster recovery
502
+ - **Survives**: Clean reinstall, disk failure (if copied elsewhere)
503
+ - **Does NOT survive**: Deleting the backup directory
504
+ - **Format**: Compressed archives (.7z/.zip) + optional uncompressed
505
+
506
+ ## Configuration Priority
507
+
508
+ The external backup directory is resolved in this order:
509
+
510
+ 1. **BACKUP_ROOT** environment variable (highest priority)
511
+ 2. **settings.json** → \`externalBackupDir\`
512
+ 3. **Default**: \`~/projects/personal/pi-utils/backups/\`
513
+
514
+ Use **⚙️ Configure external backup directory** in the main menu to change the settings.json value.
515
+
516
+ ## When to Use Which
517
+
518
+ | Scenario | Recommended |
519
+ |----------|-------------|
520
+ | Before installing risky extension | Internal |
521
+ | Before changing config files | Internal |
522
+ | Before Pi update | Both |
523
+ | Before clean reinstall | **External (required)** |
524
+ | Moving to new machine | External |
525
+
526
+ ## Restore Process
527
+
528
+ 1. Select backup → Restore
529
+ 2. Script overwrites all config in \`~/.pi/agent/\`
530
+ 3. **After restore**: Run \`cd ~/.pi/agent && npm install\`
531
+ 4. Verify: \`pi --version\`, \`/ctx-doctor\`
532
+
533
+ ## Manual Backup/Restore
534
+
535
+ \`\`\`bash
536
+ # Create external backup (uses BACKUP_ROOT or default)
537
+ ~/projects/personal/pi-backup/backup-pi.sh
538
+
539
+ # Override backup location
540
+ BACKUP_ROOT=/mnt/backups ~/projects/personal/pi-backup/backup-pi.sh
541
+
542
+ # Restore from external
543
+ ~/projects/personal/pi-backup/restore-pi.sh ~/projects/personal/pi-utils/backups/pi-backup-20260811-143000
544
+ \`\`\`
545
+
546
+ ## What Gets Backed Up
547
+
548
+ ✅ settings.json, auth.json, models.json, trust.json, keybindings.json
549
+ ✅ All extension configs (loop-police, context-mode, hermes-memory, etc.)
550
+ ✅ Global skills (\`~/.pi/agent/skills/\`)
551
+ ✅ Project skills & memory (\`~/.pi/agent/projects-memory/\`)
552
+ ✅ Local extension source code (pi-timeout, pi-chunk, etc.)
553
+ ✅ npm manifests (package.json, lockfiles)
554
+ ✅ Hermes memory files (MEMORY.md, USER.md, failures.md)
555
+ ✅ Recent hermes-cleanup backups
556
+
557
+ ## What Does NOT Get Backed Up (Regeneratable)
558
+
559
+ ❌ Sessions (\`~/.pi/agent/sessions/\`)
560
+ ❌ Context-mode KB (\`context-mode/kb.sqlite\`)
561
+ ❌ node_modules/
562
+ ❌ loop-police-detections.jsonl
563
+ ❌ Lock files`;
564
+
565
+ await ctx.ui.editor("Pi Backup Manager Help", help);
566
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jamiefutch/pi-backup",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "description": "Pi package: Pi backup/restore scripts and TUI extension. Back up and restore all Pi config, skills, extensions, and memory; /pi-backup interactive manager.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -9,7 +9,10 @@
9
9
  },
10
10
  "keywords": [
11
11
  "pi",
12
- "pi-package"
12
+ "pi-package",
13
+ "pi-extension",
14
+ "backup",
15
+ "restore"
13
16
  ],
14
17
  "license": "MIT",
15
18
  "repository": {
@@ -24,7 +27,7 @@
24
27
  "node": ">=22"
25
28
  },
26
29
  "files": [
27
- "dist",
30
+ "extensions",
28
31
  "*.sh",
29
32
  "*.ps1",
30
33
  "LICENSE",
@@ -32,7 +35,7 @@
32
35
  ],
33
36
  "pi": {
34
37
  "extensions": [
35
- "./dist/extensions/pi-backup-manager.js"
38
+ "./extensions/pi-backup-manager.ts"
36
39
  ]
37
40
  },
38
41
  "peerDependencies": {
@@ -43,5 +46,8 @@
43
46
  "@types/node": "^22.0.0",
44
47
  "typescript": "^5.6.0"
45
48
  },
46
- "dependencies": {}
49
+ "dependencies": {},
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
47
53
  }
@@ -1,2 +0,0 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- export default function piBackupManagerExtension(pi: ExtensionAPI): void;
@@ -1,521 +0,0 @@
1
- import { execSync } from "node:child_process";
2
- import { join, dirname } from "node:path";
3
- import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, writeFileSync, rmSync, cpSync } from "node:fs";
4
- const PI_ROOT = join(process.env.HOME || "", ".pi");
5
- const INTERNAL_BACKUP_DIR = join(PI_ROOT, "backups");
6
- const SETTINGS_FILE = join(PI_ROOT, "agent", "settings.json");
7
- const DEFAULT_EXTERNAL_DIR = join(process.env.HOME || "", "projects", "personal", "pi-utils", "backups");
8
- const PI_UTILS_ROOT = join(process.env.HOME || "", "projects", "personal", "pi-backup");
9
- function readSettings() {
10
- try {
11
- if (existsSync(SETTINGS_FILE)) {
12
- return JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
13
- }
14
- }
15
- catch { }
16
- return {};
17
- }
18
- function writeSettings(settings) {
19
- mkdirSync(dirname(SETTINGS_FILE), { recursive: true });
20
- writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2), "utf-8");
21
- }
22
- function getExternalBackupDir(ctx) {
23
- // 1. Environment variable (highest priority)
24
- if (process.env.BACKUP_ROOT) {
25
- return process.env.BACKUP_ROOT;
26
- }
27
- // 2. settings.json
28
- const settings = readSettings();
29
- if (settings.externalBackupDir) {
30
- return settings.externalBackupDir;
31
- }
32
- // 3. Default fallback
33
- return DEFAULT_EXTERNAL_DIR;
34
- }
35
- async function promptForExternalBackupDir(ctx) {
36
- const currentDefault = getExternalBackupDir();
37
- const source = process.env.BACKUP_ROOT ? "BACKUP_ROOT env var"
38
- : readSettings().externalBackupDir ? "settings.json"
39
- : "default";
40
- const input = await ctx.ui.input(`Configure external backup directory\n\nCurrent: ${currentDefault}\nSource: ${source}\n\nEnter a new path or press Enter to keep the current value:`, currentDefault);
41
- if (input === undefined)
42
- return null; // User cancelled
43
- const chosenPath = input.trim() || currentDefault;
44
- // Save to settings.json
45
- const settings = readSettings();
46
- settings.externalBackupDir = chosenPath;
47
- writeSettings(settings);
48
- ctx.ui.notify(`Saved external backup directory to settings.json:\n${chosenPath}`, "info");
49
- // Ensure directory exists
50
- mkdirSync(chosenPath, { recursive: true });
51
- return chosenPath;
52
- }
53
- function resolveExternalBackupDir(ctx) {
54
- return getExternalBackupDir(ctx);
55
- }
56
- function getBackupScriptPath() {
57
- return join(PI_UTILS_ROOT, "backup-pi.sh");
58
- }
59
- function getRestoreScriptPath() {
60
- return join(PI_UTILS_ROOT, "restore-pi.sh");
61
- }
62
- function ensureDirs(externalDir) {
63
- if (!existsSync(INTERNAL_BACKUP_DIR))
64
- mkdirSync(INTERNAL_BACKUP_DIR, { recursive: true });
65
- if (!existsSync(externalDir))
66
- mkdirSync(externalDir, { recursive: true });
67
- }
68
- function parseTimestamp(name) {
69
- const match = name.match(/pi-backup-(\d{8}-\d{6})/);
70
- return match ? match[1] : "unknown";
71
- }
72
- function formatTimestamp(ts) {
73
- if (ts === "unknown")
74
- return "unknown";
75
- return `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)} ${ts.slice(9, 11)}:${ts.slice(11, 13)}:${ts.slice(13, 15)}`;
76
- }
77
- function getDirSize(path) {
78
- let totalSize = 0;
79
- let fileCount = 0;
80
- try {
81
- const entries = readdirSync(path, { withFileTypes: true });
82
- for (const entry of entries) {
83
- const full = join(path, entry.name);
84
- if (entry.isDirectory()) {
85
- const sub = getDirSize(full);
86
- totalSize += parseSize(sub.size);
87
- fileCount += sub.files;
88
- }
89
- else {
90
- const stat = statSync(full);
91
- totalSize += stat.size;
92
- fileCount++;
93
- }
94
- }
95
- }
96
- catch { }
97
- return { size: formatBytes(totalSize), files: fileCount };
98
- }
99
- function getFileSize(path) {
100
- try {
101
- const stat = statSync(path);
102
- return { size: formatBytes(stat.size), files: 1 };
103
- }
104
- catch {
105
- return { size: "0 B", files: 0 };
106
- }
107
- }
108
- function parseSize(str) {
109
- const match = str.match(/^([\d.]+)\s*(\w+)$/);
110
- if (!match)
111
- return 0;
112
- const num = parseFloat(match[1]);
113
- const unit = match[2].toUpperCase();
114
- const multipliers = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
115
- return num * (multipliers[unit] || 1);
116
- }
117
- function formatBytes(bytes) {
118
- if (bytes === 0)
119
- return "0 B";
120
- const k = 1024;
121
- const sizes = ["B", "KB", "MB", "GB", "TB"];
122
- const i = Math.floor(Math.log(bytes) / Math.log(k));
123
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
124
- }
125
- function discoverBackups(ctx) {
126
- const externalDir = resolveExternalBackupDir(ctx);
127
- ensureDirs(externalDir);
128
- const backups = [];
129
- if (existsSync(INTERNAL_BACKUP_DIR)) {
130
- for (const entry of readdirSync(INTERNAL_BACKUP_DIR, { withFileTypes: true })) {
131
- if (entry.isDirectory() && entry.name.startsWith("pi-backup-")) {
132
- const path = join(INTERNAL_BACKUP_DIR, entry.name);
133
- const { size, files } = getDirSize(path);
134
- backups.push({
135
- name: entry.name,
136
- path,
137
- timestamp: parseTimestamp(entry.name),
138
- size,
139
- files,
140
- isCompressed: false,
141
- location: "internal",
142
- });
143
- }
144
- }
145
- }
146
- if (existsSync(externalDir)) {
147
- for (const entry of readdirSync(externalDir, { withFileTypes: true })) {
148
- if (entry.name.startsWith("pi-backup-")) {
149
- const path = join(externalDir, entry.name);
150
- const isCompressed = entry.name.endsWith(".zip") || entry.name.endsWith(".7z");
151
- const { size, files } = isCompressed ? getFileSize(path) : getDirSize(path);
152
- backups.push({
153
- name: entry.name,
154
- path,
155
- timestamp: parseTimestamp(entry.name),
156
- size,
157
- files,
158
- isCompressed,
159
- location: "external",
160
- });
161
- }
162
- }
163
- }
164
- return backups.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
165
- }
166
- function runBackup(internal, ctx) {
167
- try {
168
- const externalDir = resolveExternalBackupDir(ctx);
169
- const env = { ...process.env };
170
- if (internal) {
171
- env.BACKUP_ROOT = INTERNAL_BACKUP_DIR;
172
- env.KEEP_UNCOMPRESSED = "1"; // keep staging dir for fast rollback
173
- }
174
- else {
175
- env.BACKUP_ROOT = externalDir;
176
- env.KEEP_UNCOMPRESSED = "0"; // external: compressed archive only
177
- }
178
- const output = execSync(getBackupScriptPath(), { env, encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
179
- const match = output.match(/Staging:\s+(.+)$/m) || output.match(/Archive:\s+(.+)$/m);
180
- const backupPath = match ? match[1].trim() : undefined;
181
- return { success: true, output, backupPath };
182
- }
183
- catch (e) {
184
- return { success: false, output: e.stdout || e.stderr || e.message };
185
- }
186
- }
187
- function runRestore(backupPath) {
188
- try {
189
- const output = execSync(`${getRestoreScriptPath()} "${backupPath}"`, { encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
190
- return { success: true, output };
191
- }
192
- catch (e) {
193
- return { success: false, output: e.stdout || e.stderr || e.message };
194
- }
195
- }
196
- function copyBackupToInternal(backup) {
197
- if (backup.location === "internal")
198
- return { success: true, output: "Already in internal storage" };
199
- try {
200
- const destName = backup.name;
201
- const destPath = join(INTERNAL_BACKUP_DIR, destName);
202
- if (backup.isCompressed) {
203
- const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-${Date.now()}`);
204
- mkdirSync(tmpDir, { recursive: true });
205
- if (backup.name.endsWith(".zip")) {
206
- execSync(`unzip -q "${backup.path}" -d "${tmpDir}"`);
207
- }
208
- else {
209
- execSync(`7z x -o"${tmpDir}" "${backup.path}" >/dev/null`);
210
- }
211
- const extracted = readdirSync(tmpDir)[0];
212
- cpSync(join(tmpDir, extracted), destPath, { recursive: true });
213
- rmSync(tmpDir, { recursive: true, force: true });
214
- }
215
- else {
216
- cpSync(backup.path, destPath, { recursive: true });
217
- }
218
- return { success: true, output: `Copied to ${destPath}` };
219
- }
220
- catch (e) {
221
- return { success: false, output: e.message };
222
- }
223
- }
224
- function deleteBackup(backup) {
225
- try {
226
- rmSync(backup.path, { recursive: true, force: true });
227
- return { success: true, output: `Deleted ${backup.name}` };
228
- }
229
- catch (e) {
230
- return { success: false, output: e.message };
231
- }
232
- }
233
- function formatBackupLine(b) {
234
- const locIcon = b.location === "internal" ? "📁" : "💾";
235
- const comp = b.isCompressed ? " • compressed" : "";
236
- return `${locIcon} ${b.name} │ ${formatTimestamp(b.timestamp)} │ ${b.size} │ ${b.files} files${comp}`;
237
- }
238
- function findFile(dir, name) {
239
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
240
- const full = join(dir, entry.name);
241
- if (entry.isDirectory()) {
242
- const found = findFile(full, name);
243
- if (found)
244
- return found;
245
- }
246
- else if (entry.name === name) {
247
- return full;
248
- }
249
- }
250
- return null;
251
- }
252
- export default function piBackupManagerExtension(pi) {
253
- console.error("[pi-backup-manager] Extension loaded");
254
- pi.registerCommand("pi-backup", {
255
- description: "Manage Pi backups - create, restore, view, copy, delete",
256
- handler: async (_args, ctx) => {
257
- if (ctx.mode !== "tui") {
258
- ctx.ui.notify("Backup manager only available in TUI mode", "error");
259
- return;
260
- }
261
- await showMainMenu(ctx);
262
- },
263
- });
264
- }
265
- async function showMainMenu(ctx) {
266
- while (true) {
267
- const externalDir = resolveExternalBackupDir(ctx);
268
- const backups = discoverBackups(ctx);
269
- const internalCount = backups.filter(b => b.location === "internal").length;
270
- const externalCount = backups.filter(b => b.location === "external").length;
271
- const choice = await ctx.ui.select(`Pi Backup Manager — ${backups.length} backups (${internalCount} internal, ${externalCount} external)\nExternal dir: ${externalDir}`, [
272
- "📦 Create internal backup (~/.pi/backups/ — quick rollback)",
273
- "💾 Create external backup (survives reinstall)",
274
- "📋 List all backups",
275
- "⚙️ Configure external backup directory",
276
- "❓ Help",
277
- "← Exit",
278
- ]);
279
- if (!choice || choice.startsWith("←"))
280
- return;
281
- if (choice.startsWith("📦"))
282
- await createBackup(ctx, true);
283
- else if (choice.startsWith("💾"))
284
- await createBackup(ctx, false);
285
- else if (choice.startsWith("📋"))
286
- await showBackupList(ctx);
287
- else if (choice.startsWith("⚙️"))
288
- await configureExternalDir(ctx);
289
- else if (choice.startsWith("❓"))
290
- await showHelp(ctx);
291
- }
292
- }
293
- async function createBackup(ctx, internal) {
294
- // For external backup, ensure directory is configured.
295
- // Only prompt if no env/settings value AND the default dir is empty/missing.
296
- if (!internal) {
297
- const externalDir = getExternalBackupDir(ctx);
298
- const settings = readSettings();
299
- const explicitlyConfigured = process.env.BACKUP_ROOT || settings.externalBackupDir;
300
- const defaultHasContent = existsSync(externalDir) && readdirSync(externalDir).length > 0;
301
- if (!explicitlyConfigured && !defaultHasContent) {
302
- const configured = await promptForExternalBackupDir(ctx);
303
- if (!configured)
304
- return;
305
- }
306
- }
307
- ctx.ui.notify(`Creating ${internal ? "internal" : "external"} backup...`, "info");
308
- const result = runBackup(internal, ctx);
309
- if (result.success) {
310
- ctx.ui.notify(`Backup created successfully${result.backupPath ? `\n${result.backupPath}` : ""}`, "info");
311
- }
312
- else {
313
- ctx.ui.notify(`Backup failed:\n${result.output}`, "error");
314
- }
315
- }
316
- async function showBackupList(ctx) {
317
- let backups = discoverBackups(ctx);
318
- if (backups.length === 0) {
319
- ctx.ui.notify("No backups found", "info");
320
- return;
321
- }
322
- while (true) {
323
- const lines = backups.map(formatBackupLine);
324
- lines.push("🔄 Refresh");
325
- lines.push("← Back");
326
- const selected = await ctx.ui.select(`Backups (${backups.length} total)`, lines);
327
- if (!selected || selected.startsWith("←"))
328
- return;
329
- if (selected.startsWith("🔄")) {
330
- backups = discoverBackups(ctx);
331
- continue;
332
- }
333
- const backup = backups.find(b => selected.includes(b.name));
334
- if (!backup)
335
- continue;
336
- await showBackupActions(ctx, backup);
337
- backups = discoverBackups(ctx);
338
- }
339
- }
340
- async function showBackupActions(ctx, backup) {
341
- const isInternal = backup.location === "internal";
342
- const actions = [
343
- `🔄 Restore this backup (${formatTimestamp(backup.timestamp)})`,
344
- ];
345
- if (!isInternal) {
346
- actions.push("📋 Copy to internal (~/.pi/backups/)");
347
- }
348
- actions.push("📄 View manifest", "🗑️ Delete", "← Back");
349
- const choice = await ctx.ui.select(`Backup: ${backup.name}`, actions);
350
- if (!choice || choice.startsWith("←"))
351
- return;
352
- if (choice.startsWith("🔄"))
353
- await confirmRestore(ctx, backup);
354
- else if (choice.startsWith("📋")) {
355
- const result = copyBackupToInternal(backup);
356
- ctx.ui.notify(result.success ? result.output : `Failed: ${result.output}`, result.success ? "info" : "error");
357
- }
358
- else if (choice.startsWith("📄"))
359
- await viewManifest(ctx, backup);
360
- else if (choice.startsWith("🗑️"))
361
- await confirmDelete(ctx, backup);
362
- }
363
- async function confirmRestore(ctx, backup) {
364
- // Restore uses the backup's direct path, so no directory config is needed here.
365
- const confirmed = await ctx.ui.confirm(`Restore ${backup.name}?`, `⚠️ This will OVERWRITE all current Pi configuration!\n` +
366
- `Backup: ${formatTimestamp(backup.timestamp)} • ${backup.size} • ${backup.files} files\n` +
367
- `Pi must NOT be running during restore.\n\n` +
368
- `Are you sure?`);
369
- if (!confirmed)
370
- return;
371
- ctx.ui.notify("Restoring... (this may take a moment)", "info");
372
- const result = runRestore(backup.path);
373
- if (result.success) {
374
- ctx.ui.notify("Restore complete!\n\nNext steps:\n1. cd ~/.pi/agent && npm install\n2. pi --version\n3. /ctx-doctor", "info");
375
- }
376
- else {
377
- ctx.ui.notify(`Restore failed:\n${result.output}`, "error");
378
- }
379
- }
380
- async function confirmDelete(ctx, backup) {
381
- const confirmed = await ctx.ui.confirm(`Delete ${backup.name}?`, `This cannot be undone.\n${formatTimestamp(backup.timestamp)} • ${backup.size} • ${backup.files} files`);
382
- if (!confirmed)
383
- return;
384
- const result = deleteBackup(backup);
385
- ctx.ui.notify(result.success ? result.output : `Failed: ${result.output}`, result.success ? "info" : "error");
386
- }
387
- async function viewManifest(ctx, backup) {
388
- let manifestPath;
389
- if (backup.isCompressed) {
390
- const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-manifest-${Date.now()}`);
391
- mkdirSync(tmpDir, { recursive: true });
392
- try {
393
- if (backup.name.endsWith(".zip")) {
394
- execSync(`unzip -q "${backup.path}" "*/MANIFEST.txt" -d "${tmpDir}"`);
395
- }
396
- else {
397
- execSync(`7z x -o"${tmpDir}" "${backup.path}" "*/MANIFEST.txt" >/dev/null`);
398
- }
399
- const found = findFile(tmpDir, "MANIFEST.txt");
400
- if (found)
401
- manifestPath = found;
402
- else
403
- throw new Error("MANIFEST.txt not found in archive");
404
- }
405
- catch (e) {
406
- ctx.ui.notify(`Failed to extract manifest: ${e.message}`, "error");
407
- rmSync(tmpDir, { recursive: true, force: true });
408
- return;
409
- }
410
- rmSync(tmpDir, { recursive: true, force: true });
411
- }
412
- else {
413
- manifestPath = join(backup.path, "MANIFEST.txt");
414
- }
415
- if (!existsSync(manifestPath)) {
416
- ctx.ui.notify("No manifest found in backup", "warning");
417
- return;
418
- }
419
- const content = readFileSync(manifestPath, "utf-8");
420
- await ctx.ui.editor(`MANIFEST — ${backup.name}`, content);
421
- }
422
- async function configureExternalDir(ctx) {
423
- const current = getExternalBackupDir(ctx);
424
- const source = process.env.BACKUP_ROOT ? "environment variable (BACKUP_ROOT)"
425
- : readSettings().externalBackupDir ? "settings.json"
426
- : "default (not yet saved)";
427
- const choice = await ctx.ui.select(`Current external backup directory:\n${current}\n\nSource: ${source}`, [
428
- "📝 Change directory",
429
- "🔄 Reset to default",
430
- "← Back",
431
- ]);
432
- if (!choice || choice.startsWith("←"))
433
- return;
434
- if (choice.startsWith("📝")) {
435
- await promptForExternalBackupDir(ctx);
436
- }
437
- else if (choice.startsWith("🔄")) {
438
- const settings = readSettings();
439
- delete settings.externalBackupDir;
440
- writeSettings(settings);
441
- ctx.ui.notify("Reset to default. Will use environment variable or default path.", "info");
442
- }
443
- }
444
- async function showHelp(ctx) {
445
- const externalDir = resolveExternalBackupDir(ctx);
446
- const help = `# Pi Backup Manager Help
447
-
448
- ## Backup Locations
449
-
450
- ### 📁 Internal (~/.pi/backups/)
451
- - **Purpose**: Quick rollback during normal use
452
- - **Survives**: Pi updates, extension installs, config changes
453
- - **Does NOT survive**: Clean reinstall (\`rm -rf ~/.pi\`)
454
- - **Format**: Uncompressed directories (fast access)
455
-
456
- ### 💾 External (${externalDir})
457
- - **Purpose**: Disaster recovery
458
- - **Survives**: Clean reinstall, disk failure (if copied elsewhere)
459
- - **Does NOT survive**: Deleting the backup directory
460
- - **Format**: Compressed archives (.7z/.zip) + optional uncompressed
461
-
462
- ## Configuration Priority
463
-
464
- The external backup directory is resolved in this order:
465
-
466
- 1. **BACKUP_ROOT** environment variable (highest priority)
467
- 2. **settings.json** → \`externalBackupDir\`
468
- 3. **Default**: \`~/projects/personal/pi-utils/backups/\`
469
-
470
- Use **⚙️ Configure external backup directory** in the main menu to change the settings.json value.
471
-
472
- ## When to Use Which
473
-
474
- | Scenario | Recommended |
475
- |----------|-------------|
476
- | Before installing risky extension | Internal |
477
- | Before changing config files | Internal |
478
- | Before Pi update | Both |
479
- | Before clean reinstall | **External (required)** |
480
- | Moving to new machine | External |
481
-
482
- ## Restore Process
483
-
484
- 1. Select backup → Restore
485
- 2. Script overwrites all config in \`~/.pi/agent/\`
486
- 3. **After restore**: Run \`cd ~/.pi/agent && npm install\`
487
- 4. Verify: \`pi --version\`, \`/ctx-doctor\`
488
-
489
- ## Manual Backup/Restore
490
-
491
- \`\`\`bash
492
- # Create external backup (uses BACKUP_ROOT or default)
493
- ~/projects/personal/pi-backup/backup-pi.sh
494
-
495
- # Override backup location
496
- BACKUP_ROOT=/mnt/backups ~/projects/personal/pi-backup/backup-pi.sh
497
-
498
- # Restore from external
499
- ~/projects/personal/pi-backup/restore-pi.sh ~/projects/personal/pi-utils/backups/pi-backup-20260811-143000
500
- \`\`\`
501
-
502
- ## What Gets Backed Up
503
-
504
- ✅ settings.json, auth.json, models.json, trust.json, keybindings.json
505
- ✅ All extension configs (loop-police, context-mode, hermes-memory, etc.)
506
- ✅ Global skills (\`~/.pi/agent/skills/\`)
507
- ✅ Project skills & memory (\`~/.pi/agent/projects-memory/\`)
508
- ✅ Local extension source code (pi-timeout, pi-chunk, etc.)
509
- ✅ npm manifests (package.json, lockfiles)
510
- ✅ Hermes memory files (MEMORY.md, USER.md, failures.md)
511
- ✅ Recent hermes-cleanup backups
512
-
513
- ## What Does NOT Get Backed Up (Regeneratable)
514
-
515
- ❌ Sessions (\`~/.pi/agent/sessions/\`)
516
- ❌ Context-mode KB (\`context-mode/kb.sqlite\`)
517
- ❌ node_modules/
518
- ❌ loop-police-detections.jsonl
519
- ❌ Lock files`;
520
- await ctx.ui.editor("Pi Backup Manager Help", help);
521
- }