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