An open API service indexing awesome lists of open source software.

https://github.com/thedaviddias/codekeeper

๐Ÿง  Essential guardrails to prevent AI from going sideways in development projects
https://github.com/thedaviddias/codekeeper

ai ai-gents eslint guardrails lefthook llms vibe-coding vibecoding

Last synced: about 1 month ago
JSON representation

๐Ÿง  Essential guardrails to prevent AI from going sideways in development projects

Awesome Lists containing this project

README

          

# CodeKeeper - AI Development Guardrails

**Stop AI from breaking your React/Next.js code. Start shipping with confidence.**

[![Tests](https://github.com/thedaviddias/codekeeper/workflows/Test%20CodeKeeper%20Validation%20Scripts/badge.svg)](https://github.com/thedaviddias/codekeeper/actions)
[![GitHub Stars](https://img.shields.io/github/stars/thedaviddias/codekeeper?style=social)](https://github.com/thedaviddias/codekeeper)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/thedaviddias/codekeeper/pulls)
[![React](https://img.shields.io/badge/React-18+-blue)](https://reactjs.org/)
[![Next.js](https://img.shields.io/badge/Next.js-13+-black)](https://nextjs.org/)

[Quick Start](#-quick-start-2-minutes) โ€ข [Documentation](./docs/) โ€ข [Examples](./docs/EXAMPLES.md) โ€ข [Contributing](#-contributing)

---

**CodeKeeper** is a battle-tested (yes, I'm using it in production) collection of validation scripts that prevent AI assistants from introducing bugs, security issues, and bad practices into your React and Next.js projects. Works with **any** development workflow you're already using.

### ๐Ÿ› ๏ธ **Works With Your Existing Tools**
โœ… **ESLint** โ€ข โœ… **Husky** โ€ข โœ… **Lefthook** โ€ข โœ… **pre-commit** โ€ข โœ… **lint-staged** โ€ข โœ… **GitHub Actions** โ€ข โœ… **GitLab CI** โ€ข โœ… **Jenkins** โ€ข โœ… **Vercel** โ€ข โœ… **Netlify**

## ๐Ÿšจ The Problem

AI coding assistants are powerful but can introduce subtle bugs in React/Next.js projects:
- **Type assertions** that hide runtime errors (`as any` everywhere)
- **Barrel files** that destroy tree-shaking and slow builds
- **Component mega-files** with 500+ lines that become unmaintainable
- **Missing JSDoc** that leaves your team confused about props and hooks
- **Security vulnerabilities** from unsafe patterns and exposed secrets

## โœ… The Solution

CodeKeeper provides pre-built validation scripts that catch these issues before they hit production:

| Guardrail | Prevents | Impact |
|-----------|----------|---------|
| **Type Safety** | `as any`, unsafe casts | -90% runtime errors |
| **Import Quality** | Barrel file chaos | 3x faster builds |
| **Complexity Limits** | 1000+ line files | 50% easier maintenance |
| **Documentation** | Missing JSDoc | 2x faster onboarding |
| **Architecture** | Messy file structure | Clean, scalable codebase |

## ๐Ÿš€ Quick Start (Choose Your Tools)

### Option A: Lefthook + Validation Scripts (Recommended for Flow State)
```bash
# Install lefthook
npm install -g lefthook

# Copy CodeKeeper scripts and config
curl -fsSL https://raw.githubusercontent.com/thedaviddias/codekeeper/main/install.sh | bash

# Auto-configured! lefthook.yml is ready to use
lefthook install

# Now code freely - validation happens on commit! ๐ŸŽ‰
```

### Option B: Other Git Hook Managers

Pick your favorite:

#### With Husky (Most Popular)
```bash
# Install husky and lint-staged
npm install --save-dev husky lint-staged
npx husky-init

# Copy CodeKeeper scripts
curl -fsSL https://raw.githubusercontent.com/thedaviddias/codekeeper/main/install.sh | bash

# Add to package.json
{
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"node scripts/validate-all.js"
]
}
}

# Update .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
```

#### With Lefthook (My Favorite and the one I use)
```bash
# Install lefthook
npm install -g lefthook

# Copy CodeKeeper scripts and config
curl -fsSL https://raw.githubusercontent.com/thedaviddias/codekeeper/main/install.sh | bash

# Auto-configured! lefthook.yml is ready to use
lefthook install
```

#### With pre-commit (Python)
```yaml
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: codekeeper-validation
name: CodeKeeper Validation
entry: node scripts/validate-all.js
language: node
files: \.(ts|tsx)$
```

## ๐Ÿ’ก Real Examples

### Before CodeKeeper โŒ
```tsx
// AI often generates this in React components
const UserProfile = ({ data }: any) => {
const user = data as any; // Runtime bomb!
return

{user.naem.toUpperCase()}
; // Typo crashes in production
}
```

### After CodeKeeper โœ…
```tsx
// Guardrails force proper typing
interface UserProfileProps {
data: User;
}

const UserProfile = ({ data }: UserProfileProps) => {
return

{data.name.toUpperCase()}
; // TypeScript catches typos
}
```

### More Examples:
- **[Try interactive examples โ†’](./examples/)** - Working projects you can test immediately
- **[See all React/Next.js examples โ†’](./docs/EXAMPLES.md)**

## ๐Ÿ”ง What's Included

### ESLint Plugin Rules
- `no-unsafe-as-casts` - Blocks `as any` and unsafe type assertions
- `no-barrel-files` - Prevents slow barrel file exports
- `max-file-complexity` - Limits file size and complexity
- `require-jsdoc` - Enforces documentation standards

### Standalone Validation Scripts
- `check-as-casts.js` - TypeScript type safety validation
- `check-barrel-files.js` - Import performance checks
- `check-directory-structure.js` - Architecture enforcement
- `check-file-complexity.js` - Complexity limits
- `check-jsdoc.js` - Documentation requirements
- `check-relative-imports.js` - Import consistency

### Configuration
- `lefthook.yml` - Git hooks for automatic validation
- `.eslintrc.js` - ESLint integration examples

## ๐ŸŽฏ The "Vibe Coding" Workflow

CodeKeeper is designed for developers who want to **code in flow state** without constant interruptions:

1. **๐Ÿš€ Code freely** - Focus on building features, don't worry about perfect code
2. **โšก Quick validation** - Let Lefthook catch issues with specific, educational messages on commit
3. **๐Ÿค– AI-assisted fixes** - Use LLMs (like Claude, ChatGPT) to fix the issues CodeKeeper found
4. **โœ… Ship with confidence** - Your code is clean and follows best practices

This approach lets you stay in creative flow while ensuring code quality.

### ๐Ÿค– AI-Assisted Fixing Example

When CodeKeeper finds issues, copy them to your AI assistant:

```bash
git commit -m "add user profile feature"
# ๐Ÿ” Checking for unsafe 'any' types...
# โŒ COMMIT BLOCKED: Found 'any' types in UserProfile.tsx!
# ๐Ÿ’ก Replace 'any' with specific types for better type safety

# ๐Ÿ” Checking React component complexity...
# โŒ COMMIT BLOCKED: Components exceed complexity limits!
# ๐Ÿ’ก Split large components into smaller, focused ones
```

**Prompt to AI:** "Fix these CodeKeeper issues: [paste output]"

**AI Response:** Provides proper TypeScript interfaces, splits complex components, and removes barrel files.

**Result:** Clean, maintainable code without breaking your flow state!

## ๐Ÿ”„ CI/CD Integration

CodeKeeper works with any CI/CD pipeline:

### GitHub Actions
```yaml
# .github/workflows/validation.yml
name: CodeKeeper Validation
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '18'
- run: npm install
- run: npm run lint # ESLint + CodeKeeper plugin
- run: node scripts/validate-all.js # Standalone validation
```

### GitLab CI
```yaml
# .gitlab-ci.yml
stages:
- validate

code-validation:
stage: validate
script:
- npm install
- npm run lint
- node scripts/validate-all.js
only:
- merge_requests
- main
```

### Jenkins
```groovy
// Jenkinsfile
pipeline {
agent any
stages {
stage('Install') {
steps {
sh 'npm install'
}
}
stage('Validate') {
steps {
sh 'npm run lint'
sh 'node scripts/validate-all.js'
}
}
}
}
```

### Vercel/Netlify Build
```json
// package.json
{
"scripts": {
"build": "npm run validate && next build",
"validate": "eslint . && node scripts/validate-all.js"
}
}
```

## ๐Ÿ”Œ Tool Compatibility Matrix

| Tool | ESLint Plugin | Standalone Scripts | Setup Difficulty | Performance |
|------|--------------|-------------------|------------------|-------------|
| **ESLint** | โœ… Native | โœ… Via npm scripts | ๐ŸŸข Easy | ๐ŸŸข Fast |
| **Husky + lint-staged** | โœ… Perfect fit | โœ… Perfect fit | ๐ŸŸข Easy | ๐ŸŸข Fast |
| **Lefthook** | โœ… Works great | โœ… Built-in support | ๐ŸŸข Easy | ๐ŸŸข Fast |
| **pre-commit** | โœ… Via ESLint hook | โœ… Custom hook | ๐ŸŸก Moderate | ๐ŸŸข Fast |
| **GitHub Actions** | โœ… Standard workflow | โœ… Custom step | ๐ŸŸข Easy | ๐ŸŸข Fast |
| **GitLab CI** | โœ… Standard job | โœ… Custom job | ๐ŸŸข Easy | ๐ŸŸข Fast |
| **VS Code** | โœ… Real-time errors | โŒ Terminal only | ๐ŸŸข Easy | ๐ŸŸข Instant |
| **WebStorm/IntelliJ** | โœ… Built-in support | โš ๏ธ Terminal integration | ๐ŸŸข Easy | ๐ŸŸก Good |

**๐ŸŽฏ Quick Recommendations:**
- **Love flow state coding?** โ†’ Lefthook + CodeKeeper scripts (our favorite!)
- **Already use Husky?** โ†’ Add CodeKeeper to your lint-staged config
- **Team uses ESLint heavily?** โ†’ ESLint plugin for real-time feedback
- **Want maximum speed?** โ†’ Lefthook's parallel execution wins

## ๐Ÿš€ Installation

### Prerequisites

- **Node.js**: Version 18.0.0 or higher (check with `node --version`)
- **npm**: Version 8.0.0 or higher
- Use the recommended version from `.nvmrc` for best compatibility:
```bash
nvm use # If you have nvm installed
# or check the recommended version
cat .nvmrc
```

1. **Verify Node.js compatibility**:
```bash
npm run check:node
```

2. **Install lefthook** (if not already installed):
```bash
npm install -g lefthook
# or
yarn global add lefthook
```

3. **Copy the files**:
```bash
# Copy validation scripts
mkdir -p scripts/validation
cp scripts/validation/*.js scripts/validation/

# Copy lefthook config
cp lefthook.yml ./
```

4. **Install lefthook in your repo**:
```bash
lefthook install
```

## ๐ŸŽฏ What Each Guardrail Does

### Type Safety (`check-as-casts.js`)
- **Blocks**: `as any`, `as unknown`, unsafe type assertions
- **Allows**: `as const`, test files, migration scripts
- **Why**: Prevents runtime type errors and maintains type safety

### Import Quality (`check-barrel-files.js`)
- **Blocks**: Barrel files (`index.ts` that re-exports everything)
- **Enforces**: Explicit imports from specific files
- **Why**: Better tree-shaking, faster builds, clearer dependencies

### Architecture (`check-directory-structure.js`)
- **Enforces**: Clean, domain-driven directory structure
- **Prevents**: Messy file organization and anti-patterns
- **Why**: Maintainable codebase and clear separation of concerns

### Complexity (`check-file-complexity.js`)
- **Limits**: File size, function count, nesting depth
- **Suggests**: Refactoring when limits are exceeded
- **Why**: Prevents unmaintainable code and cognitive overload

### Documentation (`check-jsdoc.js`)
- **Requires**: JSDoc comments on functions and components
- **Enforces**: Parameter and return type documentation
- **Why**: Better code understanding and AI assistance

### Import Patterns (`check-relative-imports.js`)
- **Enforces**: Consistent import aliases (`@/` instead of `../`)
- **Prevents**: Deep relative imports that break on refactoring
- **Why**: Maintainable import paths and easier refactoring

## ๐Ÿ“š Documentation

For detailed guides and examples, check out the [documentation](./docs/):

- **[Quick Start Guide](./docs/QUICK-START.md)** - Get up and running in 5 minutes
- **[Why Guardrails Matter](./docs/WHY-GUARDRAILS.md)** - The reasoning behind each guardrail
- **[Real Examples](./docs/EXAMPLES.md)** - Before/after scenarios with AI-generated code

## ๐Ÿ”ง Customization

### Adjust Limits
Edit the constants in each validation script:

```javascript
// In check-file-complexity.js
const COMPLEXITY_LIMITS = {
lines: 500, // Max lines per file
functions: 15, // Max functions per file
dependencies: 20, // Max import statements
nestingDepth: 10, // Max nesting depth
}
```

### Add Exclusions
Modify the exclusion patterns in each script:

```javascript
// In check-as-casts.js
const ALLOWED_PATTERNS = [
/\bas\s+const\b/g,
/\.test\.(ts|tsx)$/,
/\.spec\.(ts|tsx)$/,
// Add your own patterns here
]
```

### Skip Checks Temporarily
Use environment variables to skip checks during development:

```bash
NODE_ENV=development git commit -m "WIP"
```

## ๐ŸŽฏ Best Practices

1. **Start Strict**: Begin with all guardrails enabled, this will avoid you nightmarish debugging sessions.
2. **Customize Gradually**: Adjust limits based on your team's needs, you can start with the defaults and then adjust them to your needs.
3. **Document Exceptions**: Add comments when you need to bypass rules, this will help you and your team to understand the reasons behind the exceptions.
4. **Review Regularly**: Update guardrails as your project evolves, this will help you to keep your codebase clean and maintainable.
5. **Team Alignment**: Ensure everyone understands the rules and their benefits, this will help you to have a more consistent codebase.

## ๐Ÿšจ Common Issues & Solutions

### "Too many violations to fix all at once"
- Temporarily increase limits in the scripts
- Fix violations incrementally
- Use `NODE_ENV=development` to bypass checks temporarily

### "Some files need exceptions"
- Add specific patterns to the `ALLOWED_PATTERNS` arrays
- Use file-specific exclusions in the validation logic
- Document why exceptions are needed

### "Checks are too slow"
- Optimize the validation scripts
- Add more specific file filters
- Consider running some checks only on pre-push

## ๐ŸŒŸ Who's Using CodeKeeper?




Your Company


Your Company?


[Add your company](https://github.com/thedaviddias/codekeeper/issues/new?title=Add%20my%20company)

## ๐Ÿงช Testing Your Setup

Ensure your CodeKeeper rules work correctly:

```bash
# Test all validation scripts
npm test

# Quick development check
node tests/quick-test.js

# Test individual validators
npm run test:as-casts
npm run test:barrel-files
npm run test:relative-imports
```

The test suite includes fixtures with known violations to verify each guardrail catches what it should. See [`tests/README.md`](./tests/README.md) for details.

## ๐Ÿค Contributing

We welcome contributions! Whether it's:
- ๐Ÿ› Bug fixes
- โœจ New guardrail types
- ๐Ÿ“š Documentation improvements
- ๐ŸŒ Translations
- ๐Ÿ’ก Feature ideas

**Before submitting changes:**
1. Run tests to ensure everything works: `npm test`
2. Add test fixtures for new validation rules
3. Update documentation if needed

### ๐Ÿ“š Contributing Resources

- [Contributing Guide](./CONTRIBUTING.md) - General contribution guidelines
- [Adding New Validation Rules](./docs/CONTRIBUTING-NEW-RULES.md) - Comprehensive step-by-step guide for adding new rules
- [Examples](./docs/EXAMPLES.md) - Usage examples and patterns

## ๐Ÿ“Š Stats & Community

- ๐ŸŒŸ **0+ GitHub Stars** - [Star us!](https://github.com/thedaviddias/codekeeper)
- ๐Ÿ‘ฅ **0+ Contributors** - [Join us!](https://github.com/thedaviddias/codekeeper/graphs/contributors)
- ๐Ÿข **0+ Companies** using in production
- ๐Ÿ’ฌ **[Discussions](https://github.com/thedaviddias/codekeeper/discussions)** - Ask questions, share ideas
- ๐Ÿฆ **[Follow updates](https://twitter.com/thedaviddias)** - Latest features and tips

## ๐Ÿ“„ License

MIT License - feel free to use these guardrails in any project!

## ๐Ÿ™ Acknowledgments

Created by [David Dias](https://github.com/thedaviddias), author of [Front-End Checklist](https://github.com/thedaviddias/Front-End-Checklist) (75k+ stars).

Inspired by the need to maintain code quality when working with AI assistants. These guardrails help ensure that AI-generated code meets the same standards as human-written code.

---

**โญ Star this repo** if it helped you ship better code with AI!

[Report Bug](https://github.com/thedaviddias/codekeeper/issues) โ€ข [Request Feature](https://github.com/thedaviddias/codekeeper/issues) โ€ข [Join Discord](#)