Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:22:09 +08:00
commit 6fc9ce7847
11 changed files with 1570 additions and 0 deletions

View File

@@ -0,0 +1,267 @@
---
model: claude-sonnet-4-5-20250929
description: Create a git worktree with isolated configuration for parallel development
argument-hint: [branch-name] [port-offset]
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
---
# Purpose
Create a new git worktree in the `trees/` directory with completely isolated configuration for parallel execution. This enables running multiple instances of the observability system simultaneously without port conflicts, database collisions, or hook misconfiguration.
## Variables
```
PROJECT_CWD: . (current working directory - the main project root)
BRANCH_NAME: $1 (required)
PORT_OFFSET: $2 (optional, defaults to auto-calculated based on existing worktrees, starts at 1)
WORKTREE_BASE_DIR: trees/
WORKTREE_DIR: trees/<BRANCH_NAME>
SERVER_BASE_PORT: 4000
CLIENT_BASE_PORT: 5173
SERVER_PORT: 4000 + (PORT_OFFSET * 10) # First worktree: 4010, Second: 4020, etc.
CLIENT_PORT: 5173 + (PORT_OFFSET * 10) # First worktree: 5183, Second: 5193, etc.
OPEN_BROWSER_WHEN_COMPLETE: false # Set to true to auto-open browser after setup
NOTE: Main repo uses ports 4000 and 5173 (no offset)
Worktrees start at offset 1 to avoid conflicts with main repo
```
## Instructions
- This is a ONE-SHOT command that creates AND starts a worktree automatically
- Creates a fully functional, isolated clone of the codebase in a separate worktree
- Each worktree runs on unique ports to prevent conflicts when running in parallel
- Port offsets start at 1 and increment (1→4010/5183, 2→4020/5193, 3→4030/5203...)
- Main repo preserves default ports 4000/5173 for primary development work
- All environment configuration must be worktree-specific
- Database files are isolated per worktree (each gets its own events.db)
- Hook scripts will send events to the worktree's specific server instance
- Dependencies are installed automatically for each worktree
- After setup, the script automatically starts both server and client services
- The start script kills any existing processes on the target ports before starting
- Services run in the FOREGROUND - Ctrl+C stops both server and client
- Validation ensures the worktree is ready before starting services
- If branch doesn't exist locally, create it from current HEAD
- If branch exists but isn't checked out, create worktree from it
- Provide clear access URLs so user can immediately use the running instance
## Workflow
### 1. Parse and Validate Arguments
- Read BRANCH_NAME from $1, error if missing
- Read PORT_OFFSET from $2 if provided
- If PORT_OFFSET not provided, calculate next available offset:
- List all existing worktrees: `git worktree list`
- Check PROJECT_CWD/trees/ directory for existing worktrees
- Count existing worktrees and use (count + 1) as offset (1, 2, 3, 4...)
- IMPORTANT: Offset starts at 1 to preserve main repo ports (4000, 5173)
- First worktree gets offset 1 → ports 4010, 5183
- Second worktree gets offset 2 → ports 4020, 5193
- Calculate SERVER_PORT and CLIENT_PORT using offset * 10
- Validate branch name format (no spaces, valid git branch name)
### 2. Pre-Creation Validation
- Check if PROJECT_CWD/trees/ directory exists, create if not: `mkdir -p trees`
- Verify trees/ is in PROJECT_CWD/.gitignore (should be there already)
- Check if worktree already exists at WORKTREE_DIR
- Check if branch exists: `git branch --list <BRANCH_NAME>`
- If branch doesn't exist, will create it in next step
- If branch exists, will checkout to create worktree
- Check if calculated ports are available:
- Check SERVER_PORT: `lsof -i :SERVER_PORT` (should return nothing)
- Check CLIENT_PORT: `lsof -i :CLIENT_PORT` (should return nothing)
- If ports are in use, error with message to try different offset
### 3. Create Git Worktree
- From PROJECT_CWD, create worktree with: `git worktree add trees/<BRANCH_NAME> <BRANCH_NAME>`
- If branch doesn't exist, this creates it from HEAD
- If branch exists, this checks it out in the worktree
- This creates WORKTREE_DIR at PROJECT_CWD/trees/<BRANCH_NAME>
- Verify worktree was created: `git worktree list | grep trees/<BRANCH_NAME>`
- All subsequent operations will reference WORKTREE_DIR (which is PROJECT_CWD/trees/<BRANCH_NAME>)
### 4. Setup Root Environment File
- Check if root .env exists in main project at PROJECT_CWD/.env
- If PROJECT_CWD/.env exists:
- Copy it to worktree root: `cp <PROJECT_CWD>/.env <WORKTREE_DIR>/.env`
- Note: This preserves API keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.)
- If PROJECT_CWD/.env doesn't exist:
- Copy .env.sample if available: `cp <PROJECT_CWD>/.env.sample <WORKTREE_DIR>/.env`
- Add warning to report that user needs to configure API keys
### 5. Setup Server Environment
- Create WORKTREE_DIR/apps/server/.env with SERVER_PORT and DB_PATH
- File contents:
```
SERVER_PORT=<calculated SERVER_PORT>
DB_PATH=events.db
```
- The DB_PATH is relative and will create events.db in WORKTREE_DIR/apps/server/ directory
- This ensures complete database isolation between worktrees
### 6. Setup Client Environment
- Create WORKTREE_DIR/apps/client/.env with all client configuration
- File contents:
```
VITE_PORT=<calculated CLIENT_PORT>
VITE_API_URL=http://localhost:<calculated SERVER_PORT>
VITE_WS_URL=ws://localhost:<calculated SERVER_PORT>/stream
VITE_MAX_EVENTS_TO_DISPLAY=100
OBSERVABILITY_SERVER_URL=http://localhost:<calculated SERVER_PORT>/events
```
- The OBSERVABILITY_SERVER_URL is critical for hooks to send events to correct server
### 7. Install Dependencies
- Install server dependencies:
- `cd <WORKTREE_DIR>/apps/server && bun install`
- Verify WORKTREE_DIR/apps/server/node_modules directory was created
- Install client dependencies:
- `cd <WORKTREE_DIR>/apps/client && bun install`
- Verify WORKTREE_DIR/apps/client/node_modules directory was created
- Return to worktree root: `cd <WORKTREE_DIR>`
### 8. Validation
- Verify directory structure:
- Confirm WORKTREE_DIR exists
- Confirm WORKTREE_DIR/.env exists at root
- Confirm WORKTREE_DIR/apps/server/.env exists
- Confirm WORKTREE_DIR/apps/client/.env exists
- Confirm WORKTREE_DIR/apps/server/node_modules exists
- Confirm WORKTREE_DIR/apps/client/node_modules exists
- List worktrees to confirm: `git worktree list`
- Read back the created env files to confirm values are correct
### 9. Start the Worktree Services
- Change to worktree directory: `cd <WORKTREE_DIR>`
- Start the system using the one-shot script in the BACKGROUND:
- Command: `cd <WORKTREE_DIR> && SERVER_PORT=<calculated SERVER_PORT> CLIENT_PORT=<calculated CLIENT_PORT> sh scripts/start-system.sh > /dev/null 2>&1 &`
- This runs WORKTREE_DIR/scripts/start-system.sh in background, redirecting output to suppress it
- The script will automatically:
- Kill any existing processes on those ports
- Start the server from WORKTREE_DIR/apps/server on the calculated port
- Start the client from WORKTREE_DIR/apps/client on the calculated port
- Wait for both services to be ready (health check)
- Give services 3-5 seconds to start before reporting
- Wait with: `sleep 5`
- Verify services are running:
- Check server: `curl -s http://localhost:<SERVER_PORT>/events/filter-options >/dev/null 2>&1`
- Check client: `curl -s http://localhost:<CLIENT_PORT> >/dev/null 2>&1`
- If health checks pass, services are confirmed running
### 10. Open Dashboard in Chrome (Optional)
- ONLY if OPEN_BROWSER_WHEN_COMPLETE is true:
- After services are confirmed running, open the dashboard in Chrome:
- Command: `open -a "Google Chrome" http://localhost:<CLIENT_PORT>`
- This automatically opens the worktree's dashboard in a new Chrome tab
- If Chrome is not available, fall back to default browser: `open http://localhost:<CLIENT_PORT>`
- Note: This happens in the background and doesn't block the report
- If OPEN_BROWSER_WHEN_COMPLETE is false, skip this step entirely
### 11. Report
Follow the Report section format below to provide comprehensive setup information.
## Report
After successful worktree creation, validation, and startup, provide a detailed report in the following format:
```
✅ Git Worktree Created and Started Successfully!
📁 Worktree Details:
Location: trees/<BRANCH_NAME>
Branch: <BRANCH_NAME>
Status: 🟢 RUNNING
🔌 Port Configuration:
Server Port: <SERVER_PORT>
Client Port: <CLIENT_PORT>
Port Offset: <PORT_OFFSET> (multiply by 10)
🌐 Access URLs (LIVE NOW):
🖥️ Dashboard: http://localhost:<CLIENT_PORT>
🔌 Server API: http://localhost:<SERVER_PORT>
📡 WebSocket: ws://localhost:<SERVER_PORT>/stream
📦 Dependencies:
✓ Server dependencies installed (WORKTREE_DIR/apps/server/node_modules)
✓ Client dependencies installed (WORKTREE_DIR/apps/client/node_modules)
🗄️ Database:
Path: WORKTREE_DIR/apps/server/events.db (isolated per worktree)
⚙️ Environment Files:
✓ Root .env (WORKTREE_DIR/.env with API keys)
✓ Server .env (WORKTREE_DIR/apps/server/.env with SERVER_PORT, DB_PATH)
✓ Client .env (WORKTREE_DIR/apps/client/.env with VITE_PORT, API URLs)
🎯 Services Running:
✓ Server started on port <SERVER_PORT> (background)
✓ Client started on port <CLIENT_PORT> (background)
✓ WebSocket streaming active
✓ Ready to receive hook events
📝 Important Notes:
• The services are running in the BACKGROUND
• Services auto-started and will continue running until manually stopped
• Open http://localhost:<CLIENT_PORT> in your browser NOW to view the dashboard
• This worktree is completely isolated from the main codebase
• You can run multiple worktrees simultaneously with different ports
• Check running processes: lsof -i :<SERVER_PORT> and lsof -i :<CLIENT_PORT>
🔄 To Restart This Worktree Later:
cd trees/<BRANCH_NAME>
# Kill existing processes first
lsof -ti :<SERVER_PORT> | xargs kill -9
lsof -ti :<CLIENT_PORT> | xargs kill -9
# Or use the one-shot script (it kills automatically)
SERVER_PORT=<SERVER_PORT> CLIENT_PORT=<CLIENT_PORT> sh scripts/start-system.sh > /dev/null 2>&1 &
🧹 To Stop This Worktree:
# Option 1: Manual kill
lsof -ti :<SERVER_PORT> | xargs kill -9
lsof -ti :<CLIENT_PORT> | xargs kill -9
# Option 2: Use reset script (with environment variables)
cd trees/<BRANCH_NAME>
SERVER_PORT=<SERVER_PORT> CLIENT_PORT=<CLIENT_PORT> ./scripts/reset-system.sh
🗑️ To Remove This Worktree:
# Stop services first (see above)
# Then remove the worktree:
git worktree remove trees/<BRANCH_NAME>
# Or force remove if needed:
git worktree remove trees/<BRANCH_NAME> --force
🎉 Next Steps:
1. Open http://localhost:<CLIENT_PORT> in your browser NOW
2. Open Claude Code in this worktree directory
3. Run commands - events will stream to this isolated instance
4. Compare side-by-side with other worktrees or main codebase
5. Each instance maintains its own database and event history
```
If any validation steps failed or warnings occurred, include an additional section:
```
⚠️ Warnings / Action Required:
- <List any warnings or actions the user needs to take>
```

View File

@@ -0,0 +1,239 @@
---
model: claude-sonnet-4-5-20250929
description: List all git worktrees with their configuration and status
allowed-tools: Bash, Read, Glob, Grep
---
# Purpose
List all git worktrees in the `trees/` directory with comprehensive information including branch names, directories, environment variables, port configuration, and service status.
## Variables
```
PROJECT_CWD: . (current working directory - the main project root)
WORKTREE_BASE_DIR: trees/
```
## Instructions
- List all worktrees managed by git
- For each worktree in trees/, gather configuration details
- Read environment files to extract port configuration
- Check if services are running on configured ports
- Display comprehensive information in a clear, organized format
- Show which worktrees are active vs stopped
- Provide quick action commands for each worktree
## Workflow
### 1. List Git Worktrees
- Run: `git worktree list`
- Parse output to identify all worktrees
- Filter for worktrees in PROJECT_CWD/trees/ directory
- Extract:
- Worktree path
- Branch name
- Commit hash (if available)
### 2. Gather Configuration for Each Worktree
For each worktree found in trees/:
**Extract Branch/Directory Info:**
- Worktree directory: `trees/<branch-name>`
- Branch name from git worktree list
- Working directory path
**Read Server Configuration:**
- Check if `<worktree>/apps/server/.env` exists
- If exists, read and extract:
- `SERVER_PORT`
- `DB_PATH`
- If doesn't exist, note as "Not configured"
**Read Client Configuration:**
- Check if `<worktree>/apps/client/.env` exists
- If exists, read and extract:
- `VITE_PORT`
- `VITE_API_URL`
- `VITE_WS_URL`
- `VITE_MAX_EVENTS_TO_DISPLAY`
- If doesn't exist, note as "Not configured"
**Read Root Configuration:**
- Check if `<worktree>/.env` exists
- Note presence/absence (contains API keys, don't display values)
### 3. Check Service Status
For each worktree with port configuration:
**Check Server Status:**
- If SERVER_PORT identified, check: `lsof -i :<SERVER_PORT>`
- Determine if process is running
- Extract PID if running
**Check Client Status:**
- If VITE_PORT identified, check: `lsof -i :<VITE_PORT>`
- Determine if process is running
- Extract PID if running
### 4. Check Dependencies
For each worktree:
- Check if `<worktree>/apps/server/node_modules` exists
- Check if `<worktree>/apps/client/node_modules` exists
- Note if dependencies are installed or missing
### 5. Calculate Statistics
- Total number of worktrees
- Number with services running
- Number with services stopped
- Total ports in use
- Available port offsets (suggest next available)
### 6. Report
Follow the Report section format below.
## Report
After gathering all information, provide a comprehensive report in the following format:
```
📊 Git Worktrees Overview
═══════════════════════════════════════════════════════════════
📈 Summary:
Total Worktrees: <count>
Running: <count> | Stopped: <count>
Next Available Port Offset: <offset>
═══════════════════════════════════════════════════════════════
🌳 Main Repository (Default)
📁 Location: <project-root>
🌿 Branch: <current-branch>
🔌 Ports: 4000 (server), 5173 (client)
🎯 Status: <RUNNING|STOPPED>
Actions:
└─ Start: ./scripts/start-system.sh
└─ Stop: ./scripts/reset-system.sh
───────────────────────────────────────────────────────────────
🌳 Worktree: <branch-name>
📁 Location: trees/<branch-name>
🌿 Branch: <branch-name>
📝 Commit: <commit-hash-short>
⚙️ Configuration:
├─ Server Port: <SERVER_PORT>
├─ Client Port: <VITE_PORT>
├─ Database: <DB_PATH>
├─ API URL: <VITE_API_URL>
└─ WebSocket: <VITE_WS_URL>
📦 Dependencies:
├─ Server: <✓ Installed | ❌ Missing>
└─ Client: <✓ Installed | ❌ Missing>
🎯 Service Status:
├─ Server: <🟢 RUNNING (PID: xxxx) | 🔴 STOPPED>
└─ Client: <🟢 RUNNING (PID: xxxx) | 🔴 STOPPED>
🌐 Access URLs (if running):
├─ Dashboard: http://localhost:<VITE_PORT>
├─ Server API: http://localhost:<SERVER_PORT>
└─ WebSocket: ws://localhost:<SERVER_PORT>/stream
Actions:
├─ Start: cd trees/<branch-name> && SERVER_PORT=<port> CLIENT_PORT=<port> sh scripts/start-system.sh
├─ Stop: SERVER_PORT=<port> CLIENT_PORT=<port> ./scripts/reset-system.sh
└─ Remove: /remove_worktree <branch-name>
───────────────────────────────────────────────────────────────
[Repeat for each worktree]
═══════════════════════════════════════════════════════════════
💡 Quick Commands:
Create new worktree:
└─ /create_worktree <branch-name> [port-offset]
Remove worktree:
└─ /remove_worktree <branch-name>
Start a stopped worktree:
└─ cd trees/<branch-name> && SERVER_PORT=<port> CLIENT_PORT=<port> sh scripts/start-system.sh &
Stop a running worktree:
└─ lsof -ti :<SERVER_PORT> | xargs kill -9 && lsof -ti :<CLIENT_PORT> | xargs kill -9
View this list again:
└─ /list_worktrees
═══════════════════════════════════════════════════════════════
```
If no worktrees exist in trees/:
```
📊 Git Worktrees Overview
═══════════════════════════════════════════════════════════════
🌳 Main Repository (Default)
📁 Location: <project-root>
🌿 Branch: <current-branch>
🔌 Ports: 4000 (server), 5173 (client)
🎯 Status: <RUNNING|STOPPED>
═══════════════════════════════════════════════════════════════
No worktrees found in trees/ directory
💡 Create your first worktree:
/create_worktree <branch-name>
This will:
• Create isolated git worktree
• Configure unique ports (4010, 5183)
• Install dependencies
• Start services automatically
═══════════════════════════════════════════════════════════════
```
If worktrees have configuration issues:
```
⚠️ Configuration Warnings:
• trees/<branch-name>: Missing .env files
└─ Fix: Recreate with /create_worktree <branch-name>
• trees/<branch-name>: Dependencies not installed
└─ Fix: cd trees/<branch-name>/apps/server && bun install
└─ Fix: cd trees/<branch-name>/apps/client && bun install
• trees/<branch-name>: Services running but ports mismatch
└─ Fix: Stop services and update .env files
```
## Notes
- Main repository is always shown first (uses default ports)
- Worktrees are sorted alphabetically by branch name
- Service status is checked in real-time
- Port conflicts are detected and highlighted
- Orphaned worktrees (in git but not in trees/) are noted
- PIDs are shown for running processes for easy termination
- All commands are copy-paste ready

View File

@@ -0,0 +1,184 @@
---
model: claude-sonnet-4-5-20250929
description: Remove a git worktree, delete its branch, and stop its running services
argument-hint: <branch-name>
allowed-tools: Bash, Read, Glob, Grep
---
# Purpose
Remove an existing git worktree from the `trees/` directory AND delete the associated git branch. This includes stopping any running services on its ports, cleaning up processes, removing the worktree directory, and permanently deleting the branch. This ensures complete cleanup without orphaned processes or files.
## Variables
```
PROJECT_CWD: . (current working directory - the main project root)
BRANCH_NAME: $1 (required)
WORKTREE_DIR: trees/<BRANCH_NAME>
```
## Instructions
- This command safely removes a worktree and all associated resources
- Stops any running server and client processes for the worktree
- Removes the git worktree using git's built-in removal command
- Deletes the git branch associated with the worktree (PERMANENT)
- Validates that the worktree and branch were completely removed
- Provides clear feedback about what was removed and any issues encountered
- If services can't be stopped gracefully, force kills them
- Handles cases where worktree is already partially removed
- WARNING: Both worktree and branch deletion are permanent and cannot be undone
## Workflow
### 1. Parse and Validate Arguments
- Read BRANCH_NAME from $1, error if missing
- Construct WORKTREE_DIR path: `PROJECT_CWD/trees/<BRANCH_NAME>`
- Validate branch name format (no spaces, valid git branch name)
### 2. Check Worktree Existence
- List all worktrees: `git worktree list`
- Check if worktree exists at WORKTREE_DIR
- If worktree doesn't exist:
- Check if directory exists anyway (orphaned directory)
- If directory exists, note it for manual cleanup
- If neither exists, error with message that worktree not found
### 3. Identify Port Configuration
- Check if WORKTREE_DIR/apps/server/.env exists
- If exists, read SERVER_PORT from the file
- Check if WORKTREE_DIR/apps/client/.env exists
- If exists, read VITE_PORT from the file
- If env files don't exist, try to infer ports from worktree count:
- Count existing worktrees in PROJECT_CWD/trees/
- Estimate ports based on typical offset pattern
- Note: This is best-effort if env files are missing
### 4. Stop Running Services
- If SERVER_PORT identified, stop processes on that port:
- Find PIDs: `lsof -ti :<SERVER_PORT>`
- Kill processes: `kill -9 <PIDs>`
- Verify processes stopped
- If VITE_PORT identified, stop processes on that port:
- Find PIDs: `lsof -ti :<VITE_PORT>`
- Kill processes: `kill -9 <PIDs>`
- Verify processes stopped
- Check for any remaining processes in WORKTREE_DIR:
- `ps aux | grep "trees/<BRANCH_NAME>"`
- Kill any orphaned processes
- Wait 2 seconds for processes to fully terminate
### 5. Remove Git Worktree
- Remove worktree using git: `git worktree remove trees/<BRANCH_NAME>`
- If removal fails with error (e.g., worktree has uncommitted changes):
- Try force removal: `git worktree remove trees/<BRANCH_NAME> --force`
- Note the force removal in the report
- Verify worktree was removed: `git worktree list | grep trees/<BRANCH_NAME>`
- Should return nothing if successfully removed
### 6. Clean Up Orphaned Files
- Check if WORKTREE_DIR still exists after git worktree remove
- If directory still exists (shouldn't, but possible with force):
- Note this in warnings
- Do NOT automatically delete with rm -rf (security)
- Provide manual cleanup instructions
- Check for any SQLite WAL files in the removed worktree location
- Check for any lingering lock files
### 7. Delete Git Branch
- After worktree is successfully removed, delete the git branch:
- First try safe delete: `git branch -d <BRANCH_NAME>`
- If safe delete fails (unmerged changes), use force delete: `git branch -D <BRANCH_NAME>`
- Note in report if force delete was used
- Verify branch was deleted: `git branch --list <BRANCH_NAME>`
- Should return nothing if successfully deleted
- Important: This is destructive and permanent
### 8. Validation
- Confirm worktree no longer appears in: `git worktree list`
- Confirm directory no longer exists at WORKTREE_DIR
- Confirm branch no longer exists: `git branch --list <BRANCH_NAME>`
- Confirm no processes running on identified ports
- If any validation fails, include in warnings section
### 9. Report
Follow the Report section format below to provide comprehensive removal information.
## Report
After successful worktree removal, provide a detailed report in the following format:
```
✅ Git Worktree and Branch Removed Successfully!
📁 Worktree Details:
Location: trees/<BRANCH_NAME>
Branch: <BRANCH_NAME>
Status: ❌ REMOVED
🛑 Services Stopped:
✓ Server on port <SERVER_PORT> (if identified)
✓ Client on port <VITE_PORT> (if identified)
✓ All orphaned processes terminated
🗑️ Cleanup:
✓ Git worktree removed
✓ Git branch deleted
✓ Directory removed from trees/
✓ No lingering processes
📝 Important Notes:
• Both the worktree AND branch '<BRANCH_NAME>' have been deleted
• This removal is PERMANENT and cannot be undone
• If you need this branch again, create a new one with: /create_worktree <BRANCH_NAME>
• The new branch will start from your current HEAD
🔍 Verification:
✓ Worktree not in git worktree list
✓ Branch not in git branch list
✓ Directory trees/<BRANCH_NAME> removed
✓ Ports <SERVER_PORT>, <VITE_PORT> are free
```
If any issues occurred during removal, include a warnings section:
```
⚠️ Warnings / Issues:
- Used --force flag to remove worktree (had uncommitted changes)
- Used -D flag to force delete branch (had unmerged changes)
- Port <PORT> could not be identified (no .env file found)
- Processes manually killed: <PID1>, <PID2>
```
If worktree was already partially removed or not found:
```
⚠️ Worktree Status:
- Worktree 'trees/<BRANCH_NAME>' was not found in git worktree list
- Directory may have been manually deleted
- Run 'git worktree prune' to clean up worktree metadata
📝 Cleanup Command:
git worktree prune
```
If orphaned directory exists after removal:
```
⚠️ Manual Cleanup Required:
- Directory trees/<BRANCH_NAME> still exists after git worktree remove
- This should not happen normally
- To manually remove, run from PROJECT_CWD:
rm -rf trees/<BRANCH_NAME>
- Or use the reset script with port variables:
SERVER_PORT=<PORT> CLIENT_PORT=<PORT> ./scripts/reset-system.sh
```