claude-hooks/CONTRIBUTING.md
Ryan Malloy 50fd0266c9 Release v1.0.0: Pure Node.js Claude Hooks with Shadow Learning
🚀 Production-ready release of the intelligent hooks system for Claude Code.

## Key Features
- Pure Node.js implementation (no Python dependencies)
- Shadow learning with pattern recognition and confidence scoring
- Auto-configuration via npm postinstall script
- Comprehensive Diátaxis documentation framework
- End-to-end testing and validation

## Package Distribution
- NPM-ready with global CLI binary
- Auto-configures hooks during installation
- Fail-safe design with graceful degradation
- Complete API reference and development docs

## Release Notes
- CHANGELOG.md with comprehensive v1.0.0 details
- CONTRIBUTING.md with development guidelines
- Updated package.json with distribution metadata
- Ready for npm registry publication

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-20 03:16:13 -06:00

7.9 KiB

Contributing to Claude Hooks

Thank you for your interest in contributing to Claude Hooks! This document provides guidelines for contributing to the project.

🚀 Getting Started

Prerequisites

  • Node.js 16.0.0 or higher
  • npm 8.0.0 or higher
  • Claude Code CLI installed
  • Git for version control

Development Setup

  1. Fork and clone the repository:

    git clone https://git.supported.systems/your-username/claude-hooks.git
    cd claude-hooks
    
  2. Install dependencies:

    npm install
    
  3. Link for local development:

    npm link
    
  4. Run tests:

    npm test
    
  5. Test integration with Claude Code:

    claude-hooks test
    

🏗️ Project Structure

claude-hooks/
├── bin/                    # CLI executable
│   └── claude-hooks.js
├── hooks/                  # Hook implementations
│   ├── context-monitor.js
│   ├── command-validator.js
│   ├── session-logger.js
│   └── session-finalizer.js
├── lib/                    # Core libraries
│   ├── shadow-learner.js
│   ├── backup-manager.js
│   ├── session-state.js
│   └── context-monitor.js
├── config/                 # Configuration templates
├── docs/                   # Diátaxis documentation
└── tests/                  # Test suites

🧪 Testing

Test Levels

  1. Unit Tests - Individual component testing
  2. Integration Tests - Hook pipeline testing
  3. End-to-End Tests - Full Claude Code integration

Running Tests

# All tests
npm test

# Specific test categories
npm run test:unit
npm run test:integration
npm run test:e2e

# Coverage report
npm run test:coverage

Writing Tests

Example hook test:

const { testHook } = require('../tests/test-utils');

describe('CommandValidator', () => {
  it('should block dangerous commands', async () => {
    const input = {
      tool: 'Bash',
      parameters: { command: 'rm -rf /' }
    };
    
    const result = await testHook('command-validator.js', input);
    
    expect(result.allow).toBe(false);
    expect(result.message).toContain('dangerous');
  });
});

📝 Code Style

JavaScript Standards

  • ES2020+ syntax
  • CommonJS modules (for Claude Code compatibility)
  • JSDoc comments for public APIs
  • Async/await for asynchronous operations

Linting and Formatting

# Lint code
npm run lint

# Auto-fix linting issues
npm run lint:fix

# Format code
npm run format

Example Code Style

/**
 * Validates a bash command for safety and provides suggestions
 * @param {Object} input - Hook input data
 * @param {string} input.tool - Tool name (should be 'Bash')
 * @param {Object} input.parameters - Tool parameters
 * @returns {Promise<Object>} Validation result
 */
async function validateCommand(input) {
  const { tool, parameters } = input;
  
  if (tool !== 'Bash') {
    return { allow: true };
  }
  
  const { command } = parameters;
  const dangerousPatterns = [
    /rm\s+-rf\s+\//,
    /mkfs\./
  ];
  
  for (const pattern of dangerousPatterns) {
    if (pattern.test(command)) {
      return {
        allow: false,
        message: '⛔ Command blocked: Dangerous pattern detected'
      };
    }
  }
  
  return { allow: true };
}

🎯 Contribution Types

🐛 Bug Reports

Use the issue template:

**Bug Description:**
Brief description of the bug

