@jamiefutch/pi-backup 1.1.11 β†’ 1.1.13

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.
@@ -1,8 +1,12 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { execFileSync } from "node:child_process";
2
+ import { execFile, spawn } from "node:child_process";
3
+ import { promisify } from "node:util";
3
4
  import { join, dirname } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
- import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, writeFileSync, rmSync, cpSync } from "node:fs";
6
+ import { existsSync, mkdirSync, readdirSync, statSync, readFileSync, writeFileSync, rmSync, cpSync, renameSync, copyFileSync } from "node:fs";
7
+
8
+ const execFileAsync = promisify(execFile);
9
+ const MAX_BUFFER = 50 * 1024 * 1024;
6
10
 
7
11
  const HOME_DIR = process.env.HOME || process.env.USERPROFILE || "";
8
12
  const IS_WINDOWS = process.platform === "win32";
@@ -22,18 +26,73 @@ interface BackupInfo {
22
26
  location: "internal" | "external";
23
27
  }
24
28
 
25
- function readSettings(): any {
29
+ interface SettingsResult {
30
+ ok: boolean;
31
+ data: Record<string, any>;
32
+ error?: string;
33
+ }
34
+
35
+ /** A missing file is fine ({}). A file that exists but cannot be parsed is NOT ok. */
36
+ function readSettings(): SettingsResult {
37
+ if (!existsSync(SETTINGS_FILE)) return { ok: true, data: {} };
38
+ try {
39
+ const parsed = JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
40
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
41
+ return { ok: false, data: {}, error: "settings.json is not a JSON object" };
42
+ }
43
+ return { ok: true, data: parsed };
44
+ } catch (e: any) {
45
+ return { ok: false, data: {}, error: `settings.json could not be parsed (${e.message})` };
46
+ }
47
+ }
48
+
49
+ const SETTINGS_BACKUPS_KEPT = 3;
50
+
51
+ /**
52
+ * Read-modify-write settings.json safely: refuses if the current file is corrupt, writes to a temp
53
+ * file and renames it into place, and keeps the previous version as settings.json.bak-<timestamp>.
54
+ */
55
+ function updateSettings(mutate: (settings: Record<string, any>) => void): { ok: boolean; error?: string } {
56
+ const current = readSettings();
57
+ if (!current.ok) {
58
+ return { ok: false, error: `${current.error}. Left untouched; fix or remove ${SETTINGS_FILE} and try again.` };
59
+ }
60
+ mutate(current.data);
61
+ const dir = dirname(SETTINGS_FILE);
62
+ const tmp = `${SETTINGS_FILE}.tmp-${process.pid}-${Date.now()}`;
26
63
  try {
64
+ mkdirSync(dir, { recursive: true });
65
+ writeFileSync(tmp, JSON.stringify(current.data, null, 2), "utf-8");
27
66
  if (existsSync(SETTINGS_FILE)) {
28
- return JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
67
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
68
+ copyFileSync(SETTINGS_FILE, `${SETTINGS_FILE}.bak-${stamp}`);
69
+ const old = readdirSync(dir).filter((f) => f.startsWith("settings.json.bak-")).sort();
70
+ for (const f of old.slice(0, Math.max(0, old.length - SETTINGS_BACKUPS_KEPT))) {
71
+ rmSync(join(dir, f), { force: true });
72
+ }
29
73
  }
30
- } catch {}
31
- return {};
74
+ renameSync(tmp, SETTINGS_FILE);
75
+ return { ok: true };
76
+ } catch (e: any) {
77
+ rmSync(tmp, { force: true });
78
+ return { ok: false, error: e.message };
79
+ }
32
80
  }
33
81
 
