VDK Docs
CLI

Watch Mode

CLI watch mode documentation

Watch Mode

Watch mode enables continuous monitoring of your project for changes, automatically updating VDK rules and IDE integrations in real-time as you develop. This ensures your AI assistant always has the most current understanding of your project.

Overview

Watch mode provides:

  • Real-time Updates: Automatic rule regeneration when files change
  • IDE Synchronization: Live updates to IDE integrations
  • Incremental Analysis: Efficient processing of only changed files
  • Background Operation: Non-intrusive monitoring while you code
  • Team Collaboration: Automatic rule sharing with team members

Enabling Watch Mode

Basic Watch Mode

# Enable watch mode during initialization
vdk init --watch

# Start watch mode on existing project
vdk watch

# Watch with specific IDE integration
vdk init --claude-code --watch

Advanced Watch Configuration

# Watch with custom patterns
vdk watch \
  --ignorePattern "**/node_modules/**" \
  --ignorePattern "**/dist/**" \
  --includePattern "src/**/*.{ts,tsx}"

# Watch with specific output
vdk watch --outputPath ./custom-rules

# Watch with verbose logging
vdk watch --verbose

# Watch with debouncing
vdk watch --debounce 5000  # 5 second delay

Watch Mode Configuration

Configuration File

Add watch settings to vdk.config.json:

{
  "watch": {
    "enabled": false,
    "debounceMs": 2000,
    "ignorePatterns": [
      "**/node_modules/**",
      "**/dist/**", 
      "**/build/**",
      "**/.git/**",
      "**/coverage/**",
      "**/*.log"
    ],
    "includePatterns": [
      "src/**/*.{ts,tsx,js,jsx}",
      "app/**/*.{ts,tsx}",
      "components/**/*.{ts,tsx}",
      "lib/**/*.ts",
      "package.json",
      "tsconfig.json"
    ],
    "triggers": {
      "fileChanges": true,
      "packageJsonChanges": true,
      "configChanges": true,
      "dependencyChanges": true
    },
    "actions": {
      "regenerateRules": true,
      "updateIDEMemory": true,
      "validateRules": true,
      "syncWithHub": false
    },
    "integrations": {
      "claude-code": {
        "enabled": true,
        "updateMemory": true,
        "reloadCommands": false
      },
      "cursor": {
        "enabled": true,
        "updateRules": true,
        "refreshEditor": false
      }
    }
  }
}

Environment Variables

Control watch mode behavior:

# Enable watch mode globally
export VDK_WATCH_ENABLED=true

# Set debounce delay (milliseconds)
export VDK_WATCH_DEBOUNCE=3000

# Enable debug logging for watch mode
export VDK_DEBUG_WATCH=true

# Disable specific watchers
export VDK_WATCH_DISABLE_FILE_WATCHER=false
export VDK_WATCH_DISABLE_PACKAGE_WATCHER=false

# Set memory limits for watch mode
export VDK_WATCH_MEMORY_LIMIT=512

How Watch Mode Works

File System Monitoring

Watch mode uses efficient file system watchers to monitor changes:

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   File System   │    │   VDK Watcher    │    │   Actions       │
│                 │    │                  │    │                 │
│  File Changed   │───▶│  Debounce        │───▶│  Regenerate     │
│  Created        │    │  Filter          │    │  Rules          │
│  Deleted        │    │  Analyze         │    │  Update IDE     │
│  Modified       │    │  Queue           │    │  Validate       │
└─────────────────┘    └──────────────────┘    └─────────────────┘

Change Detection

VDK monitors different types of changes:

1. Source Code Changes

// When you modify a component
export default function UserCard({ user }: UserCardProps) {
  // Added new prop
  const handleEdit = () => console.log('Edit user');
  
  return (
    <div className="user-card">
      <h3>{user.name}</h3>
      <button onClick={handleEdit}>Edit</button> {/* New feature */}
    </div>
  );
}

// Watch mode detects:
// - New event handler pattern
// - Updated component structure
// - New interaction patterns

2. Dependency Changes

// package.json changes
{
  "dependencies": {
    "react": "^18.2.0",
    "@tanstack/react-query": "^4.0.0"  // New dependency
  }
}

// Watch mode detects:
// - New library added
// - Updates available patterns
// - Regenerates rules with new capabilities

3. Configuration Changes

// tsconfig.json changes
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true  // New compiler option
  }
}

// Watch mode detects:
// - TypeScript configuration changes
// - Updates coding standards
// - Adjusts rule strictness

4. Project Structure Changes