**Steps to Reproduce:**
1. Step one
2. Step two
3. Expected vs actual behavior

**Environment:**
- OS: [e.g., macOS 13.0]
- Node.js version: [e.g., 18.17.0]
- Claude Code version: [e.g., 1.2.3]
- claude-hooks version: [e.g., 1.0.0]

**Additional Context:**
Hook logs, error messages, etc.

Feature Requests

Include:

  • Use case: Why is this feature needed?
  • Proposed solution: How should it work?
  • Alternatives considered: Other approaches
  • Breaking changes: Any compatibility concerns

🔧 Code Contributions

Hooks Development

New hooks should:

  • Follow the Hook API Reference
  • Include comprehensive tests
  • Handle errors gracefully
  • Execute within performance requirements (<50ms for PreToolUse)

Shadow Learner Enhancements

When extending the shadow learner:

  • Maintain backward compatibility with existing pattern databases
  • Include confidence scoring for new pattern types
  • Document learning algorithms clearly
  • Test with various failure scenarios

Documentation Improvements

Follow the Diátaxis framework:

  • Tutorials: Learning-oriented, hands-on guidance
  • How-to guides: Goal-oriented, practical steps
  • Reference: Information-oriented, comprehensive details
  • Explanation: Understanding-oriented, theoretical background

🔄 Pull Request Process

Before Submitting

  1. Test thoroughly:

    npm test
    npm run lint
    claude-hooks test
    
  2. Update documentation if needed

  3. Add changelog entry for user-facing changes

  4. Ensure backward compatibility or document breaking changes

PR Guidelines

  1. Clear title: Describe what the PR does
  2. Detailed description:
    • What problem does this solve?
    • How does the solution work?
    • Any breaking changes or migration notes?
  3. Link related issues
  4. Request specific reviewers if needed

Example PR Description

## Summary
Add support for Python virtual environment detection in command validation

## Changes
- Extend shadow learner to detect venv/conda environments
- Update command validator to suggest environment-specific alternatives
- Add tests for virtual environment scenarios

## Testing
- [ ] Unit tests pass
- [ ] Integration tests with venv scenarios
- [ ] Manual testing in conda environment

## Breaking Changes
None - fully backward compatible

Fixes #123

🎯 Development Guidelines

Hook Development

  1. Error Handling: Always fail safely

    try {
      // Hook logic
      return { allow: true, message: 'Success' };
    } catch (error) {
      console.error('Hook error:', error);
      return { allow: true }; // Fail open
    }
    
  2. Performance: Keep hooks fast

    const MAX_EXECUTION_TIME = 50; // ms for PreToolUse
    
  3. Logging: Use structured logging

    console.log(JSON.stringify({
      timestamp: new Date().toISOString(),
      hook: 'command-validator',
      action: 'blocked-command',
      command: sanitizeForLog(command)
    }));
    

Shadow Learner Extensions

  1. Pattern Validation: Ensure patterns are meaningful

    function validatePattern(pattern) {
      return pattern.confidence > 0.1 && 
             pattern.evidence_count > 2 &&
             pattern.last_seen > Date.now() - 30 * 24 * 60 * 60 * 1000;
    }
    
  2. Storage Efficiency: Keep databases compact

    // Prune old patterns periodically
    function pruneOldPatterns(db) {
      const cutoff = Date.now() - 90 * 24 * 60 * 60 * 1000; // 90 days
      return db.filter(pattern => pattern.last_seen > cutoff);
    }
    

🌟 Recognition

Contributors are recognized in:

  • README.md contributors section
  • CHANGELOG.md for significant contributions
  • GitHub releases with contributor highlights

📞 Getting Help

  • Questions: Open a GitHub discussion
  • Bug reports: Create an issue with the bug template
  • Development help: Tag @maintainers in discussions
  • Real-time chat: Join our Discord server (link in README)

🏆 Code of Conduct

This project follows the Contributor Covenant Code of Conduct. Please read and follow these guidelines to ensure a welcoming environment for all contributors.


Thank you for contributing to Claude Hooks! 🎉

Your contributions help make AI assistance more intelligent, reliable, and useful for developers worldwide.