diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..15c7e5a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,88 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## [1.0.0] - 2025-01-20 + +### ✨ Initial Release + +**πŸš€ Core Features:** +- **Shadow Learning System**: Intelligent pattern recognition that learns from command failures and successes +- **Context Monitoring**: Automatic backup triggers based on token usage estimation +- **Command Validation**: Real-time prevention of dangerous operations with smart suggestions +- **Session Continuity**: Persistent state tracking across Claude sessions with LAST_SESSION.md + +**πŸ—οΈ Architecture:** +- **Pure Node.js Implementation**: No Python dependencies, full npm ecosystem integration +- **Event-Driven Hooks**: UserPromptSubmit, PreToolUse, PostToolUse, Stop hook points +- **Auto-Configuration**: Hooks configure themselves during npm install via postinstall script +- **Fail-Safe Design**: All components designed to degrade gracefully without blocking Claude + +**πŸ“š Documentation:** +- **DiΓ‘taxis Framework**: Complete tutorial, how-to guides, reference docs, and explanations +- **Bootstrap Installation**: Self-installing prompt for Claude Code integration +- **API Reference**: Comprehensive hook development documentation + +**πŸ”§ CLI Tools:** +- `claude-hooks status` - System status and session information +- `claude-hooks test` - Comprehensive hook validation +- `claude-hooks backup` - Manual backup creation +- `claude-hooks patterns` - View learned intelligence patterns + +**πŸ’‘ Intelligence Features:** +- **Pattern Matching**: Learns which commands work/fail in your environment +- **Confidence Scoring**: Weighs suggestions based on evidence strength +- **Context Awareness**: Adapts behavior based on project type and history +- **Fuzzy Command Matching**: Handles variations and partial command matches + +**πŸ›‘οΈ Safety Features:** +- **Dangerous Command Detection**: Blocks destructive operations automatically +- **Path Validation**: Prevents access to system files and path traversal +- **Circuit Breaker Pattern**: Auto-disables problematic hooks after failures +- **Input Sanitization**: Comprehensive validation of all hook inputs/outputs + +### πŸ”„ Migration Notes + +This is the initial stable release. Future versions will maintain backward compatibility for: +- Hook configuration files +- Learned pattern databases +- Session state format +- CLI command interface + +### 🎯 Installation + +**NPM (Recommended):** +```bash +npm install -g claude-hooks +``` + +**Git Clone:** +```bash +git clone https://git.supported.systems/rsp2k/claude-hooks.git +cd claude-hooks +npm install +npm link +``` + +### πŸƒ Quick Start + +After installation, hooks auto-configure. Test with: +```bash +claude-hooks test +``` + +Then restart Claude Code to activate the intelligent assistance. + +### 🀝 Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and contribution guidelines. + +### πŸ“„ License + +MIT License - see [LICENSE](LICENSE) for details. + +--- + +**πŸŽ‰ Welcome to Claude Code with Intelligence!** + +Your AI assistant now learns from every interaction, prevents common mistakes, and automatically protects your work. The more you use it, the smarter it gets. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..52a8f3a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,342 @@ +# 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:** + ```bash + git clone https://git.supported.systems/your-username/claude-hooks.git + cd claude-hooks + ``` + +2. **Install dependencies:** + ```bash + npm install + ``` + +3. **Link for local development:** + ```bash + npm link + ``` + +4. **Run tests:** + ```bash + npm test + ``` + +5. **Test integration with Claude Code:** + ```bash + 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 + +```bash +# 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: +```javascript +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 + +```bash +# Lint code +npm run lint + +# Auto-fix linting issues +npm run lint:fix + +# Format code +npm run format +``` + +### Example Code Style + +```javascript +/** + * 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} 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: +```markdown +**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](docs/reference/hook-api.md) +- 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](https://diataxis.fr/): +- **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:** + ```bash + 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 + +```markdown +## 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 + ```javascript + 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 + ```javascript + const MAX_EXECUTION_TIME = 50; // ms for PreToolUse + ``` + +3. **Logging**: Use structured logging + ```javascript + 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 + ```javascript + 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 + ```javascript + // 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](CODE_OF_CONDUCT.md). 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. \ No newline at end of file diff --git a/package.json b/package.json index 71bce0b..73151e5 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,10 @@ "lib/", "config/", "docs/", - "README.md" + "README.md", + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE" ], "scripts": { "postinstall": "node bin/claude-hooks.js init --auto-setup",