34
- function writeSettings(settings: any): void {
35
- mkdirSync(dirname(SETTINGS_FILE), { recursive: true });
36
- writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2), "utf-8");
82
+ let corruptSettingsWarned = false;
83
+
84
+ /** Read-only callers fall back to defaults and surface a single warning. */
85
+ function readSettingsForDisplay(ctx?: any): Record<string, any> {
86
+ const result = readSettings();
87
+ if (result.ok) {
88
+ corruptSettingsWarned = false;
89
+ return result.data;
90
+ }
91
+ if (!corruptSettingsWarned) {
92
+ corruptSettingsWarned = true;
93
+ ctx?.ui?.notify?.(`${result.error}. Using default settings; ${SETTINGS_FILE} was not modified.`, "warning");
94
+ }
95
+ return {};
37
96
  }
38
97
 
39
98
  function getExternalBackupDir(ctx?: any): string {
@@ -43,7 +102,7 @@ function getExternalBackupDir(ctx?: any): string {
43
102
  }
44
103
 
45
104
  // 2. settings.json
46
- const settings = readSettings();
105
+ const settings = readSettingsForDisplay(ctx);
47
106
  if (settings.externalBackupDir) {
48
107
  return settings.externalBackupDir;
49
108
  }
@@ -53,9 +112,9 @@ function getExternalBackupDir(ctx?: any): string {
53
112
  }
54
113
 
55
114
  async function promptForExternalBackupDir(ctx: any): Promise<string | null> {
56
- const currentDefault = getExternalBackupDir();
115
+ const currentDefault = getExternalBackupDir(ctx);
57
116
  const source = process.env.BACKUP_ROOT ? "BACKUP_ROOT env var"
58
- : readSettings().externalBackupDir ? "settings.json"
117
+ : readSettingsForDisplay(ctx).externalBackupDir ? "settings.json"
59
118
  : "default";
60
119
  const input = await ctx.ui.input(
61
120
  `Configure external backup directory\n\nCurrent: ${currentDefault}\nSource: ${source}\n\nEnter a new path or press Enter to keep the current value:`,
@@ -66,10 +125,12 @@ async function promptForExternalBackupDir(ctx: any): Promise<string | null> {
66
125
 
67
126
  const chosenPath = input.trim() || currentDefault;
68
127
 
69
- // Save to settings.json
70
- const settings = readSettings();
71
- settings.externalBackupDir = chosenPath;
72
- writeSettings(settings);
128
+ // Save to settings.json (refuses if the existing file is corrupt)
129
+ const saved = updateSettings((settings) => { settings.externalBackupDir = chosenPath; });
130
+ if (!saved.ok) {
131
+ ctx.ui.notify(`Could not save external backup directory: ${saved.error}`, "error");
132
+ return null;
133
+ }
73
134
  ctx.ui.notify(`Saved external backup directory to settings.json:\n${chosenPath}`, "info");
74
135
 
75
136
  // Ensure directory exists
@@ -82,49 +143,61 @@ function resolveExternalBackupDir(ctx?: any): string {
82
143
  return getExternalBackupDir(ctx);
83
144
  }
84
145
 
146
+ // PI_BACKUP_SCRIPT_DIR is a test hook that points at stub scripts.
147
+ function scriptDir(): string {
148
+ return process.env.PI_BACKUP_SCRIPT_DIR || PACKAGE_ROOT;
149
+ }
150
+
85
151
  function getBackupScriptPath(): string {
86
- return join(PACKAGE_ROOT, IS_WINDOWS ? "backup-pi.ps1" : "backup-pi.sh");
152
+ return join(scriptDir(), IS_WINDOWS ? "backup-pi.ps1" : "backup-pi.sh");
87
153
  }
88
154
 
89
155
  function getRestoreScriptPath(): string {
90
- return join(PACKAGE_ROOT, IS_WINDOWS ? "restore-pi.ps1" : "restore-pi.sh");
156
+ return join(scriptDir(), IS_WINDOWS ? "restore-pi.ps1" : "restore-pi.sh");
91
157
  }
92
158
 
93
- function findSevenZip(): string | null {
159
+ async function findSevenZip(): Promise<string | null> {
94
160
  const lookup = IS_WINDOWS ? "where.exe" : "which";
95
161
  for (const candidate of ["7zz", "7z", "7za"]) {
96
162
  try {
97
- execFileSync(lookup, [candidate], { stdio: "ignore" });
163
+ await execFileAsync(lookup, [candidate]);
98
164
  return candidate;
99
165
  } catch {}
100
166
  }
101
167
  return null;
102
168
  }
103
169
 
104
- function expandZipWithPowerShell(archivePath: string, destination: string): void {
105
- execFileSync("pwsh", [
170
+ async function expandZipWithPowerShell(archivePath: string, destination: string): Promise<void> {
171
+ await execFileAsync("pwsh", [
106
172
  "-NoProfile",
107
173
  "-Command",
108
174
  "Expand-Archive -LiteralPath $env:PI_BACKUP_ARCHIVE -DestinationPath $env:PI_BACKUP_DEST -Force",
109
175
  ], {
110
176
  env: { ...process.env, PI_BACKUP_ARCHIVE: archivePath, PI_BACKUP_DEST: destination },
177
+ maxBuffer: MAX_BUFFER,
111
178
  });
112
179
  }
113
180
 
114
- function extractArchive(archivePath: string, destination: string): void {
115
- const sevenZip = findSevenZip();
181
+ async function extractArchive(archivePath: string, destination: string): Promise<void> {
182
+ const sevenZip = await findSevenZip();
116
183
  if (sevenZip) {
117
- execFileSync(sevenZip, ["x", "-y", `-o${destination}`, archivePath]);
184
+ await execFileAsync(sevenZip, ["x", "-y", `-o${destination}`, archivePath], { maxBuffer: MAX_BUFFER });
118
185
  return;
119
186
  }
120
187
  if (archivePath.endsWith(".zip")) {
121
- if (IS_WINDOWS) expandZipWithPowerShell(archivePath, destination);
122
- else execFileSync("unzip", ["-q", archivePath, "-d", destination]);
188
+ if (IS_WINDOWS) await expandZipWithPowerShell(archivePath, destination);
189
+ else await execFileAsync("unzip", ["-q", archivePath, "-d", destination], { maxBuffer: MAX_BUFFER });
123
190
  return;
124
191
  }
125
192
  throw new Error("7zip is required to extract .7z backups and was not found on PATH");
126
193
  }
127
194
 
195
+ /** stdout and stderr of a failed child process, falling back to the error message. */
196
+ function describeExecError(e: any): string {
197
+ const text = [e?.stdout, e?.stderr].filter((v) => typeof v === "string" && v.trim()).join("\n").trim();
198
+ return text || e?.message || String(e);
199
+ }
200
+
128
201
  function ensureDirs(externalDir: string) {
129
202
  if (!existsSync(INTERNAL_BACKUP_DIR)) mkdirSync(INTERNAL_BACKUP_DIR, { recursive: true });
130
203
  if (!existsSync(externalDir)) mkdirSync(externalDir, { recursive: true });
@@ -232,7 +305,7 @@ function discoverBackups(ctx?: any): BackupInfo[] {
232
305
  return backups.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
233
306
  }
234
307
 
235
- function runBackup(internal: boolean, ctx?: any): { success: boolean; output: string; backupPath?: string } {
308
+ async function runBackup(internal: boolean, ctx?: any): Promise<{ success: boolean; output: string; backupPath?: string }> {
236
309
  try {
237
310
  const externalDir = resolveExternalBackupDir(ctx);
238
311
  const env = { ...process.env };
@@ -243,47 +316,84 @@ function runBackup(internal: boolean, ctx?: any): { success: boolean; output: st
243
316
  env.BACKUP_ROOT = externalDir;
244
317
  env.KEEP_UNCOMPRESSED = "0"; // external: compressed archive only
245
318
  }
246
- const command = IS_WINDOWS ? "pwsh" : getBackupScriptPath();
319
+ const command = IS_WINDOWS ? "pwsh" : getBackupScriptPath();
247
320
  const args = IS_WINDOWS ? ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", getBackupScriptPath()] : [];
248
- const output = execFileSync(command, args, { env, encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
321
+ const { stdout, stderr } = await execFileAsync(command, args, { env, encoding: "utf-8", maxBuffer: MAX_BUFFER });
322
+ const output = `${stdout}${stderr ? `\n${stderr}` : ""}`;
249
323
  const match = output.match(/Staging:\s+(.+)$/m) || output.match(/Archive:\s+(.+)$/m);
250
324
  const backupPath = match ? match[1].trim() : undefined;
251
325
  return { success: true, output, backupPath };
252
326
  } catch (e: any) {
253
- return { success: false, output: e.stdout || e.stderr || e.message };
327
+ return { success: false, output: describeExecError(e) };
254
328
  }
255
329
  }
256
330
 
257
- function runRestore(backupPath: string): { success: boolean; output: string } {
258
- try {
259
- const command = IS_WINDOWS ? "pwsh" : getRestoreScriptPath();
260
- const args = IS_WINDOWS ? ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", getRestoreScriptPath(), backupPath] : [backupPath];
261
- const output = execFileSync(command, args, { encoding: "utf-8", maxBuffer: 10 * 1024 * 1024 });
262
- return { success: true, output };
263
- } catch (e: any) {
264
- return { success: false, output: e.stdout || e.stderr || e.message };
331
+ function shellQuote(value: string): string {
332
+ return IS_WINDOWS ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, `'\\''`)}'`;
333
+ }
334
+
335
+ /**
336
+ * The command the user should run AFTER exiting Pi. Restore must not run inside the live Pi
337
+ * process: Pi would keep (and later rewrite) the files being replaced.
338
+ */
339
+ function buildRestoreCommand(backupPath: string): string {
340
+ const script = getRestoreScriptPath();
341
+ if (IS_WINDOWS) {
342
+ return `$env:PI_BACKUP_ASSUME_YES='1'; pwsh -NoProfile -ExecutionPolicy Bypass -File ${shellQuote(script)} ${shellQuote(backupPath)}`;
265
343
  }
344
+ return `PI_BACKUP_ASSUME_YES=1 ${shellQuote(script)} ${shellQuote(backupPath)}`;
345
+ }
346
+
347
+ /** Best-effort clipboard copy. Disabled with PI_BACKUP_NO_CLIPBOARD=1 (used by tests). */
348
+ async function copyToClipboard(text: string): Promise<boolean> {
349
+ if (process.env.PI_BACKUP_NO_CLIPBOARD === "1") return false;
350
+ const candidates: Array<[string, string[]]> = IS_WINDOWS
351
+ ? [["clip", []]]
352
+ : process.platform === "darwin"
353
+ ? [["pbcopy", []]]
354
+ : [["wl-copy", []], ["xclip", ["-selection", "clipboard"]], ["xsel", ["--clipboard", "--input"]]];
355
+ for (const [cmd, args] of candidates) {
356
+ try {
357
+ await new Promise<void>((resolve, reject) => {
358
+ const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "ignore"] });
359
+ child.on("error", reject);
360
+ child.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`exit ${code}`))));
361
+ child.stdin.on("error", reject);
362
+ child.stdin.end(text);
363
+ });
364
+ return true;
365
+ } catch {}
366
+ }
367
+ return false;
266
368
  }
267
369
 
268
- function copyBackupToInternal(backup: BackupInfo): { success: boolean; output: string } {
370
+ async function copyBackupToInternal(backup: BackupInfo): Promise<{ success: boolean; output: string }> {
269
371
  if (backup.location === "internal") return { success: true, output: "Already in internal storage" };
372
+ const destPath = join(INTERNAL_BACKUP_DIR, backup.isCompressed ? backup.name.replace(/\.(zip|7z)$/, "") : backup.name);
373
+ let tmpDir: string | null = null;
374
+ let created = false;
270
375
  try {
271
- const destName = backup.name;
272
- const destPath = join(INTERNAL_BACKUP_DIR, destName);
376
+ if (existsSync(destPath)) throw new Error(`Already exists in internal storage: ${destPath}`);
377
+ mkdirSync(INTERNAL_BACKUP_DIR, { recursive: true });
273
378
  if (backup.isCompressed) {
274
- const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-${Date.now()}`);
379
+ tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-${Date.now()}`);
275
380
  mkdirSync(tmpDir, { recursive: true });
276
- extractArchive(backup.path, tmpDir);
381
+ await extractArchive(backup.path, tmpDir);
277
382
  const extracted = readdirSync(tmpDir)[0];
278
383
  if (!extracted) throw new Error(`Archive is empty: ${backup.path}`);
384
+ created = true;
279
385
  cpSync(join(tmpDir, extracted), destPath, { recursive: true });
280
- rmSync(tmpDir, { recursive: true, force: true });
281
386
  } else {
387
+ created = true;
282
388
  cpSync(backup.path, destPath, { recursive: true });
283
389
  }
390
+ created = false; // complete
284
391
  return { success: true, output: `Copied to ${destPath}` };
285
392
  } catch (e: any) {
286
- return { success: false, output: e.message };
393
+ if (created) rmSync(destPath, { recursive: true, force: true });
394
+ return { success: false, output: describeExecError(e) };
395
+ } finally {
396
+ if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
287
397
  }
288
398
  }
289
399
 
@@ -316,7 +426,6 @@ function findFile(dir: string, name: string): string | null {
316
426
  }
317
427
 
318
428
  export default function piBackupManagerExtension(pi: ExtensionAPI) {
319
- console.error("[pi-backup-manager] Extension loaded");
320
429
  pi.registerCommand("pi-backup", {
321
430
  description: "Manage Pi backups - create, restore, view, copy, delete",
322
431
  handler: async (_args, ctx) => {
@@ -329,6 +438,17 @@ export default function piBackupManagerExtension(pi: ExtensionAPI) {
329
438
  });
330
439
  }
331
440
 
441
+ /** Show a working status while a long task runs, when the host supports it. */
442
+ async function withStatus<T>(ctx: any, message: string, task: () => Promise<T>): Promise<T> {
443
+ const setStatus = typeof ctx?.ui?.setStatus === "function" ? ctx.ui.setStatus.bind(ctx.ui) : null;
444
+ setStatus?.("pi-backup", message);
445
+ try {
446
+ return await task();
447
+ } finally {
448
+ setStatus?.("pi-backup", undefined);
449
+ }
450
+ }
451
+
332
452
  async function showMainMenu(ctx: any) {
333
453
  while (true) {
334
454
  const externalDir = resolveExternalBackupDir(ctx);
@@ -363,7 +483,7 @@ async function createBackup(ctx: any, internal: boolean) {
363
483
  // Only prompt if no env/settings value AND the default dir is empty/missing.
364
484
  if (!internal) {
365
485
  const externalDir = getExternalBackupDir(ctx);
366
- const settings = readSettings();
486
+ const settings = readSettingsForDisplay(ctx);
367
487
  const explicitlyConfigured = process.env.BACKUP_ROOT || settings.externalBackupDir;
368
488
  const defaultHasContent = existsSync(externalDir) && readdirSync(externalDir).length > 0;
369
489
  if (!explicitlyConfigured && !defaultHasContent) {
@@ -373,14 +493,27 @@ async function createBackup(ctx: any, internal: boolean) {
373
493
  }
374
494
 
375
495
  ctx.ui.notify(`Creating ${internal ? "internal" : "external"} backup...`, "info");
376
- const result = runBackup(internal, ctx);
496
+ const result = await withStatus(ctx, `Creating ${internal ? "internal" : "external"} backup…`, () => runBackup(internal, ctx));
377
497
  if (result.success) {
378
- ctx.ui.notify(`Backup created successfully${result.backupPath ? `\n${result.backupPath}` : ""}`, "info");
498
+ const credentials = "\n⚠️ The backup contains auth.json (API credentials). Keep it private.";
499
+ ctx.ui.notify(`Backup created successfully${result.backupPath ? `\n${result.backupPath}` : ""}${credentials}`, "info");
379
500
  } else {
380
501
  ctx.ui.notify(`Backup failed:\n${result.output}`, "error");
381
502
  }
382
503
  }
383
504
 
505
+ /** Unique, exact-match labels for the backup list (never substring-match names). */
506
+ function buildLabels(backups: BackupInfo[]): Map<string, BackupInfo> {
507
+ const labels = new Map<string, BackupInfo>();
508
+ for (const b of backups) {
509
+ const base = formatBackupLine(b);
510
+ let label = base;
511
+ for (let n = 2; labels.has(label); n++) label = `${base} (${b.location} #${n})`;
512
+ labels.set(label, b);
513
+ }
514
+ return labels;
515
+ }
516
+
384
517
  async function showBackupList(ctx: any) {
385
518
  let backups = discoverBackups(ctx);
386
519
  if (backups.length === 0) {
@@ -389,7 +522,8 @@ async function showBackupList(ctx: any) {
389
522
  }
390
523
 
391
524
  while (true) {
392
- const lines = backups.map(formatBackupLine);
525
+ const labels = buildLabels(backups);
526
+ const lines = [...labels.keys()];
393
527
  lines.push("πŸ”„ Refresh");
394
528
  lines.push("← Back");
395
529
 
@@ -397,11 +531,12 @@ async function showBackupList(ctx: any) {
397
531
  if (!selected || selected.startsWith("←")) return;
398
532
  if (selected.startsWith("πŸ”„")) { backups = discoverBackups(ctx); continue; }
399
533
 
400
- const backup = backups.find(b => selected.includes(b.name));
534
+ const backup = labels.get(selected);
401
535
  if (!backup) continue;
402
536
 
403
537
  await showBackupActions(ctx, backup);
404
538
  backups = discoverBackups(ctx);
539
+ if (backups.length === 0) return;
405
540
  }
406
541
  }
407
542
 
@@ -426,30 +561,32 @@ async function showBackupActions(ctx: any, backup: BackupInfo) {
426
561
 
427
562
  if (choice.startsWith("πŸ”„")) await confirmRestore(ctx, backup);
428
563
  else if (choice.startsWith("πŸ“‹")) {
429
- const result = copyBackupToInternal(backup);
564
+ const result = await withStatus(ctx, "Copying backup…", () => copyBackupToInternal(backup));
430
565
  ctx.ui.notify(result.success ? result.output : `Failed: ${result.output}`, result.success ? "info" : "error");
431
566
  } else if (choice.startsWith("πŸ“„")) await viewManifest(ctx, backup);
432
567
  else if (choice.startsWith("πŸ—‘οΈ")) await confirmDelete(ctx, backup);
433
568
  }
434
569
 
435
570
  async function confirmRestore(ctx: any, backup: BackupInfo) {
436
- // Restore uses the backup's direct path, so no directory config is needed here.
571
+ // Restore replaces files that the running Pi process owns, so the TUI never runs it in-process.
437
572
  const confirmed = await ctx.ui.confirm(
438
573
  `Restore ${backup.name}?`,
439
- `⚠️ This will OVERWRITE all current Pi configuration!\n` +
440
- `Backup: ${formatTimestamp(backup.timestamp)} β€’ ${backup.size} β€’ ${backup.files} files\n` +
441
- `Pi must NOT be running during restore.\n\n` +
442
- `Are you sure?`,
574
+ `⚠️ Restoring OVERWRITES all current Pi configuration.\n` +
575
+ `Backup: ${formatTimestamp(backup.timestamp)} β€’ ${backup.size} β€’ ${backup.files} files\n\n` +
576
+ `Pi cannot restore itself while running. Choosing Yes shows the command to run\n` +
577
+ `AFTER you exit Pi (nothing is changed now).\n\n` +
578
+ `Continue?`,
443
579
  );
444
580
  if (!confirmed) return;
445
581
 
446
- ctx.ui.notify("Restoring... (this may take a moment)", "info");
447
- const result = runRestore(backup.path);
448
- if (result.success) {
449
- ctx.ui.notify("Restore complete!\n\nNext steps:\n1. cd ~/.pi/agent && npm install\n2. pi --version\n3. /ctx-doctor", "info");
450
- } else {
451
- ctx.ui.notify(`Restore failed:\n${result.output}`, "error");
452
- }
582
+ const command = buildRestoreCommand(backup.path);
583
+ const copied = await copyToClipboard(command);
584
+ ctx.ui.notify(
585
+ `To restore, exit Pi, then run this in a terminal:\n\n${command}\n\n` +
586
+ `${copied ? "(Copied to the clipboard.)\n" : ""}` +
587
+ `Afterwards: cd ~/.pi/agent && npm install, then pi --version and /ctx-doctor.`,
588
+ "info",
589
+ );
453
590
  }
454
591
 
455
592
  async function confirmDelete(ctx: any, backup: BackupInfo) {
@@ -466,19 +603,20 @@ async function confirmDelete(ctx: any, backup: BackupInfo) {
466
603
  async function viewManifest(ctx: any, backup: BackupInfo) {
467
604
  let content: string;
468
605
  if (backup.isCompressed) {
606
+ mkdirSync(INTERNAL_BACKUP_DIR, { recursive: true });
469
607
  const tmpDir = join(INTERNAL_BACKUP_DIR, `.tmp-manifest-${Date.now()}`);
470
608
  mkdirSync(tmpDir, { recursive: true });
471
609
  try {
472
- extractArchive(backup.path, tmpDir);
610
+ await withStatus(ctx, "Reading manifest…", () => extractArchive(backup.path, tmpDir));
473
611
  const found = findFile(tmpDir, "MANIFEST.txt");
474
612
  if (!found) throw new Error("MANIFEST.txt not found in archive");
475
613
  content = readFileSync(found, "utf-8");
476
614
  } catch (e: any) {
477
- ctx.ui.notify(`Failed to extract manifest: ${e.message}`, "error");
478
- rmSync(tmpDir, { recursive: true, force: true });
615
+ ctx.ui.notify(`Failed to extract manifest: ${describeExecError(e)}`, "error");
479
616
  return;
617
+ } finally {
618
+ rmSync(tmpDir, { recursive: true, force: true });
480
619
  }
481
- rmSync(tmpDir, { recursive: true, force: true });
482
620
  } else {
483
621
  const manifestPath = join(backup.path, "MANIFEST.txt");
484
622
  if (!existsSync(manifestPath)) {
@@ -494,7 +632,7 @@ async function viewManifest(ctx: any, backup: BackupInfo) {
494
632
  async function configureExternalDir(ctx: any) {
495
633
  const current = getExternalBackupDir(ctx);
496
634
  const source = process.env.BACKUP_ROOT ? "environment variable (BACKUP_ROOT)"
497
- : readSettings().externalBackupDir ? "settings.json"
635
+ : readSettingsForDisplay(ctx).externalBackupDir ? "settings.json"
498
636
  : "default (not yet saved)";
499
637
 
500
638
  const choice = await ctx.ui.select(
@@ -511,9 +649,11 @@ async function configureExternalDir(ctx: any) {
511
649
  if (choice.startsWith("πŸ“")) {
512
650
  await promptForExternalBackupDir(ctx);
513
651
  } else if (choice.startsWith("πŸ”„")) {
514
- const settings = readSettings();
515
- delete settings.externalBackupDir;
516
- writeSettings(settings);
652
+ const saved = updateSettings((settings) => { delete settings.externalBackupDir; });
653
+ if (!saved.ok) {
654
+ ctx.ui.notify(`Could not reset external backup directory: ${saved.error}`, "error");
655
+ return;
656
+ }
517
657
  ctx.ui.notify("Reset to default. Will use environment variable or default path.", "info");
518
658
  }
519
659
  }
@@ -528,13 +668,18 @@ async function showHelp(ctx: any) {
528
668
  - **Purpose**: Quick rollback during normal use
529
669
  - **Survives**: Pi updates, extension installs, config changes
530
670
  - **Does NOT survive**: Clean reinstall (\`rm -rf ~/.pi\`)
531
- - **Format**: Uncompressed directories (fast access)
671
+ - **Format**: Uncompressed directories only (fast access)
532
672
 
533
673
  ### πŸ’Ύ External (${externalDir})
534
674
  - **Purpose**: Disaster recovery
535
675
  - **Survives**: Clean reinstall, disk failure (if copied elsewhere)
536
676
  - **Does NOT survive**: Deleting the backup directory
537
- - **Format**: Compressed archives (.7z/.zip) + optional uncompressed
677
+ - **Format**: Compressed archives (.7z/.zip)
678
+
679
+ ## ⚠️ Credentials
680
+
681
+ Backups include \`auth.json\` (API keys / tokens) unless you set \`PI_BACKUP_EXCLUDE_AUTH=1\`.
682
+ Treat every backup as a secret: keep it private and never share or commit it.
538
683
 
539
684
  ## Configuration Priority
540
685
 
@@ -545,6 +690,7 @@ The external backup directory is resolved in this order:
545
690
  3. **Default**: \`~/pi-backups/\`
546
691
 
547
692
  Use **βš™οΈ Configure external backup directory** in the main menu to change the settings.json value.
693
+ If settings.json is corrupt, it is never overwritten: defaults are used and you are told.
548
694
 
549
695
  ## When to Use Which
550
696
 
@@ -558,10 +704,13 @@ Use **βš™οΈ Configure external backup directory** in the main menu to change th
558
704
 
559
705
  ## Restore Process
560
706
 
561
- 1. Select backup β†’ Restore
562
- 2. Script overwrites all config in \`~/.pi/agent/\`
563
- 3. **After restore**: Run \`cd ~/.pi/agent && npm install\`
564
- 4. Verify: \`pi --version\`, \`/ctx-doctor\`
707
+ Pi cannot restore itself while it is running, so the TUI never restores in-process.
708
+
709
+ 1. Select backup β†’ Restore β†’ confirm
710
+ 2. The TUI shows (and copies, where possible) the exact command
711
+ 3. **Exit Pi**, then run that command in a terminal
712
+ 4. **After restore**: Run \`cd ~/.pi/agent && npm install\`
713
+ 5. Verify: \`pi --version\`, \`/ctx-doctor\`
565
714
 
566
715
  ## Manual Backup/Restore
567
716
 
@@ -574,6 +723,9 @@ BACKUP_ROOT=/mnt/backups ./backup-pi.sh
574
723
 
575
724
  # Restore from external
576
725
  ./restore-pi.sh ~/pi-backups/pi-backup-20260811-143000
726
+
727
+ # Scripted restore (skip the prompt)
728
+ PI_BACKUP_ASSUME_YES=1 ./restore-pi.sh ~/pi-backups/pi-backup-20260811-143000
577
729
  \`\`\`
578
730
 
579
731
  ## What Gets Backed Up
@@ -596,4 +748,4 @@ BACKUP_ROOT=/mnt/backups ./backup-pi.sh
596
748
  ❌ Lock files`;
597
749
 
598
750
  await ctx.ui.editor("Pi Backup Manager Help", help);
599
- }
751
+ }
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@jamiefutch/pi-backup",
3
- "version": "1.1.11",
3
+ "version": "1.1.13",
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": {
7
7
  "typecheck": "tsc --noEmit",
8
- "build": "tsc"
8
+ "build": "tsc",
9
+ "test": "bash tests/run.sh"
9
10
  },
10
11
  "keywords": [
11
12
  "pi",
@@ -30,8 +31,10 @@
30
31
  "extensions",
31
32
  "*.sh",
32
33
  "*.ps1",
34
+ "backup-manifest.txt",
33
35
  "LICENSE",
34
- "README.md"
36
+ "README.md",
37
+ "CHANGELOG.md"
35
38
  ],
36
39
  "pi": {
37
40
  "extensions": [
@@ -42,7 +45,7 @@
42
45
  "@earendil-works/pi-coding-agent": "*"
43
46
  },
44
47
  "devDependencies": {
45
- "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-coding-agent": "^0.84.1",
46
49
  "@types/node": "^22.0.0",
47
50
  "typescript": "^5.6.0"
48
51
  },