forked from GWUDCAP/cc-sessions
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstall.js
More file actions
executable file
·1673 lines (1458 loc) · 60.5 KB
/
install.js
File metadata and controls
executable file
·1673 lines (1458 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Claude Code Sessions Framework - Cross-Platform Node.js Installer
*
* NPM wrapper installer providing identical functionality to the Python installer
* with native Windows, macOS, and Linux support. Features interactive terminal
* UI, platform-aware command detection, and cross-platform file operations.
*
* Key Features:
* - Windows compatibility with .cmd and .ps1 script installation
* - Cross-platform command detection (where/which)
* - Platform-aware path handling and file permissions
* - Interactive menu system with keyboard navigation
* - Global daic command installation with PATH integration
*
* Platform Support:
* - Windows 10/11 (Command Prompt, PowerShell, Git Bash)
* - macOS (Terminal, iTerm2 with Bash/Zsh)
* - Linux distributions (various terminals and shells)
*
* Installation Methods:
* - npm install -g cc-sessions (global installation)
* - npx cc-sessions (temporary installation)
*
* Windows Integration:
* - Creates %USERPROFILE%\AppData\Local\cc-sessions\bin directory
* - Installs both daic.cmd and daic.ps1 for shell compatibility
* - Uses Windows-style environment variables (%VAR%)
* - Platform-specific hook command generation
*
* @module install
* @requires fs
* @requires path
* @requires child_process
* @requires readline
*/
const fs = require('fs').promises;
const path = require('path');
const { execSync } = require('child_process');
const readline = require('readline');
const { promisify } = require('util');
// Colors for terminal output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
bgRed: '\x1b[41m',
bgGreen: '\x1b[42m',
bgYellow: '\x1b[43m',
bgBlue: '\x1b[44m',
bgMagenta: '\x1b[45m',
bgCyan: '\x1b[46m'
};
// Helper to colorize output
const color = (text, colorCode) => `${colorCode}${text}${colors.reset}`;
// Icons and symbols
const icons = {
check: '✓',
cross: '✗',
lock: '🔒',
unlock: '🔓',
info: 'ℹ',
warning: '⚠',
arrow: '→',
bullet: '•',
star: '★'
};
// Create readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const question = promisify(rl.question).bind(rl);
/**
* Ask a yes/no question with a default option
* @param {string} prompt - The question to ask
* @param {boolean} defaultValue - True for yes default (Y/n), False for no default (y/N)
* @returns {Promise<boolean>} - True for yes, False for no
*/
async function askYesNo(prompt, defaultValue = true) {
const suffix = defaultValue ? ' (Y/n): ' : ' (y/N): ';
while (true) {
const response = (await question(color(prompt + suffix, colors.cyan))).trim().toLowerCase();
if (response === '') {
return defaultValue;
} else if (['y', 'yes'].includes(response)) {
return true;
} else if (['n', 'no'].includes(response)) {
return false;
} else {
console.log(color(' Please enter y, n, yes, no, or press Enter for default', colors.yellow));
}
}
}
/**
* Interactive tool selection with arrow keys navigation
* @param {Array} tools - Array of [name, description, isBlocked] tuples
* @param {Array} currentBlocked - Array of currently blocked tool names
* @returns {Promise<Array|null>} Array of tool names to block, or null if cancelled
*/
async function interactiveToolSelection(tools, currentBlocked) {
try {
// Check if we're in a compatible terminal
if (!process.stdin.isTTY) {
console.log(color(' ⚠️ Interactive mode requires a terminal (not available in pipes/scripts)', colors.yellow));
return null;
}
const readline = require('readline');
// Enable keypress events
if (typeof process.stdin.setRawMode === 'function') {
process.stdin.setRawMode(true);
} else {
console.log(color(' ⚠️ Raw mode not available in this terminal', colors.yellow));
console.log(color(' Falling back to classic numbered input...', colors.dim));
return null;
}
// Required for keypress events
require('readline').emitKeypressEvents(process.stdin);
// Setup readline for raw key input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
process.stdin.resume();
// Prepare tool list with selection state
const toolItems = tools.map(([name, desc]) => ({
name,
desc,
isSelected: currentBlocked.includes(name)
}));
let currentIndex = 0;
return new Promise((resolve) => {
const showMenu = () => {
// Clear screen
console.clear();
// Show header
console.log(color('╭───────────────────────────────────────────────────────────────╮', colors.cyan));
console.log(color('│ Interactive Tool Selection │', colors.cyan));
console.log(color('├───────────────────────────────────────────────────────────────┤', colors.cyan));
console.log(color('│ Use ↑↓ to navigate, Space to toggle, Enter to confirm │', colors.cyan));
console.log(color('│ [✓] = Will be BLOCKED, [ ] = Will remain ALLOWED │', colors.cyan));
console.log(color('╰───────────────────────────────────────────────────────────────╯', colors.cyan));
console.log();
// Show tools
toolItems.forEach((tool, i) => {
const prefix = i === currentIndex ? '>' : ' ';
const checkbox = tool.isSelected ? '[✓]' : '[ ]';
const statusIcon = tool.isSelected ? '❌' : '✅';
const statusText = tool.isSelected ? 'BLOCKED' : 'ALLOWED';
const statusColor = tool.isSelected ? colors.red : colors.green;
if (i === currentIndex) {
console.log(color(`${prefix} ${checkbox} ${statusIcon} ${tool.name.padEnd(15)} - ${tool.desc}`, colors.bright + colors.white));
} else {
console.log(`${prefix} ${checkbox} ${statusIcon} ${color(tool.name.padEnd(15), colors.white)} - ${tool.desc}`);
}
console.log(` ${color(statusText, statusColor)}`);
});
console.log(color('\\nPress ESC or Ctrl+C to cancel', colors.dim));
};
const handleKeypress = (chunk, key) => {
if (key && key.ctrl && key.name === 'c') {
cleanup();
resolve(null);
return;
}
if (key) {
switch (key.name) {
case 'up':
if (currentIndex > 0) currentIndex--;
showMenu();
break;
case 'down':
if (currentIndex < toolItems.length - 1) currentIndex++;
showMenu();
break;
case 'space':
toolItems[currentIndex].isSelected = !toolItems[currentIndex].isSelected;
showMenu();
break;
case 'return':
cleanup();
resolve(toolItems.filter(tool => tool.isSelected).map(tool => tool.name));
break;
case 'escape':
cleanup();
resolve(null);
break;
}
}
};
const cleanup = () => {
process.stdin.setRawMode(false);
process.stdin.pause();
process.stdin.removeListener('keypress', handleKeypress);
rl.close();
};
process.stdin.on('keypress', handleKeypress);
showMenu();
});
} catch (error) {
console.log(color(` ⚠️ Interactive mode error: ${error.message}`, colors.yellow));
console.log(color(' Falling back to classic numbered input...', colors.dim));
return null;
}
}
// Paths
const SCRIPT_DIR = __dirname;
let PROJECT_ROOT = process.cwd();
// Check if we're running from npx or in wrong directory
async function detectProjectDirectory() {
// If running from node_modules or temp npx directory
if (PROJECT_ROOT.includes('node_modules') || PROJECT_ROOT.includes('.npm')) {
console.log(color('⚠️ Running from package directory, not project directory.', colors.yellow));
console.log();
const projectPath = await question('Enter the path to your project directory (or press Enter for current directory): ');
if (projectPath) {
PROJECT_ROOT = path.resolve(projectPath);
} else {
PROJECT_ROOT = process.cwd();
}
console.log(color(`Using project directory: ${PROJECT_ROOT}`, colors.cyan));
}
}
// Configuration object to build
const config = {
developer_name: "the developer",
trigger_phrases: ["make it so", "run that", "go ahead", "yert"],
blocked_tools: ["Edit", "Write", "MultiEdit", "NotebookEdit"],
task_detection: { enabled: true },
branch_enforcement: { enabled: true },
memory_bank_mcp: { enabled: false, auto_activate: true }
};
// Global variable for existing installation detection
let existingInstallation = null;
/**
* Detect if cc-sessions is already installed in this project
* @returns {object|null} Installation details or null if not found
*/
function detectExistingInstallation() {
const configFile = path.join(PROJECT_ROOT, 'sessions', 'sessions-config.json');
if (!require('fs').existsSync(configFile)) {
return null;
}
try {
const existingConfig = JSON.parse(require('fs').readFileSync(configFile, 'utf8'));
// Try to determine installed version
let installedVersion = "unknown";
if (existingConfig.version) {
installedVersion = existingConfig.version;
}
// Check for statusline installation
let hasStatusline = false;
try {
const settingsFile = path.join(PROJECT_ROOT, '.claude', 'settings.json');
if (require('fs').existsSync(settingsFile)) {
const settings = JSON.parse(require('fs').readFileSync(settingsFile, 'utf8'));
hasStatusline = !!settings.statusLine;
}
} catch {
// Ignore errors when checking statusline
}
return {
configFile: configFile,
config: existingConfig,
version: installedVersion,
hasHooks: require('fs').existsSync(path.join(PROJECT_ROOT, '.claude', 'hooks')),
hasAgents: require('fs').existsSync(path.join(PROJECT_ROOT, '.claude', 'agents')),
hasCommands: require('fs').existsSync(path.join(PROJECT_ROOT, '.claude', 'commands')),
hasStatusline: hasStatusline,
claudeMdExists: require('fs').existsSync(path.join(PROJECT_ROOT, 'CLAUDE.md'))
};
} catch (error) {
return null;
}
}
/**
* Get current package version
* @returns {string} Current version
*/
function getCurrentPackageVersion() {
try {
const packageJson = JSON.parse(require('fs').readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
return packageJson.version || '0.2.8';
} catch {
return '0.2.8'; // Fallback
}
}
/**
* Show installation menu for existing installations
* @returns {Promise<string>} User's choice
*/
async function showInstallationMenu() {
const currentVersion = getCurrentPackageVersion();
const existingVersion = existingInstallation.version;
console.log();
console.log(color('╔═══════════════════════════════════════════════╗', colors.bright + colors.cyan));
console.log(color('║ cc-sessions Already Installed ║', colors.bright + colors.cyan));
console.log(color('╚═══════════════════════════════════════════════╝', colors.bright + colors.cyan));
console.log();
console.log(color(` Found existing installation: ${colors.bright}v${existingVersion}${colors.reset}`, colors.white));
console.log(color(` Current version available: ${colors.bright}v${currentVersion}${colors.reset}`, colors.white));
console.log();
if (existingVersion !== currentVersion) {
console.log(color(' 🆕 Update available!', colors.green));
} else {
console.log(color(' ✅ You have the latest version', colors.green));
}
console.log();
console.log(color(' What would you like to do?', colors.cyan));
console.log(color(' 1. Update to latest version (preserve your config)', colors.white));
console.log(color(' 2. Fresh install (reset everything)', colors.yellow));
console.log(color(' 3. Repair installation (fix missing files)', colors.blue));
console.log(color(' 4. Exit (no changes)', colors.dim));
console.log();
while (true) {
const choice = await question(color(' Your choice (1-4): ', colors.cyan));
if (['1', '2', '3', '4'].includes(choice)) {
return { '1': 'update', '2': 'fresh', '3': 'repair', '4': 'exit' }[choice];
}
console.log(color(' Please enter 1, 2, 3, or 4', colors.yellow));
}
}
/**
* Create backup of existing configuration
* @returns {string} Backup file path
*/
async function backupExistingConfig() {
const backupDir = path.join(PROJECT_ROOT, 'sessions', 'backups');
await fs.mkdir(backupDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.-]/g, '_').split('T')[0] + '_' +
new Date().toISOString().split('T')[1].split('.')[0].replace(/:/g, '');
const backupFile = path.join(backupDir, `config_backup_${timestamp}.json`);
await fs.copyFile(existingInstallation.configFile, backupFile);
return backupFile;
}
/**
* Load existing configuration to preserve user settings
*/
function loadExistingConfig() {
const existing = existingInstallation.config;
// Preserve user settings
if (existing.developer_name) config.developer_name = existing.developer_name;
if (existing.trigger_phrases) config.trigger_phrases = existing.trigger_phrases;
if (existing.blocked_tools) config.blocked_tools = existing.blocked_tools;
if (existing.task_detection) config.task_detection = existing.task_detection;
if (existing.branch_enforcement) config.branch_enforcement = existing.branch_enforcement;
if (existing.memory_bank_mcp) config.memory_bank_mcp = existing.memory_bank_mcp;
// Preserve any custom settings not in defaults
for (const [key, value] of Object.entries(existing)) {
if (!(key in config)) {
config[key] = value;
}
}
}
/**
* Update existing installation preserving configuration
*/
async function runUpdate() {
console.log();
console.log(color('🔄 Updating cc-sessions installation...', colors.cyan));
console.log();
try {
// Backup existing configuration
const backupFile = await backupExistingConfig();
console.log(color(`✓ Configuration backed up to ${path.basename(backupFile)}`, colors.green));
// Load existing configuration to preserve settings
loadExistingConfig();
console.log(color('Updating system files...', colors.dim));
// Update directories structure (create any missing)
await createDirectories();
// Install Python dependencies
await installPythonDeps();
// Update all code files
await copyFiles();
// Update daic command
await installDaicCommand();
// Update configuration with preserved settings + new version
config.version = getCurrentPackageVersion();
await saveConfig(existingInstallation.hasStatusline || false);
// Preserve CLAUDE.md setup
await setupClaudeMd();
console.log();
console.log(color('✅ Update completed successfully!', colors.green));
console.log();
console.log(color(` Updated to version: ${colors.bright}v${config.version}${colors.reset}`, colors.white));
console.log(color(' Your configuration has been preserved', colors.dim));
console.log();
console.log(color(' Next steps:', colors.cyan));
console.log(color(' • Restart Claude Code to activate updated hooks', colors.dim));
console.log(color(' • Your tasks and settings remain unchanged', colors.dim));
} catch (error) {
console.log();
console.log(color('❌ Update failed!', colors.red));
console.log(color(` Error: ${error.message}`, colors.dim));
console.log(color(' Your existing installation was not modified', colors.dim));
throw error;
}
}
/**
* Repair installation by fixing missing files without changing configuration
*/
async function runRepair() {
console.log();
console.log(color('🔧 Repairing cc-sessions installation...', colors.cyan));
console.log();
try {
// Load existing configuration
loadExistingConfig();
console.log(color('Checking and repairing system files...', colors.dim));
// Recreate directories (in case any are missing)
await createDirectories();
// Install Python dependencies
await installPythonDeps();
// Restore all code files
await copyFiles();
// Restore daic command
await installDaicCommand();
// Restore CLAUDE.md setup
await setupClaudeMd();
console.log();
console.log(color('✅ Repair completed successfully!', colors.green));
console.log();
console.log(color(' All missing files have been restored', colors.white));
console.log(color(' Your configuration was not modified', colors.dim));
console.log();
console.log(color(' Next steps:', colors.cyan));
console.log(color(' • Restart Claude Code if experiencing issues', colors.dim));
console.log(color(' • All tasks and settings remain unchanged', colors.dim));
} catch (error) {
console.log();
console.log(color('❌ Repair failed!', colors.red));
console.log(color(` Error: ${error.message}`, colors.dim));
throw error;
}
}
// Check if command exists
function commandExists(command) {
try {
if (process.platform === 'win32') {
// Windows - use 'where' command
execSync(`where ${command}`, { stdio: 'ignore' });
return true;
} else {
// Unix/Mac - use 'which' command
execSync(`which ${command}`, { stdio: 'ignore' });
return true;
}
} catch {
return false;
}
}
// Cache for MCP servers to prevent repeated Chrome popups
let _installedMcpServers = null;
/**
* Get list of installed MCP servers using cached results
* @returns {string[]} Array of server names
*/
function getInstalledMcpServers() {
if (_installedMcpServers !== null) {
return _installedMcpServers;
}
try {
const result = execSync('claude mcp list', { encoding: 'utf-8', stdio: 'pipe' });
_installedMcpServers = result.split('\n')
.map(line => line.trim())
.filter(line => line && !line.startsWith('---') && !line.includes('MCP servers'))
.map(line => line.split(/\s+/)[0]) // Extract server name (first column)
.filter(name => name && name !== 'Name');
return _installedMcpServers;
} catch (error) {
console.log(color(' Warning: Could not check MCP servers', colors.yellow));
_installedMcpServers = [];
return _installedMcpServers;
}
}
/**
* Check Memory Bank MCP requirements and installation status
* @returns {object} Status object with availability flags
*/
function checkMemoryBankMcp() {
const hasNpx = commandExists("npx");
const hasClaude = commandExists("claude");
const installedServers = getInstalledMcpServers();
return {
npx: hasNpx,
claude: hasClaude,
available: hasNpx && hasClaude,
already_installed: installedServers.includes("memory-bank")
};
}
/**
* Install Memory Bank MCP server if requirements are met
* @returns {boolean} True if installed or already present, false otherwise
*/
async function installMemoryBankMcp() {
const memoryBankStatus = checkMemoryBankMcp();
if (memoryBankStatus.already_installed) {
console.log(color("✓ Memory Bank MCP already installed", colors.green));
config.memory_bank_mcp.enabled = true;
return true;
}
if (!memoryBankStatus.available) {
const missing = [];
if (!memoryBankStatus.npx) missing.push("npx");
if (!memoryBankStatus.claude) missing.push("claude");
console.log(color(`⚠️ Memory Bank MCP requirements not met. Missing: ${missing.join(", ")}`, colors.yellow));
console.log(color(" Install Node.js for npx: https://nodejs.org", colors.dim));
console.log(color(" Ensure Claude Code CLI is available: claude --version", colors.dim));
return false;
}
console.log(color("Installing Memory Bank MCP via Smithery...", colors.cyan));
try {
// Use empty string to bypass API key requirement
execSync('echo "" | npx -y @smithery/cli install @alioshr/memory-bank-mcp --client claude', {
shell: true,
stdio: 'pipe'
});
console.log(color("✓ Memory Bank MCP installed successfully", colors.green));
config.memory_bank_mcp.enabled = true;
return true;
} catch (error) {
console.log(color("⚠️ Memory Bank MCP installation failed", colors.yellow));
console.log(color(" You can manually install later with:", colors.dim));
console.log(color(' echo "" | npx -y @smithery/cli install @alioshr/memory-bank-mcp --client claude', colors.dim));
return false;
}
}
/**
* Setup automatic file discovery and sync for Memory Bank MCP
* @returns {boolean} True if setup completed successfully
*/
async function setupMemoryBankFiles() {
try {
console.log(color("\n 📄 File Synchronization Setup", colors.cyan));
console.log(color(" Discovering important project documentation for persistent context...", colors.dim));
console.log();
// Auto-discovery patterns
const discoveryPatterns = {
"Configuration": [
"CLAUDE.md", "CLAUDE.sessions.md", ".claude/CLAUDE*.md"
],
"Documentation": [
"README.md", "ARCHITECTURE.md", "DESIGN.md",
"docs/*.md", "documentation/*.md"
],
"Requirements": [
"PRD.md", "FSD.md", "*requirements*.md",
"*product*.md", "*spec*.md"
]
};
const discoveredFiles = { Configuration: [], Documentation: [], Requirements: [] };
// Scan project for files
for (const [category, patterns] of Object.entries(discoveryPatterns)) {
for (const pattern of patterns) {
if (pattern.includes('*')) {
// Use glob for wildcard patterns
const glob = require('glob');
const matches = glob.sync(pattern, { cwd: process.cwd(), absolute: false });
for (const match of matches) {
const filePath = path.join(process.cwd(), match);
if (fs.existsSync(filePath) && path.extname(match).toLowerCase() === '.md') {
const stats = fs.statSync(filePath);
const isDuplicate = Object.values(discoveredFiles)
.flat()
.some(f => f.path === match);
if (!isDuplicate) {
discoveredFiles[category].push({
path: match,
exists: true,
size: stats.size
});
}
}
}
} else {
// Direct file check
const filePath = path.join(process.cwd(), pattern);
if (fs.existsSync(filePath)) {
const stats = fs.statSync(filePath);
const isDuplicate = Object.values(discoveredFiles)
.flat()
.some(f => f.path === pattern);
if (!isDuplicate) {
discoveredFiles[category].push({
path: pattern,
exists: true,
size: stats.size
});
}
}
}
}
}
// Display discovered files
const totalDiscovered = Object.values(discoveredFiles)
.reduce((sum, files) => sum + files.length, 0);
if (totalDiscovered === 0) {
console.log(color(" ⚠️ No documentation files auto-discovered", colors.yellow));
console.log(color(" You can add files manually below", colors.dim));
} else {
console.log(color(` ✓ Auto-discovered ${totalDiscovered} documentation files:`, colors.green));
console.log();
for (const [category, files] of Object.entries(discoveredFiles)) {
if (files.length > 0) {
console.log(color(` ${category}:`, colors.cyan));
for (const fileInfo of files) {
const sizeKb = (fileInfo.size / 1024).toFixed(1);
console.log(color(` ✓ ${fileInfo.path} (${sizeKb}KB)`, colors.green));
}
}
}
console.log();
if (await askYesNo(" Add all auto-discovered files to Memory Bank sync?", true)) {
// Add all discovered files to sync configuration
for (const [category, files] of Object.entries(discoveredFiles)) {
for (const fileInfo of files) {
const syncFile = {
path: fileInfo.path,
status: "pending",
last_synced: null,
category: category.toLowerCase()
};
config.memory_bank_mcp.sync_files.push(syncFile);
}
}
console.log(color(` ✓ Added ${totalDiscovered} files to sync configuration`, colors.green));
} else {
console.log(color(" Skipped auto-discovered files", colors.dim));
}
}
// Manual file addition
console.log();
console.log(color(" Additional files:", colors.cyan));
console.log(color(' Add specific markdown files for persistent context (e.g., "docs/api.md")', colors.dim));
console.log();
while (true) {
const filePath = await question(color(" Add markdown file (Enter path relative to project root, or Enter to finish): ", colors.cyan));
if (!filePath) {
break;
}
// Skip if already added
const isDuplicate = config.memory_bank_mcp.sync_files.some(f => f.path === filePath);
if (isDuplicate) {
console.log(color(` ⚠️ File already added: ${filePath}`, colors.yellow));
continue;
}
// Validate file exists and is markdown
const fullPath = path.join(process.cwd(), filePath);
if (!fs.existsSync(fullPath)) {
console.log(color(` ⚠️ File not found: ${filePath}`, colors.yellow));
continue;
}
if (!filePath.toLowerCase().endsWith('.md')) {
console.log(color(" ⚠️ Only markdown files (.md) are supported", colors.yellow));
continue;
}
// Add to sync files configuration
const syncFile = {
path: filePath,
status: "pending",
last_synced: null,
category: "manual"
};
config.memory_bank_mcp.sync_files.push(syncFile);
console.log(color(` ✓ Added: "${filePath}"`, colors.green));
}
// Summary
const totalSyncFiles = config.memory_bank_mcp.sync_files.length;
if (totalSyncFiles > 0) {
console.log();
console.log(color(` 📋 Total files configured for sync: ${totalSyncFiles}`, colors.cyan));
console.log(color(" Use /sync-all to sync all files to Memory Bank", colors.dim));
console.log(color(" Files will auto-load in future sessions for persistent context", colors.dim));
}
return true;
} catch (error) {
console.log(color(" ⚠️ Error during Memory Bank file configuration", colors.yellow));
console.log(color(` Error: ${error.message}`, colors.dim));
console.log(color(" Memory Bank MCP server is still functional", colors.green));
return false;
}
}
// Check dependencies
async function checkDependencies() {
console.log(color('Checking dependencies...', colors.cyan));
// Check Python
const hasPython = commandExists('python3') || commandExists('python');
if (!hasPython) {
console.log(color('❌ Python 3 is required but not installed.', colors.red));
process.exit(1);
}
// Check pip
const hasPip = commandExists('pip3') || commandExists('pip');
if (!hasPip) {
console.log(color('❌ pip is required but not installed.', colors.red));
process.exit(1);
}
// Check Git (warning only)
if (!commandExists('git')) {
console.log(color('⚠️ Warning: Not in a git repository. Sessions works best with git.', colors.yellow));
if (!(await askYesNo('Continue anyway?', false))) {
process.exit(1);
}
}
}
// Create directory structure
async function createDirectories() {
console.log(color('Creating directory structure...', colors.cyan));
const dirs = [
'.claude/hooks',
'.claude/state',
'.claude/agents',
'.claude/commands',
'sessions/tasks/done',
'sessions/protocols',
'sessions/knowledge'
];
for (const dir of dirs) {
await fs.mkdir(path.join(PROJECT_ROOT, dir), { recursive: true });
}
}
// Install Python dependencies
async function installPythonDeps() {
console.log(color('Installing Python dependencies...', colors.cyan));
try {
const pipCommand = commandExists('pip3') ? 'pip3' : 'pip';
execSync(`${pipCommand} install tiktoken --quiet`, { stdio: 'ignore' });
} catch (error) {
console.log(color('⚠️ Could not install tiktoken. You may need to install it manually.', colors.yellow));
}
}
// Copy files with proper permissions
async function copyFiles() {
console.log(color('Installing hooks...', colors.cyan));
const hookFiles = await fs.readdir(path.join(SCRIPT_DIR, 'cc_sessions/hooks'));
for (const file of hookFiles) {
if (file.endsWith('.py')) {
await fs.copyFile(
path.join(SCRIPT_DIR, 'cc_sessions/hooks', file),
path.join(PROJECT_ROOT, '.claude/hooks', file)
);
if (process.platform !== 'win32') {
await fs.chmod(path.join(PROJECT_ROOT, '.claude/hooks', file), 0o755);
}
}
}
console.log(color('Installing protocols...', colors.cyan));
const protocolFiles = await fs.readdir(path.join(SCRIPT_DIR, 'cc_sessions/protocols'));
for (const file of protocolFiles) {
if (file.endsWith('.md')) {
await fs.copyFile(
path.join(SCRIPT_DIR, 'cc_sessions/protocols', file),
path.join(PROJECT_ROOT, 'sessions/protocols', file)
);
}
}
console.log(color('Installing agent definitions...', colors.cyan));
const agentFiles = await fs.readdir(path.join(SCRIPT_DIR, 'cc_sessions/agents'));
for (const file of agentFiles) {
if (file.endsWith('.md')) {
await fs.copyFile(
path.join(SCRIPT_DIR, 'cc_sessions/agents', file),
path.join(PROJECT_ROOT, '.claude/agents', file)
);
}
}
console.log(color('Installing templates...', colors.cyan));
await fs.copyFile(
path.join(SCRIPT_DIR, 'cc_sessions/templates/TEMPLATE.md'),
path.join(PROJECT_ROOT, 'sessions/tasks/TEMPLATE.md')
);
console.log(color('Installing commands...', colors.cyan));
const commandFiles = await fs.readdir(path.join(SCRIPT_DIR, 'cc_sessions/commands'));
for (const file of commandFiles) {
if (file.endsWith('.md') || file.endsWith('.py')) {
await fs.copyFile(
path.join(SCRIPT_DIR, 'cc_sessions/commands', file),
path.join(PROJECT_ROOT, '.claude/commands', file)
);
// Make Python commands executable on Unix
if (file.endsWith('.py') && process.platform !== 'win32') {
await fs.chmod(path.join(PROJECT_ROOT, '.claude/commands', file), 0o755);
}
}
}
// Copy knowledge files if they exist
const knowledgePath = path.join(SCRIPT_DIR, 'cc_sessions/knowledge/claude-code');
try {
await fs.access(knowledgePath);
console.log(color('Installing Claude Code knowledge base...', colors.cyan));
await copyDir(knowledgePath, path.join(PROJECT_ROOT, 'sessions/knowledge/claude-code'));
} catch {
// Knowledge files don't exist, skip
}
}
// Recursive directory copy
async function copyDir(src, dest) {
await fs.mkdir(dest, { recursive: true });
const entries = await fs.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
await copyDir(srcPath, destPath);
} else {
await fs.copyFile(srcPath, destPath);
}
}
}
// Install daic command
async function installDaicCommand() {
console.log(color('Installing daic command...', colors.cyan));
if (process.platform === 'win32') {
// Windows installation
const daicCmdSource = path.join(SCRIPT_DIR, 'cc_sessions/scripts/daic.cmd');
const daicPs1Source = path.join(SCRIPT_DIR, 'cc_sessions/scripts/daic.ps1');
// Install to user's local directory
const localBin = path.join(process.env.USERPROFILE || process.env.HOME, 'AppData', 'Local', 'cc-sessions', 'bin');
await fs.mkdir(localBin, { recursive: true });
try {
// Copy .cmd script
await fs.access(daicCmdSource);
const daicCmdDest = path.join(localBin, 'daic.cmd');
await fs.copyFile(daicCmdSource, daicCmdDest);
console.log(color(` ✓ Installed daic.cmd to ${localBin}`, colors.green));
} catch {
console.log(color(' ⚠️ daic.cmd script not found', colors.yellow));
}
try {
// Copy .ps1 script
await fs.access(daicPs1Source);
const daicPs1Dest = path.join(localBin, 'daic.ps1');
await fs.copyFile(daicPs1Source, daicPs1Dest);
console.log(color(` ✓ Installed daic.ps1 to ${localBin}`, colors.green));
} catch {
console.log(color(' ⚠️ daic.ps1 script not found', colors.yellow));
}
console.log(color(` ℹ Add ${localBin} to your PATH to use 'daic' command`, colors.yellow));
} else {
// Unix/Mac installation
const daicSource = path.join(SCRIPT_DIR, 'cc_sessions/scripts/daic');
const daicDest = '/usr/local/bin/daic';
try {
await fs.copyFile(daicSource, daicDest);
await fs.chmod(daicDest, 0o755);
} catch (error) {
if (error.code === 'EACCES') {
console.log(color('⚠️ Cannot write to /usr/local/bin. Trying with sudo...', colors.yellow));
try {
execSync(`sudo cp ${daicSource} ${daicDest}`, { stdio: 'inherit' });
execSync(`sudo chmod +x ${daicDest}`, { stdio: 'inherit' });
} catch {
console.log(color('⚠️ Could not install daic command globally. You can run it locally from .claude/scripts/', colors.yellow));
}
}
}
}
}
// Interactive menu with keyboard navigation
async function interactiveMenu(items, options = {}) {