@jamiefutch/pi-backup 1.0.0

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