-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclsecure-src
More file actions
executable file
·718 lines (623 loc) · 23.8 KB
/
clsecure-src
File metadata and controls
executable file
·718 lines (623 loc) · 23.8 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
#!/bin/bash
# clsecure - Enhanced isolation with User + Namespace (Firejail)
# Runs Claude Code in an isolated environment with user and namespace isolation
set -euo pipefail
# ------------------------------------------------------------------------------
# Module Loading
# ------------------------------------------------------------------------------
# Determine script directory (handles symlinks and PATH scenarios)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="${SCRIPT_DIR}/lib"
# Phase 1: Initialize variables FIRST (before sourcing other modules)
source "${LIB_DIR}/vars.sh"
init_clsecure_vars # Initialize all global variables
# Phase 2: Source modules in dependency order
# Level 1: No dependencies (but uses vars for colors)
source "${LIB_DIR}/logging.sh"
# Level 2: Depends on logging + vars
source "${LIB_DIR}/lock.sh"
source "${LIB_DIR}/config.sh"
# Level 3: Depends on logging + config/vars
source "${LIB_DIR}/worker.sh"
source "${LIB_DIR}/status.sh"
# Level 4: Depends on logging + worker + vars
source "${LIB_DIR}/git.sh"
source "${LIB_DIR}/sanitize.sh"
source "${LIB_DIR}/deps.sh"
source "${LIB_DIR}/isolation.sh"
# Level 5: Depends on logging + git + worker + vars
source "${LIB_DIR}/sync.sh"
# Level 5.5: Depends on logging + git + worker + vars
source "${LIB_DIR}/worktree.sh"
# Level 6: Depends on logging + worker + vars
source "${LIB_DIR}/cleanup.sh"
show_help() {
cat << EOF
Usage: clsecure [OPTIONS]
Run Claude Code with enhanced isolation (User + Namespace).
OPTIONS:
--help, -h Show this help message
--list, -l List all claude-worker users and their status
--status Show worker sessions and commit status
--status --all Show all workers (not just current project)
--cleanup Interactively remove worker users
--cleanup-all Remove ALL claude-worker users (requires confirmation)
--mode MODE Isolation mode: user, namespace (default)
--allow-network Allow network access (default: from config or true)
--no-network Disable network access (--net=none in firejail)
--allow-docker Allow access to Docker (WARNING: reduces isolation)
--no-docker Disable Docker access (default)
--install-deps Install project dependencies (npm/pip) on startup
--config Show current configuration and config file location
--info Show isolation details for current mode
--shell Start shell instead of Claude (for debugging)
--auto-sync Non-interactive post-session sync (for EPCTC/programmatic use)
--skip-setup Skip setup script execution
--full-clone Clone full git history (slower, default is shallow)
--session, -s NAME Run a named session (multiple environments per project)
--provider NAME API provider: anthropic (default), kimi
ISOLATION MODES:
user Basic user isolation (original clsecure behavior)
namespace User + Namespace (firejail) - RECOMMENDED
CONFIGURATION FILE:
Project: .clsecure/config (per-project, shareable via git)
User: ~/.config/clsecure/config or ~/.clsecurerc
Precedence: CLI args > User config > Project config > Defaults
Security-sensitive settings (docker, network, setup_script,
install_dependencies) can only be set via user config or CLI flags.
Project config can set: mode, cleanup_hook_timeout, skip_docker_autodetect.
REQUIREMENTS:
- git (must be run from a git repository)
- rsync
- sudo privileges
- For namespace mode: firejail
EXAMPLES:
# Run with recommended namespace isolation
clsecure
# Run with network disabled
clsecure --no-network
# Run with Docker access (for docker-compose)
clsecure --allow-docker
# Run with basic user isolation only
clsecure --mode user
# Show config file and current settings
clsecure --config
# Show isolation details
clsecure --info
# Run multiple sessions for the same project
clsecure --session auth
clsecure --session payments
# Run with Kimi K2.5 as the API provider
clsecure --provider kimi
SECURITY MODEL:
User isolation: Dedicated Linux user per project
Namespace isolation: + Firejail sandbox (PID, mount, network, IPC)
EOF
exit 0
}
check_requirements() {
local missing=()
command -v git &>/dev/null || missing+=("git")
command -v rsync &>/dev/null || missing+=("rsync")
command -v sudo &>/dev/null || missing+=("sudo")
if [ ${#missing[@]} -ne 0 ]; then
log_error "Missing required tools: ${missing[*]}"
exit 1
fi
if ! sudo -n true 2>/dev/null; then
log_warn "This script requires sudo privileges."
sudo true || { log_error "Failed to obtain sudo privileges."; exit 1; }
fi
}
# Note: Trap handler will be registered after lock acquisition (line ~273)
# This ensures cleanup happens even on early exits (e.g., missing git repo, missing Claude CLI)
# The trap must be registered AFTER acquire_lock succeeds, so the lock is released on exit
# ------------------------------------------------------------------------------
# Load configuration file (before parsing CLI args)
# ------------------------------------------------------------------------------
load_config
# ------------------------------------------------------------------------------
# Parse arguments (CLI overrides config file)
# ------------------------------------------------------------------------------
while [[ $# -gt 0 ]]; do
case $1 in
--help|-h)
show_help
;;
--list|-l)
list_workers
;;
--status)
STATUS_ALL=false
[[ "${2:-}" == "--all" ]] && STATUS_ALL=true && shift
show_worker_status "$STATUS_ALL"
;;
--cleanup)
cleanup_workers
;;
--cleanup-all)
cleanup_all_workers
;;
--info)
show_isolation_info
;;
--config)
show_config_info
;;
--mode)
ISOLATION_MODE="$2"
if [[ ! "$ISOLATION_MODE" =~ ^(user|namespace)$ ]]; then
log_error "Invalid mode: $ISOLATION_MODE (must be user or namespace)"
exit 1
fi
shift 2
;;
--allow-network)
ALLOW_NETWORK=true
shift
;;
--no-network)
ALLOW_NETWORK=false
shift
;;
--allow-docker)
ALLOW_DOCKER=true
shift
;;
--no-docker)
ALLOW_DOCKER=false
shift
;;
--install-deps)
INSTALL_DEPS=true
shift
;;
--shell)
SHELL_ONLY=true
shift
;;
--auto-sync)
AUTO_SYNC=true
shift
;;
--skip-setup)
SKIP_SETUP=true
shift
;;
--full-clone)
FULL_CLONE=true
shift
;;
--session|-s)
SESSION_NAME="$2"
shift 2
;;
--provider)
PROVIDER="$2"
if [[ ! "$PROVIDER" =~ ^(anthropic|kimi)$ ]]; then
log_error "Invalid provider: $PROVIDER (must be anthropic or kimi)"
exit 1
fi
[ "$PROVIDER" = "anthropic" ] && PROVIDER=""
shift 2
;;
*)
log_error "Unknown option: $1"
show_help
;;
esac
done
# Validate provider API key
if [ "$PROVIDER" = "kimi" ]; then
if [ -z "$KIMI_API_KEY" ]; then
log_error "Kimi provider requires an API key."
log_info "Set it via: export KIMI_API_KEY=sk-kimi-..."
log_info "Or add 'kimi_api_key = sk-kimi-...' to ~/.config/clsecure/config"
exit 1
fi
fi
# Recompute worker variables if a session name was provided
if [ -n "$SESSION_NAME" ]; then
if ! recompute_worker_vars; then
log_error "Invalid session name: '$SESSION_NAME' (sanitizes to empty)"
exit 1
fi
fi
# ------------------------------------------------------------------------------
# Main script
# ------------------------------------------------------------------------------
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Claude Code Enhanced Secure Runner ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""
# Check requirements
log_step "Checking requirements..."
check_requirements
check_isolation_requirements
# Verify git repository
log_step "Verifying git repository..."
if ! git rev-parse --git-dir &>/dev/null; then
log_error "Not a git repository. Please run from a git project root."
exit 1
fi
if ! git diff-index --quiet HEAD -- 2>/dev/null; then
log_warn "You have uncommitted changes in your working directory."
if [ "${AUTO_SYNC:-false}" = true ]; then
log_info "Auto-sync mode: continuing with uncommitted changes."
else
read -p "Continue anyway? (y/n): " continue_anyway
if [[ ! "$continue_anyway" =~ ^[Yy]$ ]]; then
log_info "Aborted. Please commit or stash your changes first."
exit 0
fi
fi
fi
ORIGINAL_BRANCH=$(git branch --show-current)
if [ -z "$ORIGINAL_BRANCH" ]; then
ORIGINAL_BRANCH=$(git rev-parse --short HEAD)
log_warn "Detached HEAD state. Using commit: $ORIGINAL_BRANCH"
fi
export ORIGINAL_BRANCH # Export so it's available in sync.sh functions
# Warn if on a claude/* branch (temporary branch from previous session)
if [[ "$ORIGINAL_BRANCH" =~ ^claude/ ]]; then
log_warn "You are currently on a temporary Claude branch: $ORIGINAL_BRANCH"
log_warn "This may prevent proper commit import from the worker session."
if [ "${AUTO_SYNC:-false}" = true ]; then
log_info "Auto-sync mode: continuing on claude/* branch."
else
echo ""
echo "It's recommended to switch to your main branch first, for example:"
echo " git checkout main # or develop, master, etc."
echo ""
read -p "Continue anyway? (y/n): " CONTINUE_ANYWAY
if [[ ! "$CONTINUE_ANYWAY" =~ ^[Yy]$ ]]; then
log_info "Aborted. Please switch to your main branch first."
exit 0
fi
fi
fi
log_info "Project: $PROJECT_NAME"
log_info "Branch: $ORIGINAL_BRANCH"
[ -n "$SESSION_NAME" ] && log_info "Session: $SESSION_NAME"
[ -n "$PROVIDER" ] && log_info "Provider: $PROVIDER"
log_info "Worker user: $WORKER_USER"
log_security "Isolation: $ISOLATION_MODE$([ "$ALLOW_NETWORK" = true ] && echo " (network enabled)" || echo " (network disabled)")$([ "$ALLOW_DOCKER" = true ] && echo " (docker enabled)")"
# Check if already running
log_step "Checking for existing session..."
if ! acquire_lock; then
if [ -n "$SESSION_NAME" ]; then
log_error "A session for '$PROJECT_NAME' (session: $SESSION_NAME) is already running!"
else
log_error "A session for '$PROJECT_NAME' is already running!"
fi
log_info "Use 'clsecure --list' to see active sessions."
exit 1
fi
# Register trap handler early (after lock acquisition) to ensure cleanup on early exits
# This is critical: if script exits early (e.g., missing git repo, missing Claude CLI),
# the trap must be registered to release the lock
trap cleanup_on_exit EXIT
# Create worker user if needed
log_step "Setting up worker user '$WORKER_USER'..."
create_worker_user
# Handle existing project files
SKIP_COPY=false
if [ -d "$WORKER_PROJECT" ]; then
if [ "${AUTO_SYNC:-false}" = true ]; then
log_info "Auto-sync mode: resuming existing project files."
SKIP_COPY=true
else
echo ""
log_warn "Project files already exist for this user."
echo ""
echo "Options:"
echo " 1) Resume (keep existing files)"
echo " 2) Replace (fresh copy from source)"
echo " 3) Abort"
echo ""
read -p "Choose (1/2/3): " EXISTING_OPTION
case $EXISTING_OPTION in
1)
log_info "Resuming..."
SKIP_COPY=true
;;
2)
log_info "Replacing..."
sudo rm -rf "$WORKER_PROJECT"
;;
3)
log_info "Aborted."
release_lock
exit 0
;;
*)
log_error "Invalid option."
release_lock
exit 1
;;
esac
fi
fi
# Clone repository and sync working directory
if [ "$SKIP_COPY" = false ]; then
log_step "Setting up project files..."
# Check available disk space before cloning
REQUIRED_SPACE_MB=1000 # Estimate: 1GB minimum
if ! check_disk_space "$REQUIRED_SPACE_MB"; then
release_lock
exit 1
fi
if is_git_worktree "$CURRENT_DIR"; then
if ! clone_worktree_repository; then
log_warn "Worktree clone failed, trying standard clone..."
if ! clone_repository; then
release_lock
exit 1
fi
fi
else
if ! clone_repository; then
release_lock
exit 1
fi
fi
# Record base commit for accurate branch creation during import
git rev-parse HEAD 2>/dev/null | sudo tee "$WORKER_HOME/.clsecure/base_commit" > /dev/null
sync_working_directory
copy_submodules
log_info "Project ready at $WORKER_PROJECT"
fi
setup_worker_home
# Copy git hooks (runs on every session, not just fresh setup)
# Merges repo-level and global hooks into a single directory when core.hooksPath is set
copy_git_hooks
# Make sure project-local MCP config is portable across worker users
sanitize_mcp_config
# Rewrite relative "./" paths in hook commands to absolute paths
sanitize_hook_relative_paths
# Copy configurations
log_step "Setting up configurations..."
# Detect provider switch to prevent cross-contamination between providers.
# When switching (e.g. kimi → anthropic or anthropic → kimi), we clean the
# worker's Claude config to start fresh.
LAST_PROVIDER=$(sudo cat "$WORKER_HOME/.clsecure/provider" 2>/dev/null || echo "")
CURRENT_PROVIDER="${PROVIDER:-}"
PROVIDER_SWITCHED=false
if [ "$LAST_PROVIDER" != "$CURRENT_PROVIDER" ] && [ -n "$LAST_PROVIDER" -o -n "$CURRENT_PROVIDER" ]; then
PROVIDER_SWITCHED=true
log_info "Provider changed (${LAST_PROVIDER:-anthropic} -> ${CURRENT_PROVIDER:-anthropic}), cleaning config..."
sudo rm -rf "$WORKER_HOME/.claude" "$WORKER_HOME/.claude.json"
fi
# Record current provider for next session
echo "$CURRENT_PROVIDER" | sudo tee "$WORKER_HOME/.clsecure/provider" > /dev/null
if [ -z "${PROVIDER:-}" ]; then
# Default provider (Anthropic): copy Claude config for session continuity
if [ -d "$HOME/.claude" ]; then
log_info "Copying Claude config (excluding large files)..."
sudo mkdir -p "$WORKER_HOME/.claude"
sudo rsync -a \
--exclude='debug' \
--exclude='file-history' \
--exclude='history.jsonl' \
--exclude='cache' \
--exclude='paste-cache' \
--exclude='plans' \
--exclude='__store.db' \
--exclude='*.db' \
--exclude='*.log' \
--exclude='venv' \
--exclude='.venv' \
--exclude='__pycache__' \
--exclude='.git' \
--exclude='node_modules' \
"$HOME/.claude/" "$WORKER_HOME/.claude/" 2>/dev/null || true
sudo chown -R "$WORKER_USER:$WORKER_USER" "$WORKER_HOME/.claude"
sanitize_worker_claude_home_paths
fi
# Copy onboarding state with OAuth so user stays logged in
if [ -f "$HOME/.claude.json" ]; then
sudo cp "$HOME/.claude.json" "$WORKER_HOME/.claude.json"
sudo chown "$WORKER_USER:$WORKER_USER" "$WORKER_HOME/.claude.json"
fi
else
# Third-party provider (e.g. kimi): no config copy, just env vars.
# Clean any leftover config to avoid contamination from previous sessions.
sudo rm -rf "$WORKER_HOME/.claude" "$WORKER_HOME/.claude.json"
log_info "Third-party provider: skipping Claude config copy (env vars only)"
fi
setup_git_config
# Setup shell environment
log_step "Setting up shell environment..."
WORKER_BASHRC="$WORKER_HOME/.bashrc"
if ! grep -q "NPM_CONFIG_PREFIX" "$WORKER_BASHRC" 2>/dev/null; then
sudo tee "$WORKER_BASHRC" > /dev/null << 'BASHRCEOF'
# Linuxbrew setup
if [ -f /home/linuxbrew/.linuxbrew/bin/brew ]; then
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
fi
# NPM global packages
export NPM_CONFIG_PREFIX="$HOME/.npm-global"
export PATH="$HOME/.npm-global/bin:$PATH"
BASHRCEOF
sudo chown "$WORKER_USER:$WORKER_USER" "$WORKER_BASHRC"
log_info "Shell environment configured."
else
log_info "Shell environment already configured."
fi
sudo -u "$WORKER_USER" mkdir -p "$WORKER_HOME/.npm-global"
# Warn early if MCP runtime is missing
check_worker_mcp_runtime
# Verify Claude CLI
log_step "Checking Claude CLI..."
if [ -x "/home/linuxbrew/.linuxbrew/bin/claude" ]; then
log_info "Claude CLI found."
CLAUDE_BIN="/home/linuxbrew/.linuxbrew/bin/claude"
export CLAUDE_BIN # Export so it's available in subshells (isolation.sh functions)
else
log_error "Claude CLI not found at /home/linuxbrew/.linuxbrew/bin/claude"
log_info "Install with: brew install claude-code"
release_lock
exit 1
fi
# Run setup script if configured (optional - failures should not terminate script)
if [ "$SKIP_SETUP" = true ]; then
log_info "Skipping setup script (--skip-setup)"
else
run_setup_script || {
log_warn "Setup script execution failed, but continuing..."
}
fi
# Install dependencies if requested
if [ "$INSTALL_DEPS" = true ]; then
install_project_dependencies
fi
# ------------------------------------------------------------------------------
# Start session with selected isolation
# ------------------------------------------------------------------------------
echo ""
if [ "$SHELL_ONLY" = true ]; then
echo -e "${CYAN}╔════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║ Starting Debug Shell Session ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════╝${NC}"
else
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Starting Claude Code Session ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
fi
echo ""
log_info "User: $WORKER_USER"
log_info "Project: $WORKER_PROJECT"
log_security "Isolation: $ISOLATION_MODE"
echo ""
# Add --continue flag if resuming an existing Anthropic session.
# Skip when: using a third-party provider, or provider just switched
# (config was cleaned, so there's no conversation to continue).
CONTINUE_FLAG=""
if [ "$SKIP_COPY" = true ] && [ -z "${PROVIDER:-}" ] && [ "$PROVIDER_SWITCHED" = false ]; then
CONTINUE_FLAG="--continue"
log_info "Resuming previous Claude session..."
fi
if [ "$SHELL_ONLY" = true ]; then
echo -e "${YELLOW}Type 'exit' to end shell session.${NC}"
else
echo -e "${YELLOW}Type /exit or press Ctrl+C to end session.${NC}"
fi
echo ""
set +e
if [ "$SHELL_ONLY" = true ]; then
# Shell-only mode for debugging
case $ISOLATION_MODE in
user)
start_user_shell
;;
namespace)
start_namespace_shell
;;
esac
else
# Normal Claude session
# Helper to start session with fallback: if --continue fails (no conversation
# found, exit code 1), retry without it so the user gets a fresh session
_run_session() {
local flag="$1"
case $ISOLATION_MODE in
user) start_user_session "$flag" ;;
namespace) start_namespace_session "$flag" ;;
esac
}
_run_session "$CONTINUE_FLAG"
_session_rc=$?
if [ $_session_rc -ne 0 ] && [ -n "$CONTINUE_FLAG" ]; then
log_info "No previous conversation found. Starting fresh session..."
_run_session ""
_session_rc=$?
fi
fi
CLAUDE_EXIT_CODE=${_session_rc:-$?}
# Keep set +e for the change detection phase to avoid premature exits
set +e
# ------------------------------------------------------------------------------
# Handle changes (Commits + Uncommitted)
# ------------------------------------------------------------------------------
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Session Ended ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""
# Detect changes (sets WORKER_COMMITS, NUM_COMMITS, WORKER_CHANGES)
set +e # Temporarily disable strict error handling for change detection
detect_worker_changes
set -e # Re-enable strict error handling after safely gathering change information
# Auto-sync mode: non-interactive sync for programmatic use (e.g., EPCTC sandbox)
if [ "${AUTO_SYNC:-false}" = true ]; then
if [ "$NUM_COMMITS" -gt 0 ] || [ -n "$WORKER_CHANGES" ]; then
import_commits || log_warn "Commit import failed"
if [ -n "$WORKER_CHANGES" ]; then
log_info "Syncing uncommitted changes..."
if sudo rsync -a \
--exclude='.git' --exclude='.epctc' --exclude='node_modules' --exclude='venv' \
--exclude='.venv' --exclude='__pycache__' --exclude='.pytest_cache' \
--exclude='dist' --exclude='build' --exclude='.next' --exclude='target' \
"$WORKER_PROJECT/" "$CURRENT_DIR/"; then
sudo chown -R "$(whoami):$(id -gn)" "$CURRENT_DIR"
log_info "Sync complete."
else
log_warn "Rsync failed. Uncommitted changes may not be synced."
fi
fi
else
log_info "No changes to sync."
fi
release_lock
exit $CLAUDE_EXIT_CODE
fi
if show_sync_summary; then
# No changes detected
echo ""
read -p "Remove worker user '$WORKER_USER'? (y/n): " cleanup
if [[ "$cleanup" =~ ^[Yy]$ ]]; then
cleanup_session "stop"
sudo userdel -r "$WORKER_USER" 2>/dev/null || true
log_info "User removed."
fi
release_lock
exit 0
fi
echo "Options:"
echo " 1) Create branch and import ALL work (commits + changes)"
echo " 2) Discard changes and remove user"
echo " 3) Keep for later (resume with clsecure)"
echo ""
read -p "Choose (1/2/3): " OPTION
case $OPTION in
1)
if ! create_branch_and_import; then
exit 1
fi
cleanup_session "stop"
;;
2)
cleanup_level="stop"
if [ "$ALLOW_DOCKER" = true ]; then
echo ""
read -p "Also remove Docker data volumes? (y/n): " purge_volumes
[[ "$purge_volumes" =~ ^[Yy]$ ]] && cleanup_level="purge"
fi
cleanup_session "$cleanup_level"
log_warn "Removing user and all changes..."
sudo userdel -r "$WORKER_USER" 2>/dev/null || true
log_info "Done."
;;
3)
log_info "Keeping user '$WORKER_USER' for later."
if [ -n "$SESSION_NAME" ]; then
echo "Resume by running 'clsecure --session $SESSION_NAME' from the same project."
else
echo "Resume by running 'clsecure' from the same project."
fi
;;
esac
release_lock
echo ""
log_info "Done!"