@link-assistant/claude-profiles 1.2.3

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,2610 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Claude Profiles - Manage Claude configuration profiles using GitHub Gists
5
+ *
6
+ * This tool uses use-m for dynamic module loading, requiring no package.json dependencies.
7
+ * It stores Claude configurations as base64-encoded zip files in GitHub Gists.
8
+ *
9
+ * Features:
10
+ * - Store/restore Claude configurations
11
+ * - Multiple profile management
12
+ * - Profile verification
13
+ * - Watch mode with filesystem monitoring
14
+ * - Verbose logging and file logging support
15
+ */
16
+
17
+ import fs from 'fs';
18
+ import path from 'path';
19
+ import os from 'os';
20
+ import { createWriteStream } from 'fs';
21
+ import { promises as fsPromises } from 'fs';
22
+ import { createHash } from 'crypto';
23
+ import { execSync } from 'child_process';
24
+
25
+ // Dynamically load dependencies using use-m
26
+ const { use } = eval(
27
+ await fetch('https://unpkg.com/use-m/use.js').then(r => r.text())
28
+ );
29
+
30
+ // Load required packages dynamically with specific versions
31
+ const [{ $ }, yargs, yargsHelpers, archiver] = await Promise.all([
32
+ use('command-stream@0.7.0'),
33
+ use('yargs@17.7.2'),
34
+ use('yargs@17.7.2/helpers'),
35
+ use('archiver@7.0.1')
36
+ ]);
37
+
38
+ const { hideBin } = yargsHelpers;
39
+
40
+ const PROFILE_NAME_REGEX = /^[a-z0-9-]+$/;
41
+
42
+ // GitHub Gist size limits (in bytes)
43
+ // Note: Files are base64 encoded before upload, which increases size by ~33%
44
+ // Empirically determined: 38.43 MB (compressed) = 51.11 MB (base64) fails with HTTP 422
45
+ const GIST_SIZE_LIMIT_API = 40 * 1024 * 1024; // ~40 MB for base64 encoded content (conservative)
46
+ const GIST_SIZE_LIMIT_WEB = 20 * 1024 * 1024; // ~20 MB via web interface (conservative)
47
+ const GIST_SIZE_WARNING = 10 * 1024 * 1024; // 10 MB warning threshold (before base64 encoding)
48
+
49
+ // Global logging configuration
50
+ let logFile = null;
51
+ let isVerbose = false;
52
+
53
+ /**
54
+ * Initialize logging based on options
55
+ */
56
+ function initLogging(options) {
57
+ isVerbose = options.verbose || false;
58
+
59
+ if (options.log !== undefined) {
60
+ // User specified log option
61
+ if (typeof options.log === 'string' && options.log.length > 0) {
62
+ // User provided specific log file path
63
+ logFile = options.log;
64
+ } else {
65
+ // User enabled logging with default filename
66
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '-').slice(0, -5);
67
+ logFile = `claude-profiles-${timestamp}.txt.log`;
68
+ }
69
+
70
+ // Write initial log header
71
+ const header = `Claude Profiles Log - Started at ${new Date().toISOString()}\n${'='.repeat(60)}\n\n`;
72
+ try {
73
+ fs.writeFileSync(logFile, header);
74
+ log('INFO', `Logging initialized to file: ${logFile}`);
75
+ } catch (error) {
76
+ log('WARN', `Could not create log file: ${error.message}`);
77
+ logFile = null;
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Log a message to console and optionally to file
84
+ */
85
+ function log(level, message, data = null) {
86
+ const timestamp = new Date().toISOString();
87
+
88
+ // Console output - clean and user-friendly (no timestamps or level prefixes for INFO)
89
+ if (level === 'ERROR') {
90
+ console.error(message);
91
+ } else if (level === 'WARN') {
92
+ console.warn(message);
93
+ } else if (level === 'INFO') {
94
+ console.log(message);
95
+ } else if (level === 'DEBUG' && isVerbose) {
96
+ console.log(`[DEBUG] ${message}`);
97
+ } else if (level === 'TRACE' && isVerbose) {
98
+ console.log(`[TRACE] ${message}`);
99
+ }
100
+
101
+ // File output - detailed with timestamps and levels
102
+ if (logFile) {
103
+ try {
104
+ const logEntry = `[${timestamp}] [${level}] ${message}`;
105
+ let fileEntry = logEntry;
106
+ if (data) {
107
+ fileEntry += '\n' + JSON.stringify(data, null, 2);
108
+ }
109
+ fs.appendFileSync(logFile, fileEntry + '\n');
110
+ } catch (error) {
111
+ // Silently fail to avoid recursive logging issues
112
+ }
113
+ }
114
+ }
115
+
116
+ // Files and directories to backup/restore
117
+ const BACKUP_PATHS = [
118
+ { source: '~/.claude', dest: '.claude', canSkipProjects: true },
119
+ { source: '~/.claude.json', dest: '.claude.json' },
120
+ { source: '~/.claude.json.backup', dest: '.claude.json.backup' }
121
+ ];
122
+
123
+ /**
124
+ * Get backup paths based on options
125
+ */
126
+ function getBackupPaths(options = {}) {
127
+ if (options.skipProjects) {
128
+ return BACKUP_PATHS.map(item => {
129
+ if (item.canSkipProjects) {
130
+ // For ~/.claude directory, create a custom backup that excludes projects
131
+ return { ...item, skipProjects: true };
132
+ }
133
+ return item;
134
+ });
135
+ }
136
+ return BACKUP_PATHS;
137
+ }
138
+
139
+ /**
140
+ * Expand tilde (~) to home directory
141
+ */
142
+ function expandHome(filepath) {
143
+ if (filepath.startsWith('~/')) {
144
+ return path.join(os.homedir(), filepath.slice(2));
145
+ }
146
+ return filepath;
147
+ }
148
+
149
+ /**
150
+ * Format bytes into human readable format
151
+ */
152
+ function formatBytes(bytes) {
153
+ if (bytes === 0) return '0 B';
154
+ const k = 1024;
155
+ const sizes = ['B', 'KB', 'MB', 'GB'];
156
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
157
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
158
+ }
159
+
160
+ /**
161
+ * Display directory tree with sizes
162
+ */
163
+ async function displayDirectoryTree(dirPath, options = {}) {
164
+ const skipProjects = options.skipProjects || false;
165
+ const maxDepth = options.maxDepth || 3;
166
+
167
+ async function getDirectorySize(dir, currentDepth = 0) {
168
+ try {
169
+ let totalSize = 0;
170
+ const items = [];
171
+
172
+ if (currentDepth >= maxDepth) {
173
+ return { size: 0, items: [] };
174
+ }
175
+
176
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true });
177
+
178
+ for (const entry of entries) {
179
+ const fullPath = path.join(dir, entry.name);
180
+
181
+ // Skip projects folder if requested
182
+ if (skipProjects && (entry.name === 'projects' || entry.name.startsWith('projects'))) {
183
+ continue;
184
+ }
185
+
186
+ try {
187
+ if (entry.isDirectory()) {
188
+ const subResult = await getDirectorySize(fullPath, currentDepth + 1);
189
+ totalSize += subResult.size;
190
+ items.push({
191
+ name: entry.name,
192
+ type: 'directory',
193
+ size: subResult.size,
194
+ items: subResult.items
195
+ });
196
+ } else if (entry.isFile()) {
197
+ const stats = await fsPromises.stat(fullPath);
198
+ totalSize += stats.size;
199
+ items.push({
200
+ name: entry.name,
201
+ type: 'file',
202
+ size: stats.size
203
+ });
204
+ }
205
+ } catch (error) {
206
+ // Skip files/directories we can't access
207
+ }
208
+ }
209
+
210
+ return { size: totalSize, items };
211
+ } catch (error) {
212
+ return { size: 0, items: [] };
213
+ }
214
+ }
215
+
216
+ function printTree(items, prefix = '', isLast = true) {
217
+ items.forEach((item, index) => {
218
+ const isLastItem = index === items.length - 1;
219
+ const connector = isLastItem ? '└── ' : '├── ';
220
+ const sizeStr = formatBytes(item.size);
221
+
222
+ if (item.type === 'directory') {
223
+ log('INFO', `${prefix}${connector}📁 ${item.name}/ (${sizeStr})`);
224
+ if (item.items && item.items.length > 0) {
225
+ const newPrefix = prefix + (isLastItem ? ' ' : '│ ');
226
+ printTree(item.items, newPrefix);
227
+ }
228
+ } else {
229
+ log('INFO', `${prefix}${connector}📄 ${item.name} (${sizeStr})`);
230
+ }
231
+ });
232
+ }
233
+
234
+ try {
235
+ const expandedPath = expandHome(dirPath);
236
+ const stats = await fsPromises.stat(expandedPath);
237
+
238
+ if (stats.isDirectory()) {
239
+ log('INFO', `📊 Directory structure and sizes${skipProjects ? ' (excluding projects)' : ''}:`);
240
+ log('INFO', '');
241
+
242
+ const result = await getDirectorySize(expandedPath);
243
+ log('INFO', `📁 ${path.basename(expandedPath)}/ (${formatBytes(result.size)})`);
244
+
245
+ if (result.items.length > 0) {
246
+ printTree(result.items);
247
+ }
248
+
249
+ log('INFO', '');
250
+ return result.size;
251
+ }
252
+ } catch (error) {
253
+ // Directory doesn't exist or can't be accessed
254
+ return 0;
255
+ }
256
+
257
+ return 0;
258
+ }
259
+
260
+ /**
261
+ * Check if archive size is within GitHub Gist limits
262
+ * Note: Files are base64 encoded before upload, which increases size by ~33%
263
+ */
264
+ function checkArchiveSize(sizeBytes, isBase64Encoded = false) {
265
+ const actualSize = isBase64Encoded ? sizeBytes : Math.ceil(sizeBytes * 1.33); // Base64 encoding overhead
266
+
267
+ const result = {
268
+ size: sizeBytes,
269
+ actualUploadSize: actualSize,
270
+ sizeFormatted: formatBytes(sizeBytes),
271
+ actualSizeFormatted: formatBytes(actualSize),
272
+ withinLimit: actualSize <= GIST_SIZE_LIMIT_API,
273
+ isLarge: actualSize > GIST_SIZE_WARNING,
274
+ exceedsWebLimit: actualSize > GIST_SIZE_LIMIT_WEB,
275
+ exceedsApiLimit: actualSize > GIST_SIZE_LIMIT_API
276
+ };
277
+
278
+ return result;
279
+ }
280
+
281
+ /**
282
+ * Get credentials from macOS Keychain
283
+ */
284
+ async function getKeychainCredentials() {
285
+ try {
286
+ const result = await $`security find-generic-password -a $USER -s "Claude Code-credentials" -w`.run({
287
+ capture: true,
288
+ mirror: false
289
+ });
290
+
291
+ if (result.code !== 0) {
292
+ return null;
293
+ }
294
+
295
+ const keychainData = JSON.parse(result.stdout.trim());
296
+ // Return the keychain data exactly as stored (no conversion)
297
+ // This preserves the exact format Claude Code expects
298
+ return keychainData;
299
+ } catch (error) {
300
+ // Credentials not found in keychain
301
+ return null;
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Convert credentials between platform formats
307
+ */
308
+ function convertCredentialsFormat(credentials, targetPlatform) {
309
+ if (targetPlatform === 'darwin') {
310
+ // Convert to macOS Keychain format
311
+ if (credentials.claudeAiOauth) {
312
+ // Already in keychain format
313
+ return credentials;
314
+ } else if (credentials.access_token) {
315
+ // Linux format with underscores - convert to macOS format
316
+ return {
317
+ claudeAiOauth: {
318
+ accessToken: credentials.access_token,
319
+ refreshToken: credentials.refresh_token,
320
+ expiresAt: credentials.expiry_date || credentials.expiresAt,
321
+ scopes: credentials.scopes || ['user:inference'],
322
+ subscriptionType: credentials.subscriptionType || 'max'
323
+ }
324
+ };
325
+ } else if (credentials.accessToken) {
326
+ // Already in Claude's format but not wrapped - wrap it
327
+ return {
328
+ claudeAiOauth: credentials
329
+ };
330
+ }
331
+ } else {
332
+ // Convert to Linux format (Linux now uses the same format as macOS with claudeAiOauth wrapper)
333
+ if (credentials.claudeAiOauth) {
334
+ // Already in the correct format for modern Linux Claude
335
+ return credentials;
336
+ } else if (credentials.access_token) {
337
+ // Old Linux format with underscores - convert to new format with wrapper
338
+ return {
339
+ claudeAiOauth: {
340
+ accessToken: credentials.access_token,
341
+ refreshToken: credentials.refresh_token,
342
+ expiresAt: credentials.expiry_date || credentials.expiresAt,
343
+ scopes: credentials.scopes || ['user:inference'],
344
+ subscriptionType: credentials.subscriptionType || 'max'
345
+ }
346
+ };
347
+ } else if (credentials.accessToken) {
348
+ // Claude format without wrapper - wrap it
349
+ return {
350
+ claudeAiOauth: credentials
351
+ };
352
+ }
353
+ }
354
+ // Return as-is if format is unknown
355
+ return credentials;
356
+ }
357
+
358
+ /**
359
+ * Set credentials in macOS Keychain
360
+ */
361
+ async function setKeychainCredentials(credentials) {
362
+ try {
363
+ // Convert to macOS format if needed
364
+ const keychainData = convertCredentialsFormat(credentials, 'darwin');
365
+
366
+ const jsonStr = JSON.stringify(keychainData);
367
+ // Escape exactly like Claude Code does - only escape double quotes
368
+ const escapedJson = jsonStr.replace(/"/g, '\\"');
369
+
370
+ try {
371
+ // Use execSync like Claude Code does, with shell: true
372
+ const command = `security add-generic-password -U -a $USER -s "Claude Code-credentials" -w "${escapedJson}"`;
373
+ execSync(command, {
374
+ shell: true,
375
+ stdio: isVerbose ? 'inherit' : 'ignore'
376
+ });
377
+
378
+ /* FAILED APPROACH - command-stream $ function adds extra quotes
379
+ * This approach fails because the command-stream library's $ function
380
+ * adds an extra layer of shell quoting when interpolating variables.
381
+ * When we pass "${escapedJson}", it gets wrapped in single quotes,
382
+ * resulting in the keychain storing: '{"claudeAiOauth":{...}}'
383
+ * instead of: {"claudeAiOauth":{...}}
384
+ *
385
+ * This makes the JSON invalid and Claude Code cannot parse it.
386
+ *
387
+ * const result = await $`security add-generic-password -U -a $USER -s "Claude Code-credentials" -w "${escapedJson}"`.run({
388
+ * capture: true,
389
+ * mirror: false
390
+ * });
391
+ * return result.code === 0;
392
+ */
393
+
394
+ return true;
395
+ } catch (error) {
396
+ if (isVerbose) {
397
+ log('DEBUG', `Security command failed: ${error.message}`);
398
+ }
399
+ return false;
400
+ }
401
+ } catch (error) {
402
+ if (isVerbose) {
403
+ log('DEBUG', `Failed to set keychain credentials: ${error.message}`);
404
+ }
405
+ return false;
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Validate profile name
411
+ */
412
+ function validateProfileName(name) {
413
+ if (!PROFILE_NAME_REGEX.test(name)) {
414
+ throw new Error(`Invalid profile name: ${name}. Only lowercase letters, numbers, and hyphens are allowed.`);
415
+ }
416
+ return true;
417
+ }
418
+
419
+ /**
420
+ * Find or create the gist for storing profiles
421
+ */
422
+ async function findOrCreateGist() {
423
+ // Use API to find gist by description
424
+ try {
425
+ const apiResult = await $`gh api /gists --jq '.[] | select(.description == "claude-profiles-backup") | .id' | head -1`.run({ capture: true, mirror: false });
426
+ const gistId = apiResult.stdout.trim();
427
+ if (gistId) {
428
+ return gistId;
429
+ }
430
+ } catch (error) {
431
+ // Check if it's a network/API error
432
+ if (error.message?.includes('404') || error.message?.includes('not found')) {
433
+ // Gist not found, will create new one
434
+ } else if (error.message?.includes('rate limit')) {
435
+ log('ERROR', '⚠️ GitHub API rate limit exceeded');
436
+ log('ERROR', ' Please wait a few minutes and try again');
437
+ log('ERROR', ' Or authenticate with a different account');
438
+ process.exit(1);
439
+ } else if (error.message?.includes('network') || error.message?.includes('timeout')) {
440
+ log('ERROR', '🌐 Network error while accessing GitHub');
441
+ log('ERROR', ' Please check your internet connection and try again');
442
+ process.exit(1);
443
+ }
444
+ // Otherwise, gist just doesn't exist yet
445
+ }
446
+
447
+ // Create new gist if not found
448
+ log('INFO', `📝 Creating new secret gist for profile storage...`);
449
+ const tempFile = path.join(os.tmpdir(), 'claude-profiles-readme.md');
450
+ const readmeContent = `# Claude Profiles Backup
451
+
452
+ This gist stores Claude profile backups as zip files (base64 encoded).
453
+
454
+ Created by claude-profiles.mjs tool.
455
+ Do not edit this gist manually.
456
+
457
+ ## Profiles
458
+
459
+ Each .zip.base64 file contains a backup of:
460
+ - ~/.claude/ directory
461
+ - ~/.claude.json
462
+ - ~/.claude.json.backup
463
+ `;
464
+
465
+ await fsPromises.writeFile(tempFile, readmeContent);
466
+
467
+ try {
468
+ const createResult = await $`gh gist create ${tempFile} --desc "claude-profiles-backup" 2>&1`.run({ capture: true, mirror: false });
469
+ await fsPromises.unlink(tempFile);
470
+
471
+ if (createResult.code !== 0) {
472
+ if (createResult.stdout.includes('gist.github.com')) {
473
+ // Sometimes gh returns non-zero but still creates the gist
474
+ const gistUrl = createResult.stdout.match(/https:\/\/gist\.github\.com\/\S+/)?.[0];
475
+ if (gistUrl) {
476
+ const gistId = gistUrl.split('/').pop();
477
+ log('INFO', `✅ Gist created successfully`);
478
+ return gistId;
479
+ }
480
+ }
481
+
482
+ // Parse error message for common issues
483
+ if (createResult.stdout.includes('permission') || createResult.stdout.includes('scope')) {
484
+ // Get detailed auth status for better error reporting
485
+ const authStatus = await getDetailedAuthStatus();
486
+
487
+ log('ERROR', '❌ Permission error creating gist');
488
+ log('ERROR', '');
489
+
490
+ if (authStatus) {
491
+ log('ERROR', '🔍 Current GitHub Authentication:');
492
+ log('ERROR', ` • Account: ${authStatus.account || 'Not logged in'}`);
493
+ log('ERROR', ` • Protocol: ${authStatus.protocol || 'Unknown'}`);
494
+ log('ERROR', ` • Token scopes: ${authStatus.scopes.join(', ') || 'None'}`);
495
+ log('ERROR', ` • Has gist scope: ${authStatus.hasGistScope ? 'Yes' : 'No'}`);
496
+ log('ERROR', '');
497
+ }
498
+
499
+ log('ERROR', '💡 To fix:');
500
+ log('ERROR', ' • Add gist scope: gh auth refresh -s gist');
501
+ log('ERROR', ' • Or re-login: gh auth login');
502
+ process.exit(1);
503
+ }
504
+
505
+ throw new Error(createResult.stdout || 'Unknown error creating gist');
506
+ }
507
+
508
+ // Extract gist ID from the URL
509
+ const gistUrl = createResult.stdout.trim();
510
+ const gistId = gistUrl.split('/').pop();
511
+ log('INFO', `✅ Gist created successfully`);
512
+ return gistId;
513
+ } catch (error) {
514
+ await fsPromises.unlink(tempFile).catch(() => {});
515
+
516
+ log('ERROR', '❌ Failed to create gist');
517
+ log('ERROR', ` Error: ${error.message}`);
518
+ log('ERROR', '');
519
+
520
+ // Get detailed auth status for diagnostics
521
+ const authStatus = await getDetailedAuthStatus();
522
+ if (authStatus) {
523
+ log('ERROR', '🔍 Current GitHub Authentication:');
524
+ log('ERROR', ` • Account: ${authStatus.account || 'Not logged in'}`);
525
+ log('ERROR', ` • Token scopes: ${authStatus.scopes.join(', ') || 'None'}`);
526
+ log('ERROR', ` • Has gist scope: ${authStatus.hasGistScope ? 'Yes' : 'No'}`);
527
+ log('ERROR', '');
528
+ }
529
+
530
+ log('ERROR', '🔧 Troubleshooting:');
531
+ log('ERROR', ' 1. Check your internet connection');
532
+ log('ERROR', ' 2. Ensure you have gist permissions: gh auth refresh -s gist');
533
+ log('ERROR', ' 3. Try creating a test gist manually: echo "test" | gh gist create -');
534
+ process.exit(1);
535
+ }
536
+ }
537
+
538
+ /**
539
+ * List all profiles in the gist
540
+ */
541
+ async function listProfiles() {
542
+ try {
543
+ const gistId = await findOrCreateGist();
544
+
545
+ // Get gist files
546
+ const result = await $`gh gist view ${gistId} --files`.run({ capture: true, mirror: false });
547
+ const allFiles = result.stdout.trim().split('\n');
548
+ const files = allFiles.filter(f => f.endsWith('.zip.base64'));
549
+
550
+ if (files.length === 0) {
551
+ log('INFO', '📋 No saved profiles found');
552
+ log('INFO', '');
553
+ log('INFO', '💡 To store your first profile, run:');
554
+ log('INFO', ' ./claude-profiles.mjs --store <profile_name>');
555
+ return;
556
+ }
557
+
558
+ log('INFO', '📋 Saved Claude Profiles:');
559
+ log('INFO', '');
560
+
561
+ for (const file of files) {
562
+ const profileName = file.replace('.zip.base64', '');
563
+ log('INFO', ` 📁 ${profileName}`);
564
+ }
565
+
566
+ log('INFO', '');
567
+ log('INFO', '💡 Usage:');
568
+ log('INFO', ' ./claude-profiles.mjs --restore <profile_name> # Restore a profile');
569
+ log('INFO', ' ./claude-profiles.mjs --store <profile_name> # Store current state');
570
+ log('INFO', ' ./claude-profiles.mjs --delete <profile_name> # Delete a profile');
571
+ } catch (error) {
572
+ log('ERROR', `❌ Error listing profiles: ${error.message}`);
573
+ log('ERROR', '');
574
+
575
+ // Get detailed auth status for diagnostics
576
+ const authStatus = await getDetailedAuthStatus();
577
+ if (authStatus && !authStatus.authenticated) {
578
+ log('ERROR', '🔍 GitHub Authentication Issue:');
579
+ log('ERROR', ' • Not authenticated with GitHub');
580
+ log('ERROR', ' • Run: gh auth login');
581
+ log('ERROR', '');
582
+ } else if (authStatus && !authStatus.hasGistScope) {
583
+ log('ERROR', '🔍 GitHub Authentication:');
584
+ log('ERROR', ` • Account: ${authStatus.account}`);
585
+ log('ERROR', ` • Missing gist scope`);
586
+ log('ERROR', ' • Run: gh auth refresh -s gist');
587
+ log('ERROR', '');
588
+ }
589
+
590
+ log('ERROR', '🔧 Troubleshooting:');
591
+ log('ERROR', ' • Check your internet connection');
592
+ log('ERROR', ' • Try: gh gist list --limit 1');
593
+ process.exit(1);
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Verify local files before creating a profile
599
+ */
600
+ async function verifyLocalFiles() {
601
+ // On macOS, credentials can be in Keychain instead of file
602
+ const isMacOS = process.platform === 'darwin';
603
+
604
+ const checks = [
605
+ {
606
+ path: expandHome('~/.claude/.credentials.json'),
607
+ essential: !isMacOS, // Not essential on macOS (might use Keychain)
608
+ description: 'Claude credentials (file)',
609
+ icon: '🔑',
610
+ skipIfKeychainExists: isMacOS // Skip if we find credentials in Keychain
611
+ },
612
+ {
613
+ path: expandHome('~/.claude.json'),
614
+ essential: true,
615
+ description: 'Claude configuration',
616
+ icon: '⚙️ '
617
+ },
618
+ {
619
+ path: expandHome('~/.claude.json.backup'),
620
+ essential: false,
621
+ description: 'Configuration backup',
622
+ icon: '💾'
623
+ }
624
+ ];
625
+
626
+ log('INFO', '🔍 Verifying local Claude configuration...');
627
+ log('INFO', '');
628
+
629
+ let hasAllEssential = true;
630
+ const issues = [];
631
+
632
+ // Check macOS Keychain first if on macOS
633
+ let hasKeychainCreds = false;
634
+ if (isMacOS) {
635
+ const keychainCreds = await getKeychainCredentials();
636
+ if (keychainCreds) {
637
+ hasKeychainCreds = true;
638
+ log('INFO', ' 🔐 Claude Keychain credentials: ✅');
639
+ }
640
+ }
641
+
642
+ for (const check of checks) {
643
+ // Skip file-based credentials check if we have Keychain credentials
644
+ if (check.skipIfKeychainExists && hasKeychainCreds) {
645
+ continue;
646
+ }
647
+ try {
648
+ const stats = fs.statSync(check.path);
649
+ if (stats.isFile()) {
650
+ log('INFO', ` ${check.icon} ${check.description}: ✅`);
651
+
652
+ // For credentials, do detailed validation
653
+ if (check.path.includes('.credentials.json')) {
654
+ try {
655
+ const content = fs.readFileSync(check.path, 'utf8');
656
+ const credentials = JSON.parse(content);
657
+
658
+ // Check for both old and new formats
659
+ if (credentials.claudeAiOauth) {
660
+ // New format with wrapper
661
+ const oauth = credentials.claudeAiOauth;
662
+ const requiredFields = ['accessToken', 'refreshToken'];
663
+ const optionalFields = ['expiresAt', 'scopes', 'subscriptionType'];
664
+ const missing = requiredFields.filter(f => !oauth[f]);
665
+ const present = [...requiredFields, ...optionalFields].filter(f => oauth[f]);
666
+
667
+ if (missing.length > 0) {
668
+ log('WARN', ` └─ ⚠️ Missing required fields in claudeAiOauth: ${missing.join(', ')}`);
669
+ issues.push(`Credentials missing in claudeAiOauth: ${missing.join(', ')}`);
670
+ } else {
671
+ log('INFO', ` └─ Valid OAuth format with claudeAiOauth wrapper`);
672
+ }
673
+ if (present.length > 0) {
674
+ log('INFO', ` └─ Present fields: claudeAiOauth.{${present.join(', ')}}`);
675
+ }
676
+ } else {
677
+ // Old format with underscores
678
+ const requiredFields = ['access_token', 'refresh_token'];
679
+ const optionalFields = ['expiry_date', 'scopes', 'subscriptionType'];
680
+ const missing = requiredFields.filter(f => !credentials[f]);
681
+ const present = [...requiredFields, ...optionalFields].filter(f => credentials[f]);
682
+
683
+ if (missing.length > 0) {
684
+ log('WARN', ` └─ ⚠️ Missing required fields (old format): ${missing.join(', ')}`);
685
+ issues.push(`Credentials missing: ${missing.join(', ')}`);
686
+ }
687
+ if (present.length > 0) {
688
+ log('INFO', ` └─ Present fields (old format): ${present.join(', ')}`);
689
+ }
690
+ }
691
+ } catch {
692
+ log('WARN', ` └─ ⚠️ Could not parse credentials file`);
693
+ issues.push('Credentials file could not be parsed');
694
+ }
695
+ }
696
+ }
697
+ } catch (error) {
698
+ if (check.essential) {
699
+ log('ERROR', ` ${check.icon} ${check.description}: ❌ Missing (REQUIRED)`);
700
+ hasAllEssential = false;
701
+ issues.push(`Missing required file: ${check.description}`);
702
+ } else {
703
+ log('WARN', ` ${check.icon} ${check.description}: ⚠️ Missing (optional)`);
704
+ }
705
+ }
706
+ }
707
+
708
+ log('INFO', '');
709
+
710
+ return { valid: hasAllEssential, issues };
711
+ }
712
+
713
+ /**
714
+ * Verify a profile contains essential files
715
+ */
716
+ async function verifyProfile(profileName) {
717
+ try {
718
+ validateProfileName(profileName);
719
+
720
+ log('INFO', `🔍 Verifying Claude profile: ${profileName}`);
721
+
722
+ // Get gist ID
723
+ const gistId = await findOrCreateGist();
724
+
725
+ // Create temporary directory
726
+ const tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'claude-verify-'));
727
+ const zipPath = path.join(tempDir, `${profileName}.zip`);
728
+
729
+ try {
730
+ // Download the profile using API (more reliable for large files)
731
+ log('INFO', `📥 Downloading profile for verification...`);
732
+
733
+ // First check if file exists
734
+ const filesResult = await $`gh gist view ${gistId} --files`.run({ capture: true, mirror: false });
735
+ if (!filesResult.stdout.includes(`${profileName}.zip.base64`)) {
736
+ throw new Error(`Profile '${profileName}' not found`);
737
+ }
738
+
739
+ // Use API to get the raw URL
740
+ const apiResult = await $`gh api /gists/${gistId}`.run({ capture: true, mirror: false });
741
+ const gistData = JSON.parse(apiResult.stdout);
742
+ const fileData = gistData.files[`${profileName}.zip.base64`];
743
+
744
+ if (!fileData) {
745
+ throw new Error(`Profile '${profileName}' not found in gist`);
746
+ }
747
+
748
+ let base64Data;
749
+
750
+ if (fileData.truncated) {
751
+ // File is truncated, need to fetch from raw_url
752
+ log('INFO', ` Profile is large (${Math.round(fileData.size / 1024)} KB), downloading from raw URL...`);
753
+ const rawResult = await $`curl -s "${fileData.raw_url}"`.run({ capture: true, mirror: false });
754
+ base64Data = rawResult.stdout.trim();
755
+ } else {
756
+ // Small file, content is in the API response
757
+ base64Data = fileData.content.trim();
758
+ }
759
+
760
+ // Validate it's base64
761
+ if (!base64Data || base64Data.length === 0) {
762
+ throw new Error('Downloaded profile data is empty');
763
+ }
764
+
765
+ try {
766
+ const zipBuffer = Buffer.from(base64Data, 'base64');
767
+ await fsPromises.writeFile(zipPath, zipBuffer);
768
+ } catch (err) {
769
+ throw new Error(`Failed to decode profile data: ${err.message}`);
770
+ }
771
+
772
+ // Extract to verify contents
773
+ log('INFO', `📂 Extracting profile...`);
774
+ const extractDir = path.join(tempDir, 'extract');
775
+ await fsPromises.mkdir(extractDir);
776
+
777
+ const extractResult = await $`unzip -q -o ${zipPath} -d ${extractDir} 2>&1`.run({
778
+ capture: true,
779
+ mirror: false
780
+ });
781
+
782
+ if (extractResult.code !== 0) {
783
+ throw new Error(`Failed to extract profile archive: ${extractResult.stdout || 'Unknown error'}`);
784
+ }
785
+
786
+ // Check for essential files
787
+ log('INFO', `\n📋 Checking profile contents:`);
788
+ log('INFO', '');
789
+
790
+ const checks = [
791
+ {
792
+ path: '.claude/.credentials.json',
793
+ essential: true,
794
+ description: 'Claude credentials',
795
+ icon: '🔑'
796
+ },
797
+ {
798
+ path: '.claude.json',
799
+ essential: true,
800
+ description: 'Claude configuration',
801
+ icon: '⚙️'
802
+ },
803
+ {
804
+ path: '.claude.json.backup',
805
+ essential: false,
806
+ description: 'Configuration backup',
807
+ icon: '💾'
808
+ },
809
+ {
810
+ path: '.claude',
811
+ essential: false,
812
+ description: 'Claude directory',
813
+ icon: '📁',
814
+ isDirectory: true
815
+ }
816
+ ];
817
+
818
+ let hasEssentialFiles = true;
819
+ let totalSize = 0;
820
+ const foundFiles = [];
821
+
822
+ for (const check of checks) {
823
+ const fullPath = path.join(extractDir, check.path);
824
+ try {
825
+ const stats = await fsPromises.stat(fullPath);
826
+
827
+ if (check.isDirectory) {
828
+ if (stats.isDirectory()) {
829
+ // Count files in directory
830
+ const files = await fsPromises.readdir(fullPath);
831
+ log('INFO', ` ${check.icon} ${check.description}: ✅ (${files.length} files)`);
832
+ foundFiles.push(check.path);
833
+ } else {
834
+ log('INFO', ` ${check.icon} ${check.description}: ❌ Not a directory`);
835
+ }
836
+ } else {
837
+ if (stats.isFile()) {
838
+ const sizeKB = Math.round(stats.size / 1024);
839
+ totalSize += stats.size;
840
+ log('INFO', ` ${check.icon} ${check.description}: ✅ (${sizeKB} KB)`);
841
+ foundFiles.push(check.path);
842
+
843
+ // For credentials, do detailed validation
844
+ if (check.path === '.claude/.credentials.json') {
845
+ try {
846
+ const content = await fsPromises.readFile(fullPath, 'utf8');
847
+ const credentials = JSON.parse(content);
848
+
849
+ // Check for various credential formats
850
+ const hasLinuxFormat = credentials.access_token && credentials.refresh_token;
851
+ const hasMacOSFormat = credentials.claudeAiOauth && credentials.claudeAiOauth.accessToken;
852
+ const hasSessionKey = credentials.sessionKey || credentials.token;
853
+
854
+ if (hasLinuxFormat) {
855
+ const fields = [];
856
+ if (credentials.access_token) fields.push('access_token');
857
+ if (credentials.refresh_token) fields.push('refresh_token');
858
+ if (credentials.expiry_date) fields.push('expiry_date');
859
+ if (credentials.scopes) fields.push('scopes');
860
+ if (credentials.subscriptionType) fields.push('subscriptionType');
861
+ log('INFO', ` └─ Linux format credentials detected`);
862
+ log('INFO', ` Fields: ${fields.join(', ')}`);
863
+ } else if (hasMacOSFormat) {
864
+ const oauth = credentials.claudeAiOauth;
865
+ const fields = [];
866
+ if (oauth.accessToken) fields.push('accessToken');
867
+ if (oauth.refreshToken) fields.push('refreshToken');
868
+ if (oauth.expiresAt) fields.push('expiresAt');
869
+ if (oauth.scopes) fields.push('scopes');
870
+ if (oauth.subscriptionType) fields.push('subscriptionType');
871
+ log('INFO', ` └─ macOS/OAuth format credentials detected`);
872
+ log('INFO', ` Fields: claudeAiOauth.{${fields.join(', ')}}`);
873
+ } else if (hasSessionKey) {
874
+ log('INFO', ` └─ Session-based credentials detected`);
875
+ } else {
876
+ log('INFO', ` └─ ⚠️ Credentials format unclear`);
877
+ const keys = Object.keys(credentials).slice(0, 5);
878
+ if (keys.length > 0) {
879
+ log('INFO', ` Found fields: ${keys.join(', ')}${keys.length < Object.keys(credentials).length ? '...' : ''}`);
880
+ }
881
+ }
882
+ } catch {
883
+ log('WARN', ` └─ ⚠️ Could not parse credentials file`);
884
+ }
885
+ }
886
+ } else {
887
+ log('INFO', ` ${check.icon} ${check.description}: ❌ Not a file`);
888
+ if (check.essential) {
889
+ hasEssentialFiles = false;
890
+ }
891
+ }
892
+ }
893
+ } catch (error) {
894
+ if (check.essential) {
895
+ log('ERROR', ` ${check.icon} ${check.description}: ❌ Missing (REQUIRED)`);
896
+ hasEssentialFiles = false;
897
+ } else {
898
+ log('WARN', ` ${check.icon} ${check.description}: ⚠️ Missing (optional)`);
899
+ }
900
+ }
901
+ }
902
+
903
+ // Show summary
904
+ log('INFO', '');
905
+ log('INFO', `📊 Summary:`);
906
+ log('INFO', ` • Profile size: ${Math.round(totalSize / 1024)} KB compressed`);
907
+ log('INFO', ` • Files found: ${foundFiles.length}`);
908
+ log('INFO', ` • Created: Check gist history`);
909
+
910
+ log('INFO', '');
911
+ if (hasEssentialFiles) {
912
+ log('INFO', `✅ Profile '${profileName}' is valid and ready to restore`);
913
+ } else {
914
+ log('INFO', `❌ Profile '${profileName}' is missing essential files`);
915
+ log('INFO', ' This profile may not restore correctly');
916
+ log('INFO', ' Consider creating a new backup with --store');
917
+ }
918
+
919
+ } finally {
920
+ // Clean up temp directory
921
+ await fsPromises.rm(tempDir, { recursive: true }).catch(() => {});
922
+ }
923
+
924
+ } catch (error) {
925
+ log('ERROR', '❌ Error verifying profile:', error.message);
926
+
927
+ if (error.message.includes('not found')) {
928
+ log('ERROR', '');
929
+ log('ERROR', '📝 Available profiles:');
930
+ try {
931
+ const listResult = await $`gh gist view ${gistId} --files`.run({ capture: true, mirror: false });
932
+ const files = listResult.stdout.trim().split('\n').filter(f => f.endsWith('.zip.base64'));
933
+ if (files.length > 0) {
934
+ files.forEach(f => log('ERROR', ` • ${f.replace('.zip.base64', '')}`));
935
+ } else {
936
+ log('ERROR', ' (no profiles found)');
937
+ }
938
+ } catch {}
939
+ } else if (error.message.includes('unzip')) {
940
+ log('ERROR', '');
941
+ log('ERROR', '📦 The unzip command is required for verification');
942
+ log('ERROR', ' • macOS: Should be pre-installed');
943
+ log('ERROR', ' • Ubuntu/Debian: sudo apt-get install unzip');
944
+ log('ERROR', ' • Alpine: apk add unzip');
945
+ }
946
+
947
+ process.exit(1);
948
+ }
949
+ }
950
+
951
+ /**
952
+ * Calculate hash of files to detect changes
953
+ */
954
+ async function calculateFilesHash(options = {}) {
955
+ const hash = createHash('sha256');
956
+ const backupPaths = getBackupPaths(options);
957
+
958
+ for (const item of backupPaths) {
959
+ const sourcePath = expandHome(item.source);
960
+
961
+ try {
962
+ const stats = await fsPromises.stat(sourcePath);
963
+
964
+ if (stats.isDirectory()) {
965
+ // Hash directory structure and file names
966
+ const files = await fsPromises.readdir(sourcePath, { recursive: true });
967
+
968
+ // Filter out projects directory if skipProjects is enabled
969
+ const filteredFiles = item.skipProjects ?
970
+ files.filter(file => !file.startsWith('projects/') && !file.startsWith('projects\\')) :
971
+ files;
972
+
973
+ hash.update(filteredFiles.sort().join('|'));
974
+
975
+ // Hash each file's content
976
+ for (const file of filteredFiles) {
977
+ const filePath = path.join(sourcePath, file);
978
+ try {
979
+ const fileStats = await fsPromises.stat(filePath);
980
+ if (fileStats.isFile()) {
981
+ const content = await fsPromises.readFile(filePath);
982
+ hash.update(content);
983
+ }
984
+ } catch {
985
+ // Skip files we can't read
986
+ }
987
+ }
988
+ } else if (stats.isFile()) {
989
+ const content = await fsPromises.readFile(sourcePath);
990
+ hash.update(content);
991
+ }
992
+ } catch {
993
+ // File doesn't exist, that's ok
994
+ }
995
+ }
996
+
997
+ // Include macOS Keychain credentials in hash if on macOS
998
+ if (process.platform === 'darwin') {
999
+ const keychainCreds = await getKeychainCredentials();
1000
+ if (keychainCreds) {
1001
+ hash.update(JSON.stringify(keychainCreds));
1002
+ }
1003
+ }
1004
+
1005
+ return hash.digest('hex');
1006
+ }
1007
+
1008
+ /**
1009
+ * Watch for changes and auto-save profile
1010
+ */
1011
+ async function watchProfile(profileName, options = {}) {
1012
+ try {
1013
+ validateProfileName(profileName);
1014
+
1015
+ log('INFO', `🔄 Starting watch mode for profile: ${profileName}`);
1016
+ log('INFO', ' Monitoring Claude configuration files for changes...');
1017
+ log('INFO', ' Press Ctrl+C to stop watching');
1018
+
1019
+ // Verify initial state
1020
+ const verification = await verifyLocalFiles();
1021
+ if (!verification.valid) {
1022
+ log('ERROR', '❌ Cannot start watch mode - essential files are missing');
1023
+ if (verification.issues.length > 0) {
1024
+ verification.issues.forEach(issue => log('ERROR', ` • ${issue}`));
1025
+ }
1026
+ process.exit(1);
1027
+ }
1028
+
1029
+ log('INFO', '');
1030
+
1031
+ // Show directory tree in watch mode to help understand potential size issues
1032
+ await displayDirectoryTree('~/.claude', { skipProjects: options.skipProjects });
1033
+
1034
+ let lastSaveTime = 0;
1035
+ let pendingSave = false;
1036
+ let saveInProgress = false;
1037
+ let lastHash = await calculateFilesHash(options);
1038
+ let saveCount = 0;
1039
+
1040
+ log('DEBUG', `Initial files hash: ${lastHash}`);
1041
+
1042
+ // Watch configuration
1043
+ const minSaveInterval = 30000; // Minimum 30 seconds between saves
1044
+ const debounceDelay = 2000; // Wait 2 seconds after last change
1045
+
1046
+ let pendingSaveTimeout = null;
1047
+ let changeDetected = false;
1048
+ const watchers = [];
1049
+
1050
+ // Function to handle file changes
1051
+ const handleFileChange = (eventType, filename) => {
1052
+ log('DEBUG', `File change detected: ${eventType} on ${filename || 'unknown'}`);
1053
+ changeDetected = true;
1054
+
1055
+ // Clear any pending save timeout
1056
+ if (pendingSaveTimeout) {
1057
+ clearTimeout(pendingSaveTimeout);
1058
+ log('TRACE', 'Cleared pending save timeout due to new change');
1059
+ }
1060
+
1061
+ // Debounce: wait for changes to settle
1062
+ log('TRACE', `Setting debounce timer for ${debounceDelay}ms`);
1063
+ pendingSaveTimeout = setTimeout(async () => {
1064
+ if (!changeDetected) {
1065
+ log('TRACE', 'No changes detected during debounce period');
1066
+ return;
1067
+ }
1068
+ changeDetected = false;
1069
+
1070
+ const now = Date.now();
1071
+ const timeSinceLastSave = now - lastSaveTime;
1072
+
1073
+ if (timeSinceLastSave >= minSaveInterval) {
1074
+ // Check if save is already in progress
1075
+ if (saveInProgress) {
1076
+ log('DEBUG', 'Save already in progress, skipping duplicate save request');
1077
+ return;
1078
+ }
1079
+
1080
+ // Enough time has passed, save immediately
1081
+ log('INFO', '📝 Changes detected, saving profile...');
1082
+ saveInProgress = true;
1083
+
1084
+ try {
1085
+ // Don't show all the normal save output in watch mode
1086
+ const originalLog = console.log;
1087
+ const originalError = console.error;
1088
+
1089
+ if (!isVerbose) {
1090
+ console.log = () => {};
1091
+ console.error = () => {};
1092
+ }
1093
+
1094
+ await saveProfileSilent(profileName, options);
1095
+
1096
+ if (!isVerbose) {
1097
+ console.log = originalLog;
1098
+ console.error = originalError;
1099
+ }
1100
+
1101
+ lastSaveTime = now;
1102
+ lastHash = await calculateFilesHash(options);
1103
+ saveCount++;
1104
+ pendingSave = false;
1105
+
1106
+ log('INFO', `✅ Profile auto-saved (save #${saveCount})`);
1107
+ log('DEBUG', `Save completed at ${new Date(now).toISOString()}`);
1108
+ log('TRACE', `Next save allowed after: ${new Date(now + minSaveInterval).toISOString()}`);
1109
+
1110
+ } catch (error) {
1111
+ log('ERROR', `❌ Failed to auto-save: ${error.message}`);
1112
+ // Exit watch mode if the profile is too large, as continuing won't help
1113
+ if (error.message.includes('Profile too large')) {
1114
+ log('INFO', '👋 Stopping watch mode...');
1115
+ // Clean up watchers
1116
+ for (const watcher of watchers) {
1117
+ watcher.close();
1118
+ }
1119
+ process.exit(1);
1120
+ }
1121
+ } finally {
1122
+ saveInProgress = false;
1123
+ }
1124
+ } else if (!pendingSave) {
1125
+ // Schedule a save for when enough time has passed
1126
+ pendingSave = true;
1127
+ const timeToWait = minSaveInterval - timeSinceLastSave;
1128
+ log('INFO', `⏳ Changes detected, will save in ${Math.round(timeToWait / 1000)} seconds...`);
1129
+
1130
+ pendingSaveTimeout = setTimeout(async () => {
1131
+ if (pendingSave) {
1132
+ // Check if save is already in progress
1133
+ if (saveInProgress) {
1134
+ log('DEBUG', 'Save already in progress, skipping pending save request');
1135
+ pendingSave = false;
1136
+ return;
1137
+ }
1138
+
1139
+ log('INFO', '📝 Saving pending changes...');
1140
+ saveInProgress = true;
1141
+
1142
+ try {
1143
+ const originalLog = console.log;
1144
+ const originalError = console.error;
1145
+
1146
+ if (!isVerbose) {
1147
+ console.log = () => {};
1148
+ console.error = () => {};
1149
+ }
1150
+
1151
+ await saveProfileSilent(profileName, options);
1152
+
1153
+ if (!isVerbose) {
1154
+ console.log = originalLog;
1155
+ console.error = originalError;
1156
+ }
1157
+
1158
+ lastSaveTime = Date.now();
1159
+ lastHash = await calculateFilesHash(options);
1160
+ saveCount++;
1161
+ pendingSave = false;
1162
+
1163
+ log('INFO', `✅ Profile auto-saved (save #${saveCount})`);
1164
+
1165
+ } catch (error) {
1166
+ log('ERROR', `❌ Failed to auto-save: ${error.message}`);
1167
+ // Exit watch mode if the profile is too large, as continuing won't help
1168
+ if (error.message.includes('Profile too large')) {
1169
+ log('INFO', '👋 Stopping watch mode...');
1170
+ // Clean up watchers
1171
+ for (const watcher of watchers) {
1172
+ watcher.close();
1173
+ }
1174
+ process.exit(1);
1175
+ }
1176
+ pendingSave = false;
1177
+ } finally {
1178
+ saveInProgress = false;
1179
+ }
1180
+ }
1181
+ }, timeToWait);
1182
+ }
1183
+ }, debounceDelay);
1184
+ };
1185
+
1186
+ // Set up file watchers for each backup path
1187
+ const backupPaths = getBackupPaths(options);
1188
+ for (const item of backupPaths) {
1189
+ const watchPath = expandHome(item.source);
1190
+
1191
+ try {
1192
+ const stats = await fsPromises.stat(watchPath);
1193
+
1194
+ // Create watcher with options
1195
+ const watcher = fs.watch(watchPath, {
1196
+ recursive: stats.isDirectory(),
1197
+ persistent: true
1198
+ }, (eventType, filename) => {
1199
+ handleFileChange(eventType, `${item.source}/${filename || ''}`);
1200
+ });
1201
+
1202
+ // Add error handler for watcher
1203
+ watcher.on('error', (error) => {
1204
+ log('ERROR', `Watcher error for ${item.source}: ${error.message}`);
1205
+ });
1206
+
1207
+ watchers.push(watcher);
1208
+ log('DEBUG', `Watching: ${item.source} (${stats.isDirectory() ? 'directory' : 'file'})`);
1209
+ } catch (error) {
1210
+ if (error.code !== 'ENOENT') {
1211
+ log('WARN', `Could not watch ${item.source}: ${error.message}`);
1212
+ }
1213
+ }
1214
+ }
1215
+
1216
+ if (watchers.length === 0) {
1217
+ log('ERROR', 'No files to watch!');
1218
+ process.exit(1);
1219
+ }
1220
+
1221
+ log('INFO', `📊 Watching ${watchers.length} paths for changes`);
1222
+
1223
+ // Set up periodic check for keychain changes on macOS
1224
+ let keychainCheckInterval = null;
1225
+ if (process.platform === 'darwin') {
1226
+ log('INFO', '🔐 Monitoring macOS Keychain for credential changes');
1227
+
1228
+ // Check keychain every 5 seconds for changes
1229
+ keychainCheckInterval = setInterval(async () => {
1230
+ try {
1231
+ // Skip keychain check if save is in progress to avoid hash conflicts
1232
+ if (saveInProgress) {
1233
+ log('TRACE', 'Skipping keychain check - save in progress');
1234
+ return;
1235
+ }
1236
+
1237
+ const currentHash = await calculateFilesHash(options);
1238
+ if (currentHash !== lastHash) {
1239
+ log('DEBUG', 'Keychain credentials changed, triggering save');
1240
+ handleFileChange('change', 'macOS Keychain');
1241
+ }
1242
+ } catch (error) {
1243
+ log('ERROR', `Error checking keychain: ${error.message}`);
1244
+ }
1245
+ }, 5000);
1246
+ }
1247
+
1248
+ // Handle graceful shutdown
1249
+ process.on('SIGINT', () => {
1250
+ log('INFO', '\n👋 Stopping watch mode...');
1251
+
1252
+ // Close all watchers
1253
+ watchers.forEach(watcher => watcher.close());
1254
+
1255
+ // Clear keychain check interval
1256
+ if (keychainCheckInterval) {
1257
+ clearInterval(keychainCheckInterval);
1258
+ }
1259
+
1260
+ // Clear any pending timeouts
1261
+ if (pendingSaveTimeout) {
1262
+ clearTimeout(pendingSaveTimeout);
1263
+ log('INFO', 'Cancelled pending save');
1264
+ }
1265
+
1266
+ log('INFO', `Watch mode ended - Total saves: ${saveCount}`);
1267
+
1268
+ if (logFile) {
1269
+ console.log(`\n📄 Log saved to: ${logFile}`);
1270
+ }
1271
+
1272
+ process.exit(0);
1273
+ });
1274
+
1275
+ // Keep process running
1276
+ process.stdin.resume();
1277
+
1278
+ } catch (error) {
1279
+ log('ERROR', `❌ Error in watch mode: ${error.message}`);
1280
+ process.exit(1);
1281
+ }
1282
+ }
1283
+
1284
+ /**
1285
+ * Save profile without console output (for watch mode)
1286
+ */
1287
+ async function saveProfileSilent(profileName, options = {}) {
1288
+ // This is a simplified version of saveProfile that doesn't output to console
1289
+ // It reuses the same logic but skips console.log calls
1290
+
1291
+ const tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'claude-profile-'));
1292
+ const zipPath = path.join(tempDir, `${profileName}.zip`);
1293
+
1294
+ try {
1295
+ const output = createWriteStream(zipPath);
1296
+ const archive = archiver('zip', { zlib: { level: 9 } });
1297
+
1298
+ const archivePromise = new Promise((resolve, reject) => {
1299
+ output.on('close', () => resolve());
1300
+ archive.on('error', (err) => reject(err));
1301
+ });
1302
+
1303
+ archive.pipe(output);
1304
+
1305
+ // Add files to archive
1306
+ const backupPaths = getBackupPaths(options);
1307
+ for (const item of backupPaths) {
1308
+ const sourcePath = expandHome(item.source);
1309
+ try {
1310
+ const stats = await fsPromises.stat(sourcePath);
1311
+ if (stats.isDirectory()) {
1312
+ if (item.skipProjects) {
1313
+ // Add directory but exclude projects folder and nested .claude directories
1314
+ const files = await fsPromises.readdir(sourcePath, { recursive: true });
1315
+ const filteredFiles = files.filter(file => {
1316
+ // Exclude projects folder
1317
+ if (file.startsWith('projects/') || file.startsWith('projects\\')) {
1318
+ return false;
1319
+ }
1320
+
1321
+ // Fix recursive .claude directory issue:
1322
+ // Exclude any .claude directory that is nested inside another directory
1323
+ // (not at the root level of the main .claude directory)
1324
+ const pathParts = file.split(/[/\\]/);
1325
+ for (let i = 0; i < pathParts.length; i++) {
1326
+ if (pathParts[i] === '.claude' && i > 0) {
1327
+ // Found .claude directory nested inside another directory
1328
+ return false;
1329
+ }
1330
+ }
1331
+
1332
+ return true;
1333
+ });
1334
+
1335
+ // Add each file individually
1336
+ for (const file of filteredFiles) {
1337
+ const fullPath = path.join(sourcePath, file);
1338
+ try {
1339
+ const fileStat = await fsPromises.stat(fullPath);
1340
+ if (fileStat.isFile()) {
1341
+ archive.file(fullPath, { name: path.join(item.dest, file) });
1342
+ }
1343
+ } catch {
1344
+ // Skip files we can't read
1345
+ }
1346
+ }
1347
+ } else {
1348
+ archive.directory(sourcePath, item.dest);
1349
+ }
1350
+ } else if (stats.isFile()) {
1351
+ archive.file(sourcePath, { name: item.dest });
1352
+ }
1353
+ } catch {
1354
+ // Skip missing files
1355
+ }
1356
+ }
1357
+
1358
+ // Handle macOS Keychain credentials (silent version)
1359
+ if (process.platform === 'darwin') {
1360
+ const keychainCreds = await getKeychainCredentials();
1361
+ if (keychainCreds) {
1362
+ const credsPath = path.join(tempDir, '.macos.credentials.json');
1363
+ await fsPromises.writeFile(credsPath, JSON.stringify(keychainCreds, null, 2));
1364
+ archive.file(credsPath, { name: '.macos.credentials.json' });
1365
+ }
1366
+ }
1367
+
1368
+ await archive.finalize();
1369
+ await archivePromise;
1370
+
1371
+ // Check archive size before proceeding
1372
+ const zipBuffer = await fsPromises.readFile(zipPath);
1373
+ const sizeCheck = checkArchiveSize(zipBuffer.length);
1374
+
1375
+ // Show archive size even in silent mode for watch visibility
1376
+ log('INFO', `📦 Archive created: ${sizeCheck.sizeFormatted}`);
1377
+
1378
+ if (!sizeCheck.withinLimit) {
1379
+ const errorMsg = `Profile too large (${sizeCheck.sizeFormatted} compressed, ${sizeCheck.actualSizeFormatted} when base64 encoded) - GitHub Gist limit is ${formatBytes(GIST_SIZE_LIMIT_API)}`;
1380
+
1381
+ if (options.skipProjects) {
1382
+ // Already tried with projects skipped, this is as small as it gets
1383
+ throw new Error(`${errorMsg}\nConsider manually cleaning up ~/.claude/ directory.`);
1384
+ } else {
1385
+ // Suggest using --skip-projects
1386
+ throw new Error(`${errorMsg}\nConsider using --skip-projects option to exclude the projects folder.`);
1387
+ }
1388
+ }
1389
+
1390
+ // Get or create gist
1391
+ const gistId = await findOrCreateGist();
1392
+
1393
+ // Convert to base64
1394
+ const base64Content = zipBuffer.toString('base64');
1395
+ const base64Path = path.join(tempDir, `${profileName}.zip.base64`);
1396
+ await fsPromises.writeFile(base64Path, base64Content);
1397
+
1398
+ // Upload to gist
1399
+ const uploadResult = await $`gh gist edit ${gistId} --add ${base64Path} --filename "${profileName}.zip.base64" 2>&1`.run({
1400
+ capture: true,
1401
+ mirror: false
1402
+ });
1403
+
1404
+ if (uploadResult.code !== 0 && !uploadResult.stdout.includes('Added')) {
1405
+ // Check for size-related errors first
1406
+ if (uploadResult.stdout.includes('422') || uploadResult.stdout.includes('contents are too large')) {
1407
+ const sizeCheck = checkArchiveSize(zipBuffer.length);
1408
+ const errorMsg = `Failed to upload: HTTP 422 - Content too large (${sizeCheck.sizeFormatted} compressed, ${sizeCheck.actualSizeFormatted} when base64 encoded)`;
1409
+
1410
+ if (options.skipProjects) {
1411
+ throw new Error(`${errorMsg}\nGitHub Gist limit is ${formatBytes(GIST_SIZE_LIMIT_API)}.\nConsider cleaning up ~/.claude/ directory manually.`);
1412
+ } else {
1413
+ throw new Error(`${errorMsg}\nGitHub Gist limit is ${formatBytes(GIST_SIZE_LIMIT_API)}.\nTry using --skip-projects option to exclude the projects folder.`);
1414
+ }
1415
+ }
1416
+
1417
+ // Get detailed auth status for better error reporting
1418
+ const authStatus = await getDetailedAuthStatus();
1419
+
1420
+ if (uploadResult.stdout.includes('409') || uploadResult.stdout.includes('Gist cannot be updated')) {
1421
+ log('ERROR', `Failed to upload: HTTP 409 - Gist cannot be updated`);
1422
+
1423
+ if (authStatus) {
1424
+ log('ERROR', '🔍 GitHub Authentication Status:');
1425
+ log('ERROR', ` • Account: ${authStatus.account || 'Not logged in'}`);
1426
+ log('ERROR', ` • Protocol: ${authStatus.protocol || 'Unknown'}`);
1427
+ log('ERROR', ` • Token scopes: ${authStatus.scopes.join(', ') || 'None'}`);
1428
+ log('ERROR', ` • Has gist scope: ${authStatus.hasGistScope ? 'Yes' : 'No'}`);
1429
+
1430
+ if (isVerbose && authStatus.rawOutput) {
1431
+ log('DEBUG', 'Full gh auth status output:', authStatus.rawOutput);
1432
+ }
1433
+ }
1434
+
1435
+ log('ERROR', '');
1436
+ log('ERROR', '💡 Possible causes:');
1437
+ log('ERROR', ' • Gist may be owned by a different account');
1438
+ log('ERROR', ' • Token may lack write permissions');
1439
+ log('ERROR', ' • Try: gh auth refresh -s gist');
1440
+
1441
+ throw new Error(`Failed to upload: HTTP 409 - Gist cannot be updated`);
1442
+ }
1443
+
1444
+ throw new Error(`Failed to upload: ${uploadResult.stdout}`);
1445
+ }
1446
+
1447
+ log('DEBUG', `Profile uploaded successfully - Size: ${Math.round(zipBuffer.length / 1024)} KB`);
1448
+
1449
+ } finally {
1450
+ await fsPromises.rm(tempDir, { recursive: true }).catch(() => {});
1451
+ }
1452
+ }
1453
+
1454
+ /**
1455
+ * Delete a profile from the gist
1456
+ */
1457
+ async function deleteProfile(profileName) {
1458
+ try {
1459
+ validateProfileName(profileName);
1460
+
1461
+ log('INFO', `🗑️ Deleting Claude profile: ${profileName}`);
1462
+
1463
+ // Get gist ID
1464
+ const gistId = await findOrCreateGist();
1465
+
1466
+ // Check if profile exists
1467
+ const listResult = await $`gh gist view ${gistId} --files`.run({ capture: true, mirror: false });
1468
+ const files = listResult.stdout.trim().split('\n').filter(f => f);
1469
+ const profileFile = `${profileName}.zip.base64`;
1470
+
1471
+ if (!files.includes(profileFile)) {
1472
+ throw new Error(`Profile '${profileName}' not found`);
1473
+ }
1474
+
1475
+ // We need to use a different approach - gh api to update gist
1476
+
1477
+ // Create update payload - set the file to delete as null
1478
+ const updatePayload = {
1479
+ files: {
1480
+ [profileFile]: null // Setting to null deletes the file
1481
+ }
1482
+ };
1483
+
1484
+ // Update the gist using gh api
1485
+ const updateResult = await $`gh api /gists/${gistId} --method PATCH --input -`.run({
1486
+ capture: true,
1487
+ mirror: false,
1488
+ stdin: JSON.stringify(updatePayload)
1489
+ });
1490
+
1491
+ if (updateResult.code === 0) {
1492
+ log('INFO', `✅ Profile '${profileName}' deleted successfully`);
1493
+ } else {
1494
+ throw new Error('Failed to delete profile from gist');
1495
+ }
1496
+
1497
+ } catch (error) {
1498
+ log('ERROR', '❌ Error deleting profile:', error.message);
1499
+
1500
+ if (error.message.includes('not found')) {
1501
+ log('ERROR', '');
1502
+ log('ERROR', '📝 Profile does not exist. Available profiles:');
1503
+ try {
1504
+ await listProfiles();
1505
+ } catch {}
1506
+ } else {
1507
+ log('ERROR', '');
1508
+
1509
+ // Get detailed auth status for diagnostics
1510
+ const authStatus = await getDetailedAuthStatus();
1511
+ if (authStatus) {
1512
+ log('ERROR', '🔍 Current GitHub Authentication:');
1513
+ log('ERROR', ` • Account: ${authStatus.account || 'Not logged in'}`);
1514
+ log('ERROR', ` • Has gist scope: ${authStatus.hasGistScope ? 'Yes' : 'No'}`);
1515
+ log('ERROR', '');
1516
+ }
1517
+
1518
+ log('ERROR', '🔧 Troubleshooting:');
1519
+ log('ERROR', ' • Check your internet connection');
1520
+ log('ERROR', ' • Verify the profile exists: ./claude-profiles.mjs --list');
1521
+ log('ERROR', ' • Ensure you have write permissions to the gist');
1522
+ log('ERROR', ' • Try: gh auth refresh -s gist');
1523
+ }
1524
+ process.exit(1);
1525
+ }
1526
+ }
1527
+
1528
+ /**
1529
+ * Save current Claude configuration to a profile
1530
+ */
1531
+ async function saveProfile(profileName, options = {}) {
1532
+ try {
1533
+ validateProfileName(profileName);
1534
+
1535
+ log('INFO', `💾 Preparing to save Claude profile: ${profileName}`);
1536
+ log('INFO', '');
1537
+
1538
+ // Verify local files before creating backup
1539
+ const verification = await verifyLocalFiles();
1540
+
1541
+ if (!verification.valid) {
1542
+ log('ERROR', '❌ Cannot create profile - essential files are missing');
1543
+ log('ERROR', '');
1544
+ if (verification.issues.length > 0) {
1545
+ log('ERROR', 'Issues found:');
1546
+ verification.issues.forEach(issue => log('ERROR', ` • ${issue}`));
1547
+ log('ERROR', '');
1548
+ }
1549
+ log('ERROR', '💡 Tips:');
1550
+ log('ERROR', ' • Ensure Claude is properly configured');
1551
+ log('ERROR', ' • Try using Claude at least once to generate config files');
1552
+ log('ERROR', ' • Check that ~/.claude/ directory exists');
1553
+ process.exit(1);
1554
+ }
1555
+
1556
+ log('INFO', '✅ Local configuration verified');
1557
+ log('INFO', '');
1558
+
1559
+ // Display directory tree with sizes before archiving
1560
+ await displayDirectoryTree('~/.claude', { skipProjects: options.skipProjects });
1561
+
1562
+ // Create temporary directory for staging
1563
+ const tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'claude-profile-'));
1564
+ const zipPath = path.join(tempDir, `${profileName}.zip`);
1565
+
1566
+ // Create zip archive
1567
+ const output = createWriteStream(zipPath);
1568
+ const archive = archiver('zip', { zlib: { level: 9 } });
1569
+
1570
+ // Create a promise to track when archiving is complete
1571
+ const archivePromise = new Promise((resolve, reject) => {
1572
+ output.on('close', () => {
1573
+ resolve();
1574
+ });
1575
+
1576
+ archive.on('error', (err) => {
1577
+ reject(err);
1578
+ });
1579
+ });
1580
+
1581
+ archive.pipe(output);
1582
+
1583
+ // Add files to archive
1584
+ let hasFiles = false;
1585
+ const backupPaths = getBackupPaths(options);
1586
+ for (const item of backupPaths) {
1587
+ const sourcePath = expandHome(item.source);
1588
+
1589
+ try {
1590
+ const stats = await fsPromises.stat(sourcePath);
1591
+
1592
+ if (stats.isDirectory()) {
1593
+ if (item.skipProjects) {
1594
+ // Add directory but exclude projects folder and nested .claude directories
1595
+ const files = await fsPromises.readdir(sourcePath, { recursive: true });
1596
+ const filteredFiles = files.filter(file => {
1597
+ // Exclude projects folder
1598
+ if (file.startsWith('projects/') || file.startsWith('projects\\')) {
1599
+ return false;
1600
+ }
1601
+
1602
+ // Fix recursive .claude directory issue:
1603
+ // Exclude any .claude directory that is nested inside another directory
1604
+ // (not at the root level of the main .claude directory)
1605
+ const pathParts = file.split(/[/\\]/);
1606
+ for (let i = 0; i < pathParts.length; i++) {
1607
+ if (pathParts[i] === '.claude' && i > 0) {
1608
+ // Found .claude directory nested inside another directory
1609
+ return false;
1610
+ }
1611
+ }
1612
+
1613
+ return true;
1614
+ });
1615
+
1616
+ log('INFO', `📂 Added directory: ${item.source} (excluding projects folder)`);
1617
+
1618
+ // Add each file individually
1619
+ for (const file of filteredFiles) {
1620
+ const fullPath = path.join(sourcePath, file);
1621
+ try {
1622
+ const fileStat = await fsPromises.stat(fullPath);
1623
+ if (fileStat.isFile()) {
1624
+ archive.file(fullPath, { name: path.join(item.dest, file) });
1625
+ }
1626
+ } catch {
1627
+ // Skip files we can't read
1628
+ }
1629
+ }
1630
+ hasFiles = true;
1631
+ } else {
1632
+ archive.directory(sourcePath, item.dest);
1633
+ log('INFO', `📂 Added directory: ${item.source}`);
1634
+ hasFiles = true;
1635
+ }
1636
+ } else if (stats.isFile()) {
1637
+ archive.file(sourcePath, { name: item.dest });
1638
+ log('INFO', `📄 Added file: ${item.source}`);
1639
+ hasFiles = true;
1640
+ }
1641
+ } catch (error) {
1642
+ if (error.code !== 'ENOENT') {
1643
+ log('WARN', `⚠️ Could not add ${item.source}: ${error.message}`);
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ // Handle macOS Keychain credentials
1649
+ if (process.platform === 'darwin') {
1650
+ const keychainCreds = await getKeychainCredentials();
1651
+ if (keychainCreds) {
1652
+ // Save credentials to a temporary file and add to archive
1653
+ const credsPath = path.join(tempDir, '.macos.credentials.json');
1654
+ await fsPromises.writeFile(credsPath, JSON.stringify(keychainCreds, null, 2));
1655
+ archive.file(credsPath, { name: '.macos.credentials.json' });
1656
+ log('INFO', `🔐 Added macOS Keychain credentials`);
1657
+ hasFiles = true;
1658
+ } else {
1659
+ log('WARN', 'No credentials found in macOS Keychain');
1660
+ }
1661
+ }
1662
+
1663
+ if (!hasFiles) {
1664
+ log('ERROR', '❌ No Claude configuration files found to backup');
1665
+ log('ERROR', '');
1666
+ log('ERROR', '📝 Expected files:');
1667
+ log('ERROR', ' • ~/.claude/ directory');
1668
+ log('ERROR', ' • ~/.claude.json file');
1669
+ log('ERROR', ' • ~/.claude.json.backup file');
1670
+ log('ERROR', '');
1671
+ log('ERROR', '🔧 This usually means Claude is not configured yet');
1672
+ log('ERROR', ' Please use Claude at least once to generate config files');
1673
+ await fsPromises.rm(tempDir, { recursive: true });
1674
+ process.exit(1);
1675
+ }
1676
+
1677
+ await archive.finalize();
1678
+
1679
+ // Wait for the archive to be written to disk
1680
+ await archivePromise;
1681
+
1682
+ const archiveStats = await fsPromises.stat(zipPath);
1683
+ const sizeCheck = checkArchiveSize(archiveStats.size);
1684
+ log('INFO', `📦 Archive created: ${sizeCheck.sizeFormatted}`);
1685
+
1686
+ // Check if archive is too large before uploading
1687
+ if (!sizeCheck.withinLimit) {
1688
+ log('ERROR', '');
1689
+ log('ERROR', `❌ Profile is too large (${sizeCheck.sizeFormatted} compressed, ${sizeCheck.actualSizeFormatted} when base64 encoded) for GitHub Gist`);
1690
+ log('ERROR', ` GitHub Gist limit: ${formatBytes(GIST_SIZE_LIMIT_API)}`);
1691
+
1692
+ if (options.skipProjects) {
1693
+ log('ERROR', ' Consider cleaning up ~/.claude/ directory manually');
1694
+ } else {
1695
+ log('ERROR', ' Consider using --skip-projects option to exclude the projects folder');
1696
+ }
1697
+
1698
+ throw new Error('Profile too large');
1699
+ }
1700
+
1701
+ // Show warning for large profiles
1702
+ if (sizeCheck.isLarge) {
1703
+ log('INFO', `⚠️ Large profile detected (${sizeCheck.sizeFormatted} compressed, ${sizeCheck.actualSizeFormatted} when base64 encoded)`);
1704
+ if (sizeCheck.exceedsWebLimit) {
1705
+ log('INFO', ' Profile exceeds web interface limit, but should work via CLI');
1706
+ }
1707
+ }
1708
+
1709
+ // Get or create gist
1710
+ const gistId = await findOrCreateGist();
1711
+
1712
+ // Convert zip to base64 for gist storage
1713
+ const zipBuffer = await fsPromises.readFile(zipPath);
1714
+ const base64Content = zipBuffer.toString('base64');
1715
+
1716
+ // Save base64 as text file
1717
+ const base64Path = path.join(tempDir, `${profileName}.zip.base64`);
1718
+ await fsPromises.writeFile(base64Path, base64Content);
1719
+
1720
+ // Upload base64 file to gist
1721
+ log('INFO', `📤 Uploading profile to gist...`);
1722
+ const uploadResult = await $`gh gist edit ${gistId} --add ${base64Path} --filename "${profileName}.zip.base64" 2>&1`.run({
1723
+ capture: true,
1724
+ mirror: false
1725
+ });
1726
+
1727
+ if (uploadResult.code !== 0 && !uploadResult.stdout.includes('Added')) {
1728
+ // Check for size-related errors first
1729
+ if (uploadResult.stdout.includes('422') || uploadResult.stdout.includes('contents are too large') || uploadResult.stdout.includes('too large')) {
1730
+ const sizeCheck = checkArchiveSize(zipBuffer.length);
1731
+ log('ERROR', `❌ Failed to upload: HTTP 422 - Content too large (${sizeCheck.sizeFormatted} compressed, ${sizeCheck.actualSizeFormatted} when base64 encoded)`);
1732
+ log('ERROR', ` GitHub Gist limit: ${formatBytes(GIST_SIZE_LIMIT_API)}`);
1733
+
1734
+ if (options.skipProjects) {
1735
+ log('ERROR', ' Consider manually cleaning up ~/.claude/ directory');
1736
+ } else {
1737
+ log('ERROR', ' Try using --skip-projects option to exclude the projects folder');
1738
+ }
1739
+
1740
+ throw new Error('Profile too large');
1741
+ } else if (uploadResult.stdout.includes('rate limit')) {
1742
+ log('ERROR', '⚠️ GitHub API rate limit exceeded');
1743
+ log('ERROR', ' Please wait a few minutes and try again');
1744
+ throw new Error('Rate limit exceeded');
1745
+ } else if (uploadResult.stdout.includes('409') || uploadResult.stdout.includes('Gist cannot be updated')) {
1746
+ // Get detailed auth status for better error reporting
1747
+ const authStatus = await getDetailedAuthStatus();
1748
+
1749
+ log('ERROR', '❌ Failed to upload: HTTP 409 - Gist cannot be updated');
1750
+ log('ERROR', '');
1751
+
1752
+ if (authStatus) {
1753
+ log('ERROR', '🔍 Current GitHub Authentication:');
1754
+ log('ERROR', ` • Account: ${authStatus.account || 'Not logged in'}`);
1755
+ log('ERROR', ` • Protocol: ${authStatus.protocol || 'Unknown'}`);
1756
+ log('ERROR', ` • Token scopes: ${authStatus.scopes.join(', ') || 'None'}`);
1757
+ log('ERROR', ` • Has gist scope: ${authStatus.hasGistScope ? 'Yes' : 'No'}`);
1758
+ log('ERROR', '');
1759
+ }
1760
+
1761
+ log('ERROR', '💡 How to fix:');
1762
+ log('ERROR', ' • Gist may be owned by a different account');
1763
+ log('ERROR', ' • Check gist owner: gh gist view ' + gistId);
1764
+ log('ERROR', ' • Re-authenticate: gh auth refresh -s gist');
1765
+ log('ERROR', ' • Or login as the gist owner: gh auth login');
1766
+
1767
+ throw new Error('HTTP 409: Gist cannot be updated');
1768
+ }
1769
+
1770
+ throw new Error(`Failed to upload profile to gist: ${uploadResult.stdout}`);
1771
+ }
1772
+
1773
+ // Clean up temp directory
1774
+ await fsPromises.rm(tempDir, { recursive: true });
1775
+
1776
+ log('INFO', `✅ Profile '${profileName}' saved successfully`);
1777
+ log('INFO', '');
1778
+ log('INFO', '💡 To restore this profile later, run:');
1779
+ log('INFO', ` ./claude-profiles.mjs --restore ${profileName}`);
1780
+ } catch (error) {
1781
+ log('ERROR', '❌ Error saving profile:', error.message);
1782
+ log('ERROR', '');
1783
+
1784
+ if (error.message.includes('Profile too large') || error.message.includes('Rate limit') || error.message.includes('HTTP 409')) {
1785
+ // Specific error messages already shown with detailed diagnostics
1786
+ } else {
1787
+ // Get detailed auth status for diagnostics
1788
+ const authStatus = await getDetailedAuthStatus();
1789
+ if (authStatus && !authStatus.hasGistScope) {
1790
+ log('ERROR', '🔍 Missing gist permissions:');
1791
+ log('ERROR', ` • Account: ${authStatus.account || 'Unknown'}`);
1792
+ log('ERROR', ' • Run: gh auth refresh -s gist');
1793
+ log('ERROR', '');
1794
+ }
1795
+
1796
+ log('ERROR', '🔧 Troubleshooting:');
1797
+ log('ERROR', ' • Check your internet connection');
1798
+ log('ERROR', ' • Try creating a test gist: echo "test" | gh gist create -');
1799
+ log('ERROR', ' • Check available profiles: ./claude-profiles.mjs --list');
1800
+ }
1801
+ process.exit(1);
1802
+ }
1803
+ }
1804
+
1805
+ /**
1806
+ * Verify a downloaded profile before restoring
1807
+ */
1808
+ async function verifyDownloadedProfile(profileName, tempDir) {
1809
+ const extractDir = path.join(tempDir, 'verify');
1810
+ const zipPath = path.join(tempDir, `${profileName}.zip`);
1811
+
1812
+ try {
1813
+ await fsPromises.mkdir(extractDir);
1814
+
1815
+ // Extract for verification
1816
+ const extractResult = await $`unzip -q -o ${zipPath} -d ${extractDir} 2>&1`.run({
1817
+ capture: true,
1818
+ mirror: false
1819
+ });
1820
+
1821
+ if (extractResult.code !== 0) {
1822
+ return { valid: false, issues: ['Failed to extract profile archive'] };
1823
+ }
1824
+
1825
+ // Check for credentials from either platform
1826
+ const hasLinuxCreds = await fsPromises.stat(path.join(extractDir, '.claude/.credentials.json')).catch(() => null);
1827
+ const hasMacOSCreds = await fsPromises.stat(path.join(extractDir, '.macos.credentials.json')).catch(() => null);
1828
+
1829
+ // At least one credential format must be present
1830
+ const hasCredentials = hasLinuxCreds || hasMacOSCreds;
1831
+
1832
+ // Check essential files
1833
+ const checks = [
1834
+ {
1835
+ path: path.join(extractDir, '.claude.json'),
1836
+ essential: true,
1837
+ description: 'Claude configuration'
1838
+ }
1839
+ ];
1840
+
1841
+ let valid = true;
1842
+ const issues = [];
1843
+
1844
+ // Check for credentials
1845
+ if (!hasCredentials) {
1846
+ valid = false;
1847
+ issues.push('Missing: Claude credentials (no .credentials.json or .macos.credentials.json found)');
1848
+ } else {
1849
+ // Validate credential fields with detailed reporting
1850
+ if (hasLinuxCreds) {
1851
+ try {
1852
+ const content = await fsPromises.readFile(path.join(extractDir, '.claude/.credentials.json'), 'utf8');
1853
+ const credentials = JSON.parse(content);
1854
+
1855
+ // Check for both old and new Linux credential formats
1856
+ if (credentials.claudeAiOauth) {
1857
+ // New Linux format (same as macOS)
1858
+ const oauth = credentials.claudeAiOauth;
1859
+ const fields = {
1860
+ 'accessToken': oauth.accessToken,
1861
+ 'refreshToken': oauth.refreshToken,
1862
+ 'expiresAt': oauth.expiresAt,
1863
+ 'scopes': oauth.scopes,
1864
+ 'subscriptionType': oauth.subscriptionType
1865
+ };
1866
+
1867
+ const missingFields = [];
1868
+ const presentFields = [];
1869
+
1870
+ for (const [field, value] of Object.entries(fields)) {
1871
+ if (value === undefined || value === null) {
1872
+ missingFields.push(field);
1873
+ } else {
1874
+ presentFields.push(field);
1875
+ }
1876
+ }
1877
+
1878
+ if (isVerbose) {
1879
+ log('DEBUG', 'Linux credentials format: modern (claudeAiOauth wrapper)');
1880
+ log('DEBUG', ` Present fields: claudeAiOauth.{${presentFields.join(', ')}}`);
1881
+ if (missingFields.length > 0) {
1882
+ log('DEBUG', ` Missing fields: claudeAiOauth.{${missingFields.join(', ')}}`);
1883
+ }
1884
+ }
1885
+
1886
+ if (missingFields.length > 0) {
1887
+ issues.push(`Linux credentials (.credentials.json):\n Present: claudeAiOauth.{${presentFields.join(', ')}}\n Missing: claudeAiOauth.{${missingFields.join(', ')}}`);
1888
+ }
1889
+
1890
+ // Check for required fields
1891
+ if (!oauth.accessToken || !oauth.refreshToken) {
1892
+ valid = false;
1893
+ }
1894
+ } else if (credentials.access_token) {
1895
+ // Old Linux format with underscores
1896
+ const linuxFields = {
1897
+ 'access_token': credentials.access_token,
1898
+ 'refresh_token': credentials.refresh_token,
1899
+ 'expiry_date': credentials.expiry_date,
1900
+ 'scopes': credentials.scopes,
1901
+ 'subscriptionType': credentials.subscriptionType
1902
+ };
1903
+
1904
+ const missingFields = [];
1905
+ const presentFields = [];
1906
+
1907
+ for (const [field, value] of Object.entries(linuxFields)) {
1908
+ if (value === undefined || value === null) {
1909
+ missingFields.push(field);
1910
+ } else {
1911
+ presentFields.push(field);
1912
+ }
1913
+ }
1914
+
1915
+ if (isVerbose) {
1916
+ log('DEBUG', 'Linux credentials format: legacy (underscore format)');
1917
+ log('DEBUG', ` Present fields: ${presentFields.join(', ')}`);
1918
+ if (missingFields.length > 0) {
1919
+ log('DEBUG', ` Missing fields: ${missingFields.join(', ')}`);
1920
+ }
1921
+ log('DEBUG', ' Note: This format will be converted to modern format on restore');
1922
+ }
1923
+
1924
+ if (missingFields.length > 0) {
1925
+ issues.push(`Linux credentials (.credentials.json - old format):\n Present: ${presentFields.join(', ')}\n Missing: ${missingFields.join(', ')}`);
1926
+ }
1927
+
1928
+ // Check for required fields
1929
+ if (!credentials.access_token || !credentials.refresh_token) {
1930
+ valid = false;
1931
+ }
1932
+ } else {
1933
+ issues.push('Linux credentials file has unrecognized format');
1934
+ valid = false;
1935
+ }
1936
+ } catch (e) {
1937
+ issues.push(`Linux credentials file is not valid JSON: ${e.message}`);
1938
+ valid = false;
1939
+ }
1940
+ }
1941
+
1942
+ if (hasMacOSCreds) {
1943
+ try {
1944
+ const content = await fsPromises.readFile(path.join(extractDir, '.macos.credentials.json'), 'utf8');
1945
+ const credentials = JSON.parse(content);
1946
+
1947
+ // Check all expected macOS credential fields
1948
+ if (credentials.claudeAiOauth) {
1949
+ const oauth = credentials.claudeAiOauth;
1950
+ const macFields = {
1951
+ 'accessToken': oauth.accessToken,
1952
+ 'refreshToken': oauth.refreshToken,
1953
+ 'expiresAt': oauth.expiresAt,
1954
+ 'scopes': oauth.scopes,
1955
+ 'subscriptionType': oauth.subscriptionType
1956
+ };
1957
+
1958
+ const missingFields = [];
1959
+ const presentFields = [];
1960
+
1961
+ for (const [field, value] of Object.entries(macFields)) {
1962
+ if (value === undefined || value === null) {
1963
+ missingFields.push(field);
1964
+ } else {
1965
+ presentFields.push(field);
1966
+ }
1967
+ }
1968
+
1969
+ if (missingFields.length > 0) {
1970
+ issues.push(`macOS credentials (.macos.credentials.json):\n Present: claudeAiOauth.{${presentFields.join(', ')}}\n Missing: claudeAiOauth.{${missingFields.join(', ')}}`);
1971
+ }
1972
+
1973
+ // Check for required fields
1974
+ if (!oauth.accessToken || !oauth.refreshToken) {
1975
+ valid = false;
1976
+ }
1977
+ } else {
1978
+ issues.push('macOS credentials missing claudeAiOauth wrapper object');
1979
+ valid = false;
1980
+ }
1981
+ } catch (e) {
1982
+ issues.push(`macOS credentials file is not valid JSON: ${e.message}`);
1983
+ valid = false;
1984
+ }
1985
+ }
1986
+ }
1987
+
1988
+ // Check other essential files
1989
+ for (const check of checks) {
1990
+ try {
1991
+ const stats = await fsPromises.stat(check.path);
1992
+ if (!stats.isFile() && check.essential) {
1993
+ valid = false;
1994
+ issues.push(`Missing: ${check.description}`);
1995
+ }
1996
+ } catch {
1997
+ if (check.essential) {
1998
+ valid = false;
1999
+ issues.push(`Missing: ${check.description}`);
2000
+ }
2001
+ }
2002
+ }
2003
+
2004
+ // Clean up verification directory
2005
+ await fsPromises.rm(extractDir, { recursive: true }).catch(() => {});
2006
+
2007
+ return { valid, issues };
2008
+ } catch (error) {
2009
+ return { valid: false, issues: [error.message] };
2010
+ }
2011
+ }
2012
+
2013
+ /**
2014
+ * Restore a profile from the gist
2015
+ */
2016
+ async function restoreProfile(profileName, options = {}) {
2017
+ try {
2018
+ validateProfileName(profileName);
2019
+
2020
+ log('INFO', `📦 Preparing to restore Claude profile: ${profileName}`);
2021
+ log('INFO', '');
2022
+
2023
+ // Get gist ID
2024
+ const gistId = await findOrCreateGist();
2025
+
2026
+ // Create temporary directory
2027
+ const tempDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'claude-restore-'));
2028
+ const zipPath = path.join(tempDir, `${profileName}.zip`);
2029
+
2030
+ // Download the profile using API (same as verify function)
2031
+ log('INFO', `📥 Downloading profile from gist...`);
2032
+
2033
+ // First check if file exists
2034
+ const filesResult = await $`gh gist view ${gistId} --files`.run({ capture: true, mirror: false });
2035
+ if (!filesResult.stdout.includes(`${profileName}.zip.base64`)) {
2036
+ log('ERROR', `❌ Profile '${profileName}' not found`);
2037
+ log('ERROR', '');
2038
+ log('ERROR', '📝 Available profiles:');
2039
+ const files = filesResult.stdout.trim().split('\n').filter(f => f.endsWith('.zip.base64'));
2040
+ if (files.length > 0) {
2041
+ files.forEach(f => log('ERROR', ` • ${f.replace('.zip.base64', '')}`));
2042
+ } else {
2043
+ log('ERROR', ' (no profiles found)');
2044
+ }
2045
+ throw new Error('Profile not found');
2046
+ }
2047
+
2048
+ // Use API to get the file content or raw URL
2049
+ const apiResult = await $`gh api /gists/${gistId}`.run({ capture: true, mirror: false });
2050
+ const gistData = JSON.parse(apiResult.stdout);
2051
+ const fileData = gistData.files[`${profileName}.zip.base64`];
2052
+
2053
+ if (!fileData) {
2054
+ throw new Error(`Profile '${profileName}' not found in gist`);
2055
+ }
2056
+
2057
+ let base64Data;
2058
+
2059
+ if (fileData.truncated) {
2060
+ // File is truncated, need to fetch from raw_url
2061
+ log('INFO', ` Profile is large (${Math.round(fileData.size / 1024)} KB), downloading from raw URL...`);
2062
+ const rawResult = await $`curl -s "${fileData.raw_url}"`.run({ capture: true, mirror: false });
2063
+ base64Data = rawResult.stdout.trim();
2064
+ } else {
2065
+ // Small file, content is in the API response
2066
+ base64Data = fileData.content.trim();
2067
+ }
2068
+
2069
+ if (!base64Data || base64Data.length === 0) {
2070
+ throw new Error('Downloaded profile data is empty');
2071
+ }
2072
+
2073
+ // Decode base64 and write to zip file
2074
+ const zipBuffer = Buffer.from(base64Data, 'base64');
2075
+ await fsPromises.writeFile(zipPath, zipBuffer);
2076
+
2077
+ // Verify the profile before restoring
2078
+ log('INFO', `🔍 Verifying profile integrity...`);
2079
+ const verification = await verifyDownloadedProfile(profileName, tempDir);
2080
+
2081
+ if (!verification.valid) {
2082
+ log('ERROR', '');
2083
+ log('ERROR', '❌ Cannot restore profile - verification failed');
2084
+ if (verification.issues.length > 0) {
2085
+ log('ERROR', '');
2086
+ log('ERROR', 'Issues found:');
2087
+ verification.issues.forEach(issue => log('ERROR', ` • ${issue}`));
2088
+ }
2089
+ log('ERROR', '');
2090
+ log('ERROR', '💡 This profile appears to be corrupted or incomplete');
2091
+ log('ERROR', ' Consider creating a new backup with --store');
2092
+ throw new Error('Profile verification failed');
2093
+ }
2094
+
2095
+ log('INFO', '✅ Profile verified successfully');
2096
+ log('INFO', '');
2097
+
2098
+ // Extract zip archive for restoration
2099
+ log('INFO', `📂 Extracting profile...`);
2100
+ const extractDir = path.join(tempDir, 'extract');
2101
+ await fsPromises.mkdir(extractDir);
2102
+
2103
+ // Use unzip command to extract
2104
+ await $`unzip -q -o ${zipPath} -d ${extractDir}`.run({ mirror: false });
2105
+
2106
+ // Restore files from extracted directory
2107
+ const backupPaths = getBackupPaths(options);
2108
+ for (const item of backupPaths) {
2109
+ const sourcePath = path.join(extractDir, item.dest);
2110
+ const destPath = expandHome(item.source);
2111
+
2112
+ try {
2113
+ const stats = await fsPromises.stat(sourcePath);
2114
+
2115
+ if (stats.isDirectory()) {
2116
+ // Ensure parent directory exists
2117
+ await fsPromises.mkdir(path.dirname(destPath), { recursive: true });
2118
+
2119
+ if (item.skipProjects) {
2120
+ // Restore directory but skip projects folder
2121
+ await $`rsync -a --exclude='projects/' ${sourcePath}/ ${destPath}/`.run({ mirror: false });
2122
+ log('INFO', `📂 Restored directory (excluding projects): ${item.source}`);
2123
+ } else {
2124
+ // Copy directory recursively
2125
+ await $`cp -r ${sourcePath} ${destPath}`.run({ mirror: false });
2126
+ log('INFO', `📂 Restored directory: ${item.source}`);
2127
+ }
2128
+ } else if (stats.isFile()) {
2129
+ // Ensure parent directory exists
2130
+ await fsPromises.mkdir(path.dirname(destPath), { recursive: true });
2131
+ // Copy file
2132
+ await fsPromises.copyFile(sourcePath, destPath);
2133
+ log('INFO', `📄 Restored file: ${item.source}`);
2134
+ }
2135
+ } catch (error) {
2136
+ if (error.code !== 'ENOENT') {
2137
+ log('WARN', `⚠️ Could not restore ${item.source}: ${error.message}`);
2138
+ }
2139
+ }
2140
+ }
2141
+
2142
+ // Handle credentials restoration with cross-platform support
2143
+ const currentPlatform = process.platform;
2144
+ let credentialsRestored = false;
2145
+
2146
+ // Try to restore credentials from available sources
2147
+ // 1. First try platform-specific credentials
2148
+ if (currentPlatform === 'darwin') {
2149
+ // On macOS, try macOS credentials first
2150
+ const macosCredsPath = path.join(extractDir, '.macos.credentials.json');
2151
+ try {
2152
+ const macosCredsData = await fsPromises.readFile(macosCredsPath, 'utf8');
2153
+ const macosCreds = JSON.parse(macosCredsData);
2154
+
2155
+ if (await setKeychainCredentials(macosCreds)) {
2156
+ log('INFO', '🔐 Restored macOS Keychain credentials from macOS profile');
2157
+ credentialsRestored = true;
2158
+ }
2159
+ } catch (error) {
2160
+ if (error.code !== 'ENOENT' && isVerbose) {
2161
+ log('DEBUG', `Could not restore macOS credentials: ${error.message}`);
2162
+ }
2163
+ }
2164
+
2165
+ // If no macOS credentials, try Linux credentials and convert
2166
+ if (!credentialsRestored) {
2167
+ const linuxCredsPath = path.join(extractDir, '.claude/.credentials.json');
2168
+ try {
2169
+ const linuxCredsData = await fsPromises.readFile(linuxCredsPath, 'utf8');
2170
+ const linuxCreds = JSON.parse(linuxCredsData);
2171
+
2172
+ // Convert Linux credentials to macOS format
2173
+ const convertedCreds = convertCredentialsFormat(linuxCreds, 'darwin');
2174
+
2175
+ if (isVerbose) {
2176
+ log('DEBUG', 'Converting Linux credentials to macOS format:');
2177
+ log('DEBUG', ` Source format: ${linuxCreds.claudeAiOauth ? 'modern (claudeAiOauth wrapper)' : 'legacy (underscore format)'}`);
2178
+ log('DEBUG', ` Target format: macOS Keychain (claudeAiOauth wrapper)`);
2179
+ }
2180
+
2181
+ if (await setKeychainCredentials(convertedCreds)) {
2182
+ log('INFO', '🔄 Converted and restored Linux credentials to macOS Keychain');
2183
+ credentialsRestored = true;
2184
+ }
2185
+ } catch (error) {
2186
+ if (error.code !== 'ENOENT' && isVerbose) {
2187
+ log('DEBUG', `Could not convert Linux credentials: ${error.message}`);
2188
+ }
2189
+ }
2190
+ }
2191
+ } else {
2192
+ // On Linux, try Linux credentials first
2193
+ const linuxCredsPath = path.join(extractDir, '.claude/.credentials.json');
2194
+ const linuxCredsDestPath = expandHome('~/.claude/.credentials.json');
2195
+
2196
+ try {
2197
+ await fsPromises.stat(linuxCredsPath);
2198
+ // Linux credentials exist, check if they need conversion
2199
+ const linuxCredsData = await fsPromises.readFile(linuxCredsPath, 'utf8');
2200
+ const linuxCreds = JSON.parse(linuxCredsData);
2201
+
2202
+ // Check if old format needs conversion
2203
+ if (!linuxCreds.claudeAiOauth && linuxCreds.access_token) {
2204
+ // Old format - convert to new
2205
+ const convertedCreds = convertCredentialsFormat(linuxCreds, 'linux');
2206
+
2207
+ if (isVerbose) {
2208
+ log('DEBUG', 'Converting old Linux format to new format:');
2209
+ log('DEBUG', ' Source: underscore format (access_token, refresh_token)');
2210
+ log('DEBUG', ' Target: claudeAiOauth wrapper format');
2211
+ }
2212
+
2213
+ await fsPromises.mkdir(path.dirname(linuxCredsDestPath), { recursive: true });
2214
+ await fsPromises.writeFile(linuxCredsDestPath, JSON.stringify(convertedCreds, null, 2));
2215
+ log('INFO', '🔄 Upgraded Linux credentials from old to new format');
2216
+ } else {
2217
+ // Already in new format, just copy
2218
+ await fsPromises.mkdir(path.dirname(linuxCredsDestPath), { recursive: true });
2219
+ await fsPromises.copyFile(linuxCredsPath, linuxCredsDestPath);
2220
+ log('INFO', '🔑 Restored Linux credentials (already in modern format)');
2221
+ }
2222
+ credentialsRestored = true;
2223
+ } catch (error) {
2224
+ if (error.code !== 'ENOENT' && isVerbose) {
2225
+ log('DEBUG', `Could not restore Linux credentials: ${error.message}`);
2226
+ }
2227
+ }
2228
+
2229
+ // If no Linux credentials, try macOS credentials and convert
2230
+ if (!credentialsRestored) {
2231
+ const macosCredsPath = path.join(extractDir, '.macos.credentials.json');
2232
+ try {
2233
+ const macosCredsData = await fsPromises.readFile(macosCredsPath, 'utf8');
2234
+ const macosCreds = JSON.parse(macosCredsData);
2235
+
2236
+ // Convert macOS credentials to Linux format
2237
+ const convertedCreds = convertCredentialsFormat(macosCreds, 'linux');
2238
+
2239
+ if (isVerbose) {
2240
+ log('DEBUG', 'Converting macOS credentials to Linux format:');
2241
+ log('DEBUG', ` Source format: ${macosCreds.claudeAiOauth ? 'claudeAiOauth wrapper' : 'unknown'}`);
2242
+ log('DEBUG', ` Target format: ${convertedCreds.claudeAiOauth ? 'claudeAiOauth wrapper (modern)' : 'underscore format (legacy)'}`);
2243
+ }
2244
+
2245
+ // Save converted credentials to Linux location
2246
+ await fsPromises.mkdir(path.dirname(linuxCredsDestPath), { recursive: true });
2247
+ await fsPromises.writeFile(linuxCredsDestPath, JSON.stringify(convertedCreds, null, 2));
2248
+ log('INFO', '🔄 Converted and restored macOS credentials to Linux format');
2249
+ credentialsRestored = true;
2250
+ } catch (error) {
2251
+ if (error.code !== 'ENOENT' && isVerbose) {
2252
+ log('DEBUG', `Could not convert macOS credentials: ${error.message}`);
2253
+ }
2254
+ }
2255
+ }
2256
+ }
2257
+
2258
+ if (!credentialsRestored) {
2259
+ log('WARN', '⚠️ No credentials were restored - profile may not have valid credentials');
2260
+ }
2261
+
2262
+ // Verify credentials were restored (for non-macOS or fallback)
2263
+ const credFile = expandHome('~/.claude/.credentials.json');
2264
+ try {
2265
+ await fsPromises.stat(credFile);
2266
+ log('INFO', '🔑 Credentials file restored');
2267
+ } catch {
2268
+ if (process.platform !== 'darwin') {
2269
+ log('WARN', '⚠️ No credentials file found in profile');
2270
+ }
2271
+ }
2272
+
2273
+ // Clean up temp directory
2274
+ await fsPromises.rm(tempDir, { recursive: true });
2275
+
2276
+ log('INFO', `✅ Profile '${profileName}' restored successfully`);
2277
+ log('INFO', '');
2278
+ log('INFO', '💡 To save current state as a profile, run:');
2279
+ log('INFO', ' ./claude-profiles.mjs --save <profile_name>');
2280
+ } catch (error) {
2281
+ if (!error.message.includes('Profile not found')) {
2282
+ log('ERROR', '❌ Error restoring profile:', error.message);
2283
+ }
2284
+
2285
+ if (error.message.includes('unzip')) {
2286
+ log('ERROR', '');
2287
+ log('ERROR', '📦 The unzip command is required but not installed');
2288
+ log('ERROR', ' • macOS: Should be pre-installed');
2289
+ log('ERROR', ' • Ubuntu/Debian: sudo apt-get install unzip');
2290
+ log('ERROR', ' • Alpine: apk add unzip');
2291
+ } else if (!error.message.includes('Profile not found')) {
2292
+ log('ERROR', '');
2293
+ log('ERROR', '🔧 Troubleshooting:');
2294
+ log('ERROR', ' • Check your internet connection');
2295
+ log('ERROR', ' • Verify the profile exists: ./claude-profiles.mjs --list');
2296
+ log('ERROR', ' • Ensure you have read permissions for the gist');
2297
+ log('ERROR', ' • Check disk space for extracting the profile');
2298
+ }
2299
+ process.exit(1);
2300
+ }
2301
+ }
2302
+
2303
+ // Main CLI setup
2304
+ const argv = yargs(hideBin(process.argv))
2305
+ .usage('Usage: $0 [options]')
2306
+ .option('list', {
2307
+ alias: 'l',
2308
+ type: 'boolean',
2309
+ description: 'List all saved profiles'
2310
+ })
2311
+ .option('store', {
2312
+ alias: ['s', 'save'],
2313
+ type: 'string',
2314
+ description: 'Store current Claude configuration to a profile'
2315
+ })
2316
+ .option('restore', {
2317
+ alias: 'r',
2318
+ type: 'string',
2319
+ description: 'Restore a saved profile'
2320
+ })
2321
+ .option('delete', {
2322
+ alias: 'd',
2323
+ type: 'string',
2324
+ description: 'Delete a saved profile'
2325
+ })
2326
+ .option('verify', {
2327
+ alias: 'v',
2328
+ type: 'string',
2329
+ description: 'Verify a profile contains essential files'
2330
+ })
2331
+ .option('watch', {
2332
+ alias: 'w',
2333
+ type: 'string',
2334
+ description: 'Watch for changes and auto-save to profile (30s throttle)'
2335
+ })
2336
+ .option('verbose', {
2337
+ type: 'boolean',
2338
+ description: 'Enable verbose logging for debugging',
2339
+ default: false
2340
+ })
2341
+ .option('log', {
2342
+ type: 'string',
2343
+ description: 'Log output to file (provide path or use default)',
2344
+ coerce: (arg) => {
2345
+ // If --log is provided without value, return empty string to trigger default
2346
+ return arg === true ? '' : arg;
2347
+ }
2348
+ })
2349
+ .option('skip-projects', {
2350
+ type: 'boolean',
2351
+ description: 'Exclude projects folder from backup (reduces size)',
2352
+ default: false
2353
+ })
2354
+ .help('help')
2355
+ .alias('help', 'h')
2356
+ .example('$0 --list', 'List all saved profiles')
2357
+ .example('$0 --store work', 'Store current config as "work" profile')
2358
+ .example('$0 --save work', 'Same as --store (alias)')
2359
+ .example('$0 --restore personal', 'Restore "personal" profile')
2360
+ .example('$0 --delete old-profile', 'Delete "old-profile"')
2361
+ .example('$0 --verify work', 'Verify "work" profile integrity')
2362
+ .example('$0 --store work --skip-projects', 'Store profile without projects folder')
2363
+ .example('$0 --watch work', 'Watch for changes and auto-save')
2364
+ .example('$0 --restore work --watch work', 'Restore profile then start watching')
2365
+ .example('$0 --store work --watch work', 'Store current state then start watching')
2366
+ .example('$0 --watch work --skip-projects', 'Watch with projects folder excluded')
2367
+ .example('$0 --watch work --verbose --log', 'Watch with debugging and logging')
2368
+ .epilogue('Profile names must contain only lowercase letters, numbers, and hyphens')
2369
+ .check((argv) => {
2370
+ const mainOptions = [argv.list, argv.store, argv.restore, argv.delete, argv.verify, argv.watch].filter(Boolean);
2371
+ if (mainOptions.length === 0) {
2372
+ throw new Error('Please specify one of: --list, --store, --restore, --delete, --verify, --watch, or combine --restore/--store with --watch');
2373
+ }
2374
+
2375
+ // Allow combining --restore or --store with --watch, but not other combinations
2376
+ if (mainOptions.length > 1) {
2377
+ const hasWatch = !!argv.watch;
2378
+ const hasRestoreOrStore = !!(argv.restore || argv.store);
2379
+ const hasOtherOptions = !!(argv.list || argv.delete || argv.verify);
2380
+
2381
+ if (hasWatch && hasRestoreOrStore && !hasOtherOptions && mainOptions.length === 2) {
2382
+ // Valid combination: --watch with --restore or --store
2383
+ return true;
2384
+ } else {
2385
+ throw new Error('Only --restore/--store can be combined with --watch. Other options must be used individually.');
2386
+ }
2387
+ }
2388
+ return true;
2389
+ })
2390
+ .argv;
2391
+
2392
+ /**
2393
+ * Check GitHub authentication status with friendly messaging
2394
+ */
2395
+ async function checkGitHubAuth() {
2396
+ try {
2397
+ const authResult = await $`gh auth status 2>&1`.run({ capture: true, mirror: false });
2398
+
2399
+ if (authResult.code === 0) {
2400
+ // Parse the output to check for gist scope
2401
+ const output = authResult.stdout;
2402
+ const scopesMatch = output.match(/Token scopes:\s*(.+)/);
2403
+
2404
+ // Check if gist scope is present
2405
+ if (scopesMatch) {
2406
+ const scopesLine = scopesMatch[1];
2407
+ // Extract all quoted strings (e.g., 'gist', 'read:org', 'repo')
2408
+ const quotedScopes = scopesLine.match(/'([^']+)'/g);
2409
+ if (quotedScopes) {
2410
+ // Remove quotes from each scope
2411
+ const scopes = quotedScopes.map(s => s.replace(/'/g, ''));
2412
+ const hasGistScope = scopes.includes('gist');
2413
+
2414
+ if (!hasGistScope) {
2415
+ log('INFO', '⚠️ Warning: Your GitHub token does not have "gist" scope');
2416
+ log('INFO', ' You may need to re-authenticate with: gh auth login -s gist');
2417
+ log('INFO', '');
2418
+ }
2419
+ } else {
2420
+ // Fallback: split by comma if no quotes found
2421
+ const scopes = scopesLine.split(',').map(s => s.trim());
2422
+ const hasGistScope = scopes.includes('gist');
2423
+
2424
+ if (!hasGistScope) {
2425
+ log('INFO', '⚠️ Warning: Your GitHub token does not have "gist" scope');
2426
+ log('INFO', ' You may need to re-authenticate with: gh auth login -s gist');
2427
+ log('INFO', '');
2428
+ }
2429
+ }
2430
+ }
2431
+
2432
+ return true;
2433
+ } else {
2434
+ return false;
2435
+ }
2436
+ } catch (error) {
2437
+ // gh command might not be installed
2438
+ if (error.message?.includes('not found') || error.message?.includes('command not found')) {
2439
+ log('ERROR', '❌ GitHub CLI (gh) is not installed');
2440
+ log('ERROR', '');
2441
+ log('ERROR', '📦 To install GitHub CLI:');
2442
+ log('ERROR', ' • macOS: brew install gh');
2443
+ log('ERROR', ' • Linux: See https://github.com/cli/cli#installation');
2444
+ log('ERROR', ' • Windows: winget install --id GitHub.cli');
2445
+ process.exit(1);
2446
+ }
2447
+ return false;
2448
+ }
2449
+ }
2450
+
2451
+ /**
2452
+ * Get detailed GitHub auth status for error diagnostics
2453
+ */
2454
+ async function getDetailedAuthStatus() {
2455
+ try {
2456
+ const authResult = await $`gh auth status 2>&1`.run({ capture: true, mirror: false });
2457
+ const output = authResult.stdout;
2458
+
2459
+ // Parse auth status details
2460
+ const details = {
2461
+ authenticated: authResult.code === 0,
2462
+ loggedInAs: null,
2463
+ account: null,
2464
+ protocol: null,
2465
+ token: null,
2466
+ scopes: [],
2467
+ hasGistScope: false,
2468
+ rawOutput: output // Include raw output for debugging
2469
+ };
2470
+
2471
+ // Parse logged in account - updated pattern for new format
2472
+ const accountMatch = output.match(/Logged in to github\.com account (\S+)|Logged in to [\w\.]+ as (\S+)/);
2473
+ if (accountMatch) {
2474
+ details.account = accountMatch[1] || accountMatch[2];
2475
+ }
2476
+
2477
+ // Parse git operations protocol
2478
+ const protocolMatch = output.match(/Git operations protocol:\s*(\w+)/);
2479
+ if (protocolMatch) {
2480
+ details.protocol = protocolMatch[1];
2481
+ }
2482
+
2483
+ // Parse token (masked)
2484
+ const tokenMatch = output.match(/Token:\s*(\S+)/);
2485
+ if (tokenMatch) {
2486
+ details.token = tokenMatch[1];
2487
+ }
2488
+
2489
+ // Parse token scopes - capture the entire line after "Token scopes:"
2490
+ const scopesMatch = output.match(/Token scopes:\s*(.+)/);
2491
+ if (scopesMatch) {
2492
+ const scopesLine = scopesMatch[1];
2493
+ // Extract all quoted strings (e.g., 'gist', 'read:org', 'repo')
2494
+ const quotedScopes = scopesLine.match(/'([^']+)'/g);
2495
+ if (quotedScopes) {
2496
+ // Remove quotes from each scope
2497
+ details.scopes = quotedScopes.map(s => s.replace(/'/g, ''));
2498
+ } else {
2499
+ // Fallback: split by comma if no quotes found
2500
+ details.scopes = scopesLine.split(',').map(s => s.trim());
2501
+ }
2502
+ details.hasGistScope = details.scopes.includes('gist');
2503
+ }
2504
+
2505
+ // Check if completely logged out
2506
+ if (output.includes('You are not logged into any GitHub hosts')) {
2507
+ details.authenticated = false;
2508
+ details.account = null;
2509
+ }
2510
+
2511
+ return details;
2512
+ } catch (error) {
2513
+ return null;
2514
+ }
2515
+ }
2516
+
2517
+ // Execute the requested action
2518
+ (async () => {
2519
+ try {
2520
+ // Initialize logging if needed
2521
+ initLogging({
2522
+ verbose: argv.verbose,
2523
+ log: argv.log
2524
+ });
2525
+
2526
+ // Check if gh is authenticated
2527
+ const isAuthenticated = await checkGitHubAuth();
2528
+
2529
+ if (!isAuthenticated) {
2530
+ log('ERROR', '🔐 GitHub CLI is not authenticated');
2531
+ log('ERROR', '');
2532
+ log('ERROR', '📝 To authenticate with GitHub:');
2533
+ log('ERROR', ' 1. Run: gh auth login');
2534
+ log('ERROR', ' 2. Follow the prompts to authenticate');
2535
+ log('ERROR', ' 3. Make sure to grant "gist" scope when asked');
2536
+ log('ERROR', '');
2537
+ log('ERROR', '💡 Tips:');
2538
+ log('ERROR', ' • Use SSH if you have SSH keys set up');
2539
+ log('ERROR', ' • Use HTTPS with a token for simpler setup');
2540
+ log('ERROR', ' • You can also use: gh auth login -s gist');
2541
+ process.exit(1);
2542
+ }
2543
+
2544
+ // Prepare options object
2545
+ const options = {
2546
+ skipProjects: argv.skipProjects || false
2547
+ };
2548
+
2549
+ if (argv.list) {
2550
+ await listProfiles();
2551
+ } else if (argv.store && argv.watch) {
2552
+ // Store first, then watch
2553
+ // Handle case where --store is boolean (true) when no value provided
2554
+ const storeProfileName = typeof argv.store === 'boolean' ? argv.watch : argv.store;
2555
+ const watchProfileName = argv.watch;
2556
+ await saveProfile(storeProfileName, options);
2557
+ log('INFO', '');
2558
+ log('INFO', '🔄 Now starting watch mode...');
2559
+ await watchProfile(watchProfileName, options);
2560
+ } else if (argv.restore && argv.watch) {
2561
+ // Restore first, then watch
2562
+ // Handle case where --restore is boolean (true) when no value provided
2563
+ const restoreProfileName = typeof argv.restore === 'boolean' ? argv.watch : argv.restore;
2564
+ const watchProfileName = argv.watch;
2565
+ await restoreProfile(restoreProfileName, options);
2566
+ log('INFO', '');
2567
+ log('INFO', '🔄 Now starting watch mode...');
2568
+ await watchProfile(watchProfileName, options);
2569
+ } else if (argv.store) {
2570
+ await saveProfile(argv.store, options);
2571
+ } else if (argv.restore) {
2572
+ await restoreProfile(argv.restore, options);
2573
+ } else if (argv.delete) {
2574
+ await deleteProfile(argv.delete);
2575
+ } else if (argv.verify) {
2576
+ await verifyProfile(argv.verify);
2577
+ } else if (argv.watch) {
2578
+ await watchProfile(argv.watch, options);
2579
+ }
2580
+ } catch (error) {
2581
+ log('ERROR', '❌ Unexpected error:', error.message);
2582
+
2583
+ // Provide helpful context for common errors
2584
+ if (error.code === 'EACCES') {
2585
+ log('ERROR', '');
2586
+ log('ERROR', '📝 Permission denied. This could mean:');
2587
+ log('ERROR', ' • You need sudo access (not recommended)');
2588
+ log('ERROR', ' • File permissions are incorrect');
2589
+ log('ERROR', ' • Try: ls -la ~/.claude/');
2590
+ } else if (error.code === 'ENOENT') {
2591
+ log('ERROR', '');
2592
+ log('ERROR', '📝 File or directory not found');
2593
+ log('ERROR', ' This usually means Claude configuration doesn\'t exist yet');
2594
+ } else if (error.code === 'ENOSPC') {
2595
+ log('ERROR', '');
2596
+ log('ERROR', '💾 No space left on device');
2597
+ log('ERROR', ' Please free up some disk space and try again');
2598
+ } else if (error.message?.includes('network')) {
2599
+ log('ERROR', '');
2600
+ log('ERROR', '🌐 Network issue detected');
2601
+ log('ERROR', ' • Check your internet connection');
2602
+ log('ERROR', ' • Check if GitHub is accessible');
2603
+ log('ERROR', ' • Try: ping github.com');
2604
+ }
2605
+
2606
+ log('ERROR', '');
2607
+ log('ERROR', 'For more help, check the tool documentation or report an issue');
2608
+ process.exit(1);
2609
+ }
2610
+ })();