src/
├── components/
├── hooks/           # New directory
│   ├── useAuth.ts   # New custom hook
│   └── useApi.ts    # New custom hook
└── utils/

Watch Mode Features

Incremental Analysis

Watch mode performs efficient incremental analysis:

# Only analyze changed files
Modified files: src/components/UserCard.tsx, src/hooks/useAuth.ts
Analyzing 2 files instead of 247 total files
Generated updates in 0.8s instead of 15.2s

Intelligent Debouncing

Prevents excessive updates during rapid changes:

// Multiple rapid changes
12:34:01 - UserCard.tsx modified
12:34:01 - UserCard.tsx modified (debounced)
12:34:02 - UserCard.tsx modified (debounced)
12:34:05 - Processing changes... (after 3s debounce)

Change Classification

Different types of changes trigger different actions:

{
  "changeTypes": {
    "minor": {
      "description": "Small code changes, formatting",
      "action": "update_rules_only",
      "examples": ["variable rename", "comment changes"]
    },
    "moderate": {
      "description": "New functions, components, patterns",
      "action": "regenerate_rules_and_update_ide",
      "examples": ["new component", "new hook", "API changes"]
    },
    "major": {
      "description": "Architecture changes, new dependencies",
      "action": "full_analysis_and_sync",
      "examples": ["new framework", "architecture refactor"]
    }
  }
}

IDE Integration in Watch Mode

Claude Code Integration

# Watch mode automatically updates Claude Code memory
File changed: src/components/NewComponent.tsx
 Analyzing changes...
 Updating CLAUDE.md with new patterns
 Refreshing Claude Code context
 Claude Code updated with new component patterns

Generated Update:

# Project Memory Update

## Recent Changes (Auto-detected)
*Last updated: 2024-01-15 14:23:15*

### New Component Pattern Detected
- **File**: `src/components/NewComponent.tsx`
- **Pattern**: Modal component with portal usage
- **Integration**: Uses our custom `useModal` hook
- **Styling**: Follows Tailwind CSS conventions

### Updated Guidelines
When creating modal components:
1. Use the `useModal` hook for state management
2. Implement portal rendering for proper z-index
3. Include proper focus management
4. Add escape key handling

Cursor Integration

# Watch mode updates Cursor MDC files
File changed: src/api/users.ts
 Detecting API route patterns...
 Updating .cursor/rules/api-patterns.mdc
 Notifying Cursor of rule changes
 Cursor rules updated with new API patterns

Generated Update:

---
title: "API Patterns - Updated"
version: "1.1.0"
updated: "2024-01-15T14:23:15Z"
---

# API Route Patterns

<cursor:patterns>
## New Authentication Pattern Detected

```typescript
// Updated pattern for protected API routes
export async function GET(request: NextRequest) {
  const session = await getServerSession(authOptions);
  
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  
  // Protected route logic
}

Multi-IDE Synchronization

Watch mode can update multiple IDEs simultaneously:

# Configuration for multi-IDE watch
{
  "watch": {
    "integrations": {
      "claude-code": {
        "enabled": true,
        "priority": "high",
        "updateMemory": true
      },
      "cursor": {
        "enabled": true,
        "priority": "medium", 
        "updateRules": true
      },
      "windsurf": {
        "enabled": false,
        "priority": "low"
      }
    }
  }
}

Performance Optimization

Memory Management

Watch mode includes memory optimization:

# Memory usage monitoring
Watch Mode Stats:
- File watchers: 15 active
- Memory usage: 125MB / 512MB limit
- Processed changes: 1,247
- Average processing time: 1.2s
- Cache hit rate: 78%

Efficient File Monitoring

// Optimized file watching strategy
{
  "fileWatcher": {
    "strategy": "native",           // Use OS-native watchers
    "recursive": true,              // Monitor subdirectories
    "followSymlinks": false,        // Don't follow symlinks
    "binaryFiles": false,          // Skip binary files
    "maxFiles": 10000,             // File limit
    "excludeHidden": true          // Skip hidden files
  }
}

Batch Processing

Changes are batched for efficiency:

# Batch processing example
14:23:01 - UserCard.tsx changed (queued)
14:23:02 - UserProfile.tsx changed (queued)
14:23:03 - user-types.ts changed (queued)
14:23:05 - Processing batch of 3 changes...
14:23:06 - Batch completed in 1.1s

Watch Mode Commands

Starting Watch Mode

# Basic watch mode
vdk watch

# Watch with specific configuration
vdk watch --config ./watch-config.json

# Watch specific directory
vdk watch --projectPath ./src

# Watch with custom debounce
vdk watch --debounce 5000

Managing Watch Mode

# Check watch status
vdk watch status

# Pause watch mode
vdk watch pause

# Resume watch mode
vdk watch resume

# Stop watch mode
vdk watch stop

# Restart watch mode
vdk watch restart

Watch Mode Diagnostics

# View watch statistics
vdk watch stats

# Show active watchers
vdk watch list

# Debug watch mode
VDK_DEBUG_WATCH=true vdk watch

# Test watch responsiveness
vdk watch test

Team Collaboration with Watch Mode

Shared Watch Configuration

// .vdk/team-watch.json
{
  "team": "frontend-team",
  "shared": {
    "patterns": ["src/**/*.{ts,tsx}"],
    "rules": ["react-patterns", "typescript-conventions"],
    "autoSync": true,
    "notifications": {
      "onMajorChanges": true,
      "onNewPatterns": true,
      "onRuleUpdates": false
    }
  }
}

Automatic Team Synchronization

# Enable team sync in watch mode
vdk watch --team frontend-team --auto-sync

# Watch mode automatically:
# 1. Detects significant changes
# 2. Updates local rules
# 3. Deploys to team hub
# 4. Notifies team members

Troubleshooting Watch Mode

Common Issues

High CPU Usage:

# Reduce file monitoring scope
vdk watch --ignorePattern "**/node_modules/**" "**/dist/**" "**/*.log"

# Increase debounce time
vdk watch --debounce 10000

# Check active watchers
vdk watch list

Memory Leaks:

# Set memory limits
export VDK_WATCH_MEMORY_LIMIT=256

# Restart watch mode periodically
vdk watch restart

# Monitor memory usage
vdk watch stats --memory

Missing Updates:

# Check file permissions
ls -la src/

# Verify watch patterns
vdk watch test --file src/components/Test.tsx

# Debug file watcher
VDK_DEBUG_WATCH=true vdk watch

Debug Mode

Enable comprehensive watch mode debugging:

# Full debug mode
export VDK_DEBUG_WATCH=true
export VDK_WATCH_VERBOSE=true
vdk watch

# Component-specific debugging
export VDK_DEBUG_WATCH_FILES=true      # File system events
export VDK_DEBUG_WATCH_CHANGES=true    # Change detection
export VDK_DEBUG_WATCH_PROCESSING=true # Processing pipeline
export VDK_DEBUG_WATCH_IDE=true        # IDE integration

Advanced Configuration

Custom Change Handlers

// .vdk/watch-handlers.js
module.exports = {
  handlers: {
    'package.json': async (change) => {
      // Custom handler for package.json changes
      console.log('Dependencies updated, running deep analysis...');
      await vdk.init({ deep: true, overwrite: true });
    },
    'src/types/*.ts': async (change) => {
      // Custom handler for type definition changes
      console.log('Type definitions updated, refreshing IDE...');
      await vdk.updateIDEMemory();
    }
  }
};

Integration with Build Tools

// Integration with webpack/vite
const VDKWatchPlugin = require('@vdk/watch-plugin');

module.exports = {
  plugins: [
    new VDKWatchPlugin({
      enabled: process.env.NODE_ENV === 'development',
      debounce: 2000,
      updateIDE: true
    })
  ]
};

Git Integration

# Git hooks integration
cat > .git/hooks/post-merge << 'EOF'
#!/bin/sh
# Update VDK rules after git merge
if [ -f "package.json" ]; then
  vdk init --overwrite
fi
EOF

chmod +x .git/hooks/post-merge

Best Practices

1. Configure Appropriate Debouncing

# For active development (faster feedback)
vdk watch --debounce 1000

# For large projects (reduce noise)
vdk watch --debounce 5000

# For CI/CD environments (disabled)
vdk watch --debounce 0 --disabled

2. Use Specific Include/Exclude Patterns

{
  "watch": {
    "includePatterns": [
      "src/**/*.{ts,tsx}",        // Source files only
      "package.json",             // Dependencies
      "tsconfig.json"             // TypeScript config
    ],
    "ignorePatterns": [
      "**/node_modules/**",       // Dependencies
      "**/dist/**",               // Build output
      "**/*.test.{ts,tsx}",       // Test files
      "**/*.log"                  // Log files
    ]
  }
}

3. Monitor Performance

# Regular performance checks
vdk watch stats
vdk watch --memory-limit 256

# Profile watch mode performance
VDK_PROFILE_WATCH=true vdk watch

4. Team Coordination

# Coordinate watch mode across team
vdk config set watch.team frontend-team
vdk config set watch.autoSync true
vdk config set watch.notifications.onMajorChanges true

Next Steps