npm package: @hatem427/code-guard-ci
Description: Production-ready TypeScript tooling to enforce PR & coding guidelines for Angular, React, NextJS, NestJS, Fastify, Hono, and Node.js projects.
Author: Hatem Bassem
Latest version: 3.6.4

# 🛡️ Code Guardian — Complete Documentation

> **Version:** 3.6.0  
> **Package:** `@hatem427/code-guard-ci`  
> **Author:** Hatem Bassem  
> **License:** MIT

---

## 📦 Installation

```bash
npm i @hatem427/code-guard-ci
```

Then initialize your project:

```bash
npx code-guard init
```

---

> ⚠️ **IMPORTANT — Updating the Package**
>
> When a new version is available, **do NOT just run `npm update`**.
> You must follow this order to avoid config conflicts:
>
> ```bash
> # 1. Uninstall (removes all generated files cleanly)
> npx code-guard uninstall
>
> # 2. Install the latest version
> npm i @hatem427/code-guard-ci@latest
>
> # 3. Re-initialize
> npx code-guard init
> ```
>
> Skipping the uninstall step may leave stale configs that conflict with the new version.

---

## Table of Contents

1. [What is Code Guardian?](#1-what-is-code-guardian)
2. [Why Use It?](#2-why-use-it)
3. [How to Install & Set Up](#3-how-to-install--set-up)
4. [How It Works — Architecture](#4-how-it-works--architecture)
5. [All Rules Reference](#5-all-rules-reference)
6. [CLI Commands](#6-cli-commands)
7. [Configuration Files Generated](#7-configuration-files-generated)
8. [Pre-commit Hook Flow](#8-pre-commit-hook-flow)
9. [Bypass System & Security](#9-bypass-system--security)
10. [Custom Rules](#10-custom-rules)
11. [AI Assistant Integration](#11-ai-assistant-integration)
12. [Framework Support](#12-framework-support)
13. [Expected Behavior & What to Expect](#13-expected-behavior--what-to-expect)
14. [Troubleshooting](#14-troubleshooting)

---

## 1. What is Code Guardian?

**Code Guardian** is an enterprise-grade code quality enforcement system packaged as an npm package (`@hatem427/code-guard-ci`). It automatically configures and enforces coding standards across your frontend projects through:

- **Pre-commit hooks** — Blocks bad code before it enters the repository
- **Custom rule engine** — 50+ built-in rules with framework-specific checks
- **Auto-configuration** — Zero-prompt setup of ESLint, Prettier, TypeScript, Husky, lint-staged, EditorConfig, and VS Code settings
- **AI assistant configs** — Generates coding rules for Cursor, GitHub Copilot, Antigravity, Windsurf, and Aider
- **Bypass audit system** — Password-protected bypass with full audit logging (local storage)
- **Documentation generation** — Auto-generates feature docs and PR checklists

### Who is it for?

- **Team leads** who want to enforce consistent coding standards
- **Solo developers** who want professional-grade tooling out of the box
- **Companies** standardizing code quality across multiple projects

---

## 2. Why Use It?

| Problem                               | Code Guardian Solution                                |
| ------------------------------------- | ----------------------------------------------------- |
| Developers skip ESLint/Prettier setup | Auto-configures everything in one command             |
| Inconsistent code formatting          | Prettier + lint-staged auto-fix on every commit       |
| Bad patterns slip through reviews     | 50+ custom rules catch issues pre-commit              |
| No code quality standards             | 50+ built-in rules catch issues pre-commit            |
| AI assistants write bad code          | AI config files guide assistants to follow your rules |
| Developers bypass pre-commit hooks    | Password-protected bypass with tamper-proof audit log |
| No documentation workflow             | Template-based feature doc & PR checklist generation  |

---

## 3. How to Install & Set Up

### Quick Setup (Recommended)

```bash
# 1. Install Code Guardian
npm install --save-dev @hatem427/code-guard-ci

# 2. Initialize (fully automatic — zero prompts)
npx code-guard init
```

That's it. Code Guardian will automatically:

1. **Detect your framework** (React, Angular, Next.js, Vue, Svelte, Node)
2. **Install all dependencies** (ESLint, Prettier, Husky, lint-staged, etc.)
3. **Generate all config files** (13+ files tailored to your framework)
4. **Set up git hooks** (pre-commit with lint-staged + Code Guardian checks)
5. **Create AI assistant configs** (Cursor, Copilot, Claude, Gemini, Windsurf, Junie, Antigravity, Aider)
6. **Create custom rules templates** (.code-guardian/ directory)
7. **Update package.json** with all necessary npm scripts

### Init Options

```bash
# Full setup (default)
npx code-guard init

# Skip AI config generation
npx code-guard init --skip-ai

# Skip Husky/git hooks setup
npx code-guard init --skip-hooks

# Overwrite existing configurations
npx code-guard init --force

# Preview what would be done (no changes)
npx code-guard init --dry-run
```

### Post-Setup (Required Security Steps)

```bash
# IMPORTANT: Change default passwords immediately!
npm run set-bypass-password    # Default: "bypass123"
npm run set-admin-password     # Default: "admin123"
```

---

## 4. How It Works — Architecture

### System Overview

```
┌─────────────────────────────────────────────────────────┐
│                    Code Guardian                        │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌─────────────┐   ┌──────────────┐   ┌─────────────┐ │
│  │  CLI Engine  │──▶│ Project      │──▶│ Config      │ │
│  │  (cli.ts)    │   │ Detector     │   │ Generators  │ │
│  └──────┬───────┘   └──────────────┘   └─────────────┘ │
│         │                                               │
│  ┌──────▼───────────────────────────────────────────┐  │
│  │            Pre-commit Hook Pipeline               │  │
│  │                                                    │  │
│  │  1. Bypass Check (password + env + commit msg)    │  │
│  │  2. Project Detection (React/Angular/Next/etc.)   │  │
│  │  3. Staged File Reading                           │  │
│  │  4. Rule Engine (50+ rules)                        │  │
│  │  5. ESLint Check                                  │  │
│  │  6. Prettier Check + Auto-fix                     │  │
│  │  7. Feature Doc Reminder                          │  │
│  │  8. Final Verdict (pass/block)                    │  │
│  └───────────────────────────────────────────────────┘  │
│                                                         │
│  ┌──────────────────────────────────────────────────┐   │
│  │              Rule Registry                        │   │
│  │                                                    │   │
│  │  guidelines.config.ts  ── Shared rules (8)        │   │
│  │  react.config.ts       ── React rules (20)        │   │
│  │  angular.config.ts     ── Angular rules (16)      │   │
│  │  nextjs.config.ts      ── Next.js rules (5)       │   │
│  │                                                    │   │
│  │  + Custom rules from .code-guardian/               │   │
│  └──────────────────────────────────────────────────┘   │
│                                                         │
│  ┌──────────────────────────────────────────────────┐   │
│  │              Security System                      │   │
│  │                                                    │   │
│  │  bypass-manager.ts ── Password auth + audit log   │   │
│  │  security-check.ts ── Log integrity verification  │   │
│  └──────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────┘
```

### Key Modules

| Module                  | File                                               | Purpose                                                       |
| ----------------------- | -------------------------------------------------- | ------------------------------------------------------------- |
| **CLI**                 | `scripts/cli.ts`                                   | Main entry point, 14-step init process                        |
| **Project Detector**    | `scripts/utils/project-detector.ts`                | Auto-detects framework, TypeScript, package manager, monorepo |
| **Rule Engine**         | `scripts/utils/rule-engine.ts`                     | Runs rules against files, produces violation reports          |
| **File Checker**        | `scripts/utils/file-checker.ts`                    | Reads staged files, finds matches, inline suppressions        |
| **Pre-commit Check**    | `scripts/precommit-check.ts`                       | Orchestrates the entire pre-commit pipeline                   |
| **Bypass Manager**      | `scripts/utils/bypass-manager.ts`                  | Password auth, audit log, integrity checksums                 |
| **Structure Validator** | `scripts/utils/structure-validator.ts`             | Validates project folder structure                            |
| **Naming Validator**    | `scripts/utils/naming-validator.ts`                | Validates file naming conventions                             |
| **ESLint Generator**    | `scripts/config-generators/eslint-generator.ts`    | Generates `eslint.config.mjs` (Flat Config)                   |
| **Prettier Generator**  | `scripts/config-generators/prettier-generator.ts`  | Generates `.prettierrc.json`                                  |
| **VS Code Generator**   | `scripts/config-generators/vscode-generator.ts`    | Generates `.vscode/settings.json`                             |
| **AI Config Generator** | `scripts/config-generators/ai-config-generator.ts` | Generates AI assistant configs                                |

---

## 5. All Rules Reference

### Tool Responsibilities — No Overlap

Code Guardian is designed so that **each tool handles its own domain** with zero redundancy:

| Tool              | What It Handles                                                                                                                                                                                                                                                   | Config File          |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- |
| **Prettier**      | Code formatting: indentation, quotes, semicolons, trailing commas, print width, bracket spacing                                                                                                                                                                   | `.prettierrc.json`   |
| **ESLint**        | Syntax & static analysis: `no-console`, `no-var`, `no-eval`, `prefer-template`, `prefer-const`, `eqeqeq`, `@typescript-eslint/*`, `react-hooks/*`, `jsx-a11y/*`, `import/order`, `react/no-danger`, `react/no-array-index-key`                                    | `eslint.config.mjs`  |
| **Code Guardian** | Architecture & domain rules: component size limits, custom CSS detection, commented code, magic numbers, Angular lifecycle patterns, RxJS best practices, React hook patterns, Next.js conventions, security (hardcoded credentials, HTTPS), performance patterns | `config/*.config.ts` |
| **Code Guardian** | Built-in commit message validation                                                                                                                                                                                                                                | -                    |
| **lint-staged**   | Auto-fix pipeline: runs ESLint `--fix` and Prettier `--write` on staged files before commit                                                                                                                                                                       | `.lintstagedrc.json` |

> **Rule of thumb:** If ESLint or Prettier already catches it, Code Guardian does NOT duplicate it.

#### ESLint Rules (generated by Code Guardian)

| Category            | Rules                                                                                                                                                                                                               |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Code Quality**    | `no-console`, `no-debugger`, `no-alert`, `no-eval`, `no-implied-eval`, `no-new-func`, `prefer-const`, `no-var`, `eqeqeq`, `curly`, `no-throw-literal`, `prefer-template`, `no-useless-concat`                       |
| **Import Ordering** | `import/order`, `import/no-duplicates`, `import/no-unresolved`                                                                                                                                                      |
| **TypeScript**      | `@typescript-eslint/no-explicit-any`, `@typescript-eslint/no-unused-vars`, `@typescript-eslint/no-non-null-assertion`, `@typescript-eslint/consistent-type-imports`                                                 |
| **React**           | `react/no-danger`, `react/no-array-index-key`, `react/self-closing-comp`, `react/jsx-no-target-blank`, `react-hooks/rules-of-hooks`, `react-hooks/exhaustive-deps`, `jsx-a11y/alt-text`, `jsx-a11y/anchor-is-valid` |
| **Angular (Nx)**    | `@angular-eslint/directive-selector`, `@angular-eslint/component-selector`, `@angular-eslint/prefer-standalone`                                                                                                     |
| **Nx Monorepo**     | `@nx/enforce-module-boundaries` (when Nx is detected)                                                                                                                                                               |

#### Prettier Settings (generated by Code Guardian)

| Setting           | Value   | Purpose                             |
| ----------------- | ------- | ----------------------------------- |
| `semi`            | `true`  | Always use semicolons               |
| `singleQuote`     | `true`  | Use single quotes                   |
| `trailingComma`   | `es5`   | Trailing commas where valid in ES5  |
| `printWidth`      | `80`    | Max line width                      |
| `tabWidth`        | `2`     | 2-space indentation                 |
| `arrowParens`     | `avoid` | Omit parens for single-param arrows |
| `bracketSameLine` | `true`  | Put `>` on same line                |
| `endOfLine`       | `auto`  | Respect OS line endings             |

---

### Code Guardian Rules (what ESLint/Prettier do NOT cover)

### Shared Rules (Apply to ALL frameworks)

| #   | Rule ID                  | Label                        | Severity  | Description                                                                                                  |
| --- | ------------------------ | ---------------------------- | --------- | ------------------------------------------------------------------------------------------------------------ |
| 1   | `no-settimeout`          | No setTimeout                | warning   | Use RxJS `timer()`, `delay()`, or framework alternatives.                                                    |
| 2   | `max-component-lines`    | Component ≤ 400 lines        | **error** | Split files exceeding 400 lines into smaller components.                                                     |
| 3   | `no-custom-css`          | Use Tailwind over custom CSS | warning   | Prefer Tailwind utilities. Applies to `.css`/`.scss`/`.sass`/`.less` files (>3 custom declarations trigger). |
| 4   | `no-commented-code`      | Remove commented code        | warning   | Remove commented-out code blocks. Use git history if needed.                                                 |
| 5   | `no-magic-numbers`       | Avoid magic numbers          | info      | Use named constants instead of magic numbers.                                                                |
| 6   | `no-unnecessary-bind`    | Avoid unnecessary .bind()    | info      | Use arrow functions instead of .bind(this).                                                                  |
| 7   | `prefer-early-return`    | Prefer early returns         | info      | Use early returns to avoid deep nesting.                                                                     |
| 8   | `prefer-arrow-functions` | Prefer arrow functions       | info      | Use arrow functions for callbacks and short functions.                                                       |

> **Note:** Rules previously here (`no-console-log`, `no-any-type`, `no-var-keyword`, `prefer-template-literals`) are now handled by ESLint — see [Tool Responsibilities](#tool-responsibilities--no-overlap) above.

### React Rules (Apply to React & Next.js)

| #   | Rule ID                                  | Label                         | Severity  | Description                                                    |
| --- | ---------------------------------------- | ----------------------------- | --------- | -------------------------------------------------------------- |
| 9   | `react-no-useeffect-no-deps`             | useEffect must have deps      | **error** | Every `useEffect` must have a dependency array.                |
| 10  | `react-no-inline-styles`                 | No inline styles              | warning   | Avoid `style={{ }}` in JSX. Use CSS modules or Tailwind.       |
| 11  | `react-no-direct-dom`                    | No direct DOM manipulation    | **error** | Avoid `document.getElementById`, etc. Use `useRef()`.          |
| 12  | `react-prefer-fc-typing`                 | Type props explicitly         | info      | Avoid `React.FC` — type props parameter directly.              |
| 13  | `react-no-prop-spreading`                | Avoid prop spreading          | info      | Avoid `{...props}` — explicitly pass required props.           |
| 14  | `no-hardcoded-credentials`               | No hardcoded credentials      | **error** | Never hardcode API keys, passwords. Use env variables.         |
| 15  | `require-https`                          | Require HTTPS URLs            | warning   | Always use HTTPS (except localhost/127.0.0.1).                 |
| 16  | `react-no-anonymous-functions-in-render` | No anonymous functions in JSX | warning   | Causes re-renders. Use `useCallback` or named functions.       |
| 17  | `react-missing-key-prop`                 | Missing key in lists          | **error** | `.map()` with JSX must have a `key` prop.                      |
| 18  | `no-large-bundle-imports`                | Avoid large library imports   | warning   | Import specific lodash/moment modules, not the entire library. |
| 19  | `require-button-type`                    | Buttons must have type        | warning   | Always specify `type` on `<button>` elements.                  |
| 20  | `react-prefer-lazy-loading`              | Consider lazy loading         | info      | Use React.lazy() for code-splitting large route components.    |
| 21  | `react-memo-expensive-components`        | Consider React.memo           | info      | Wrap expensive components in React.memo().                     |
| 22  | `no-object-array-in-deps`                | Avoid objects in deps arrays  | warning   | Objects/arrays in deps cause re-runs on every render.          |
| 23  | `react-use-fragments`                    | Use React fragments           | info      | Avoid unnecessary DOM nodes. Use <></> instead of divs.        |
| 24  | `prefer-optional-chaining`               | Use optional chaining         | info      | Use ?. instead of nested ternaries or && chains.               |
| 25  | `prefer-nullish-coalescing`              | Use nullish coalescing (??)   | info      | Use ?? instead of \|\| for default values.                     |
| 26  | `react-error-boundary-usage`             | Consider error boundaries     | info      | Wrap components that may throw in ErrorBoundary.               |
| 27  | `no-sync-external-calls`                 | Avoid synchronous calls       | warning   | Use async/await for API calls and external services.           |
| 28  | `react-prefer-controlled-inputs`         | Prefer controlled components  | info      | Use value + onChange instead of defaultValue + ref.            |
| 29  | `react-cleanup-effects`                  | Cleanup side effects          | warning   | useEffect with subscriptions must return cleanup function.     |
| 30  | `prefer-const-assertion`                 | Use const assertions          | info      | Use "as const" for object/array literals.                      |

> **Note:** Rules previously here (`react-no-dangerously-set-html`, `no-eval`, `require-alt-text`, `no-index-as-key`) are now handled by ESLint — see [Tool Responsibilities](#tool-responsibilities--no-overlap) above.

### Angular Rules (Apply to Angular only)

| #   | Rule ID                           | Label                         | Severity  | Description                                              |
| --- | --------------------------------- | ----------------------------- | --------- | -------------------------------------------------------- |
| 31  | `angular-no-ngoninit`             | Avoid ngOnInit                | warning   | Prefer constructor injection and inject() + signals.     |
| 32  | `angular-no-ng-deep`              | No ::ng-deep                  | **error** | Deprecated. Use `:host`, CSS custom properties.          |
| 33  | `angular-no-common-module`        | No CommonModule               | warning   | Import specific directives or use @if/@for control flow. |
| 34  | `angular-no-ngclass`              | No [ngClass]                  | warning   | Use `[class.name]` binding or Tailwind.                  |
| 35  | `angular-no-ngstyle`              | No [ngStyle]                  | warning   | Use `[style.property]` binding or Tailwind.              |
| 36  | `angular-no-function-in-template` | No functions in templates     | **error** | Use pipes or signals instead.                            |
| 37  | `angular-use-async-pipe`          | Use async pipe / toSignal     | warning   | Manual `.subscribe()` causes memory leaks.               |
| 38  | `angular-use-takeuntildestroyed`  | Use takeUntilDestroyed()      | warning   | Auto-unsubscribe with `takeUntilDestroyed()`.            |
| 39  | `angular-prefer-signals`          | Consider Angular Signals      | info      | Migrate `BehaviorSubject` to `signal()` / `computed()`.  |
| 40  | `angular-prefer-inject`           | Use inject() over constructor | warning   | Modern Angular (v14+) prefers `inject()` function.       |
| 41  | `angular-onpush-change-detection` | Consider OnPush               | info      | Use ChangeDetectionStrategy.OnPush for performance.      |
| 42  | `angular-trackby-ngfor`           | Use trackBy with \*ngFor      | warning   | Always provide trackBy function for \*ngFor.             |
| 43  | `angular-lazy-load-modules`       | Use lazy loading              | info      | Lazy load feature modules in routing.                    |
| 44  | `angular-standalone-components`   | Prefer standalone components  | info      | Use standalone components instead of NgModules.          |
| 45  | `angular-strict-templates`        | Enable strict templates       | info      | Use strictTemplates: true in tsconfig.json.              |
| 46  | `angular-defer-for-lazy`          | Use @defer for lazy views     | info      | Angular 17+ @defer blocks for lazy loading.              |

> **Note:** `angular-avoid-any-in-services` is now handled by ESLint (`@typescript-eslint/no-explicit-any`).

### Next.js Rules (Apply to Next.js only)

| #   | Rule ID                       | Label                          | Severity | Description                                        |
| --- | ----------------------------- | ------------------------------ | -------- | -------------------------------------------------- |
| 47  | `nextjs-use-client-directive` | Verify use client / use server | warning  | Components using hooks/events need `"use client"`. |
| 48  | `nextjs-use-image-component`  | Use next/image                 | warning  | Use `<Image>` instead of `<img>` for optimization. |
| 49  | `nextjs-use-link-component`   | Use next/link                  | warning  | Use `<Link>` for client-side navigation.           |
| 50  | `nextjs-api-error-handling`   | API routes need error handling | warning  | Wrap API handlers in try/catch.                    |
| 51  | `nextjs-page-metadata`        | Pages should export metadata   | info     | Add metadata or `generateMetadata` for SEO.        |

### Severity Levels

| Level       | Behavior                                                       |
| ----------- | -------------------------------------------------------------- |
| **error**   | 🔴 **Blocks the commit**. Must be fixed before committing.     |
| **warning** | 🟡 Allows commit but logs the issue. Should be addressed soon. |
| **info**    | 🔵 Advisory only. Informational notices for best practices.    |

---

## 6. CLI Commands

> 📄 **Full command reference:** [COMMANDS.md](COMMANDS.md)

All commands are run via `npx code-guard <command>`. Quick overview:

| Command | Description |
|---------|-------------|
| `init` | Full project setup (ESLint, Prettier, Husky, AI configs, …) |
| `check` | Manually run rule checks (same as pre-commit) |
| `check-vuln` | 3-layer security audit (npm audit + RetireJS + Grype) |
| `report` | Open last code quality report in editor |
| `checklist` | Generate PR checklist from active rules |
| `uninstall` | Remove all generated files (uses manifest) |
| `add-ai <name>` | Add a single AI assistant config |
| `list-ai` | List all AI integrations and their status |
| `version` | Print installed version |
| `help` | Display usage information |

See [COMMANDS.md](COMMANDS.md) for flags, examples, and the full npm scripts reference.

---

## 7. Configuration Files Generated

After running `code-guard init`, these files are created/updated:

### Linting & Formatting

| File                 | Purpose                                                                                 |
| -------------------- | --------------------------------------------------------------------------------------- |
| `eslint.config.mjs`  | ESLint 9+ flat configuration with framework-specific rules, import ordering, TypeScript |
| `.prettierrc.json`   | Prettier formatting rules (semi, singleQuote, trailingComma, etc.)                      |
| `.prettierignore`    | Files/folders excluded from Prettier                                                    |
| `.lintstagedrc.json` | lint-staged config — auto-fix staged files on commit                                    |

### Git Hooks & Commit Standards

| File                | Purpose                                                  |
| ------------------- | -------------------------------------------------------- |
| `.husky/pre-commit` | Pre-commit hook — runs lint-staged + Code Guardian rules |

(Commit message validation is now built into Code Guardian)

### TypeScript

| File                   | Purpose                                              |
| ---------------------- | ---------------------------------------------------- |
| `tsconfig.strict.json` | Strict TypeScript config (extends existing tsconfig) |

### Editor

| File                      | Purpose                                                                |
| ------------------------- | ---------------------------------------------------------------------- |
| `.editorconfig`           | Universal editor settings (indent, charset, EOL)                       |
| `.vscode/settings.json`   | VS Code workspace settings (ESLint validate, format-on-save, Prettier) |
| `.vscode/extensions.json` | Recommended VS Code extensions                                         |

### AI Assistants

| File                              | Purpose                                                        |
| --------------------------------- | -------------------------------------------------------------- |
| `.cursor/rules/cursor.mdc`        | Cursor AI coding rules (combined best practices + style guide) |
| `.github/copilot-instructions.md` | GitHub Copilot instructions                                    |
| `.claude/CLAUDE.md`               | Claude AI instructions                                         |
| `.gemini/GEMINI.md`               | Google Gemini AI instructions                                  |
| `.windsurf/rules/guidelines.md`   | Windsurf (Codeium) AI rules                                    |
| `.junie/guidelines.md`            | JetBrains Junie AI guidelines                                  |
| `AGENTS.md`                       | Antigravity / generic AI agent rules                           |
| `.aider.conf.yml`                 | Aider AI config                                                |

### Code Guardian Internal

| File                                    | Purpose                                                     |
| --------------------------------------- | ----------------------------------------------------------- |
| `.code-guardian/custom-rules.json`      | Custom rules, overrides, disabled rules, AI guidelines      |
| `.code-guardian/structure-rules.json`   | Project folder structure rules                              |
| `.code-guardian/naming-rules.json`      | File naming convention rules                                |
| `.code-guardian/bypass-log.json`        | Bypass audit log (read-only, tamper-protected)              |
| `.code-guardian/bypass-password.hash`   | SHA-256 hash of bypass password                             |
| `.code-guardian/admin-credentials.hash` | SHA-256 hash of admin password                              |
| `config/`                               | Framework rule configs (guidelines, react, angular, nextjs) |
| `templates/`                            | Feature doc templates (UI, API, Service)                    |
| `docs/features/`                        | Generated feature documentation                             |

---

## 8. Pre-commit Hook Flow

When you run `git commit`, the following pipeline executes:

```
┌──────────────────────────────────────────────────────────────┐
│                    Pre-commit Pipeline                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  Step 1: lint-staged (via .husky/pre-commit)                │
│          ├── ESLint --fix on staged .ts/.tsx/.js/.jsx files  │
│          ├── Prettier --write on all staged files            │
│          └── Auto-stages fixed files                         │
│                                                              │
│  Step 2: Code Guardian rules (npm run precommit-check)       │
│          │                                                   │
│          ├── 2a. Check bypass conditions                     │
│          │       ├── BYPASS_RULES=true env var → skip        │
│          │       └── #bypass-rules in message → password     │
│          │                                                   │
│          ├── 2b. Detect project type                         │
│          │       └── React / Angular / Next.js / etc.        │
│          │                                                   │
│          ├── 2c. Read staged files                           │
│          │                                                   │
│          ├── 2d. Execute rule engine (60+ rules)             │
│          │       ├── Shared rules (all frameworks)           │
│          │       └── Framework-specific rules                │
│          │                                                   │
│          ├── 2e. Run ESLint check                            │
│          │                                                   │
│          ├── 2f. Run Prettier check + auto-fix               │
│          │                                                   │
│          ├── 2g. Feature doc reminder (feature/* branches)   │
│          │                                                   │
│          └── 2h. Final verdict                               │
│                 ├── errors > 0 → ❌ COMMIT BLOCKED          │
│                 ├── warnings > 0 → ⚠️  ALLOWED with warning │
│                 └── clean → ✅ PASSED                        │
│                                                              │
└──────────────────────────────────────────────────────────────┘
```

### What Blocks a Commit?

1. **Code Guardian error-severity rule violations** (e.g., component >400 lines, direct DOM manipulation)
2. **ESLint errors** (e.g., `no-console`, `no-eval`, `no-var`, `@typescript-eslint/no-explicit-any`)

### What Allows a Commit with Warnings?

1. **Code Guardian warning-severity violations** (e.g., inline styles, setTimeout)
2. **Prettier issues** (auto-fixed and re-staged automatically)

---

## 9. Bypass System & Security

### How to Bypass Checks

There are **two methods** to bypass pre-commit checks:

#### Method 1: Commit Message Flag (Requires Password)

```bash
git commit -m "fix: emergency hotfix #bypass-rules"
# → Prompts for bypass password
# → Prompts for reason
# → Records in audit log
```

#### Method 2: Environment Variable (CI/CD)

```bash
BYPASS_RULES=true git commit -m "chore: ci deployment"
# → No password required
# → Records in audit log with default reason
# → Optional: BYPASS_REASON="Automated deployment" for custom reason
```

### Audit Log

Every bypass is recorded in `.code-guardian/bypass-log.json` with:

| Field           | Description                |
| --------------- | -------------------------- |
| `id`            | UUID for each bypass entry |
| `author`        | Git author name            |
| `email`         | Git author email           |
| `timestamp`     | ISO 8601 timestamp         |
| `reason`        | Why the bypass was needed  |
| `commitMessage` | Full commit message        |
| `branch`        | Git branch name            |
| `files`         | List of staged files       |
| `method`        | How bypass was triggered   |

### Security Features

- **Password protection** — SHA-256 hashed passwords stored in `.code-guardian/`
- **Tamper detection** — SHA-256 checksum validates log integrity
- **Read-only log** — File permissions set to 444 (read-only) after each write
- **Archive system** — Tampered or deleted logs are archived, never truly destroyed
- **Admin-only deletion** — Bypass log entries require admin password to delete
- **Local audit trail** — All bypass attempts logged to `.code-guardian/bypass-log.json`

### Managing Passwords

```bash
# Set new bypass password (for developers)
npm run set-bypass-password

# Set new admin password (for team leads/managers)
npm run set-admin-password

# View bypass log
npm run view-bypass-log

# Delete bypass entries (admin password required)
npm run delete-bypass-logs
```

---

## 10. Custom Rules

### Understanding Custom Rules Configuration

The `.code-guardian/custom-rules.json` file has **4 main sections**:

#### **1. `customRules` Array — Add New Rules**

Define new custom rules specific to your company/team:

```json
{
  "customRules": [
    {
      "id": "rule-identifier",              // Unique ID for this rule
      "label": "Display name",              // Shows in error messages
      "description": "Full explanation",    // What the rule checks
      "severity": "error",                  // error | warning | info
      "fileExtensions": ["ts", "tsx"],     // Check in these file types
      "pattern": "regex pattern",           // RegEx to find violations
      "category": "Company Standards"       // Group related rules
    }
  ]
}
```

**Example:** No hardcoded API URLs
```json
{
  "id": "nextjs-no-hardcoded-api-urls",
  "label": "No hardcoded API URLs",
  "description": "API URLs must come from environment variables",
  "severity": "error",                    // 🔴 Blocks commit
  "fileExtensions": ["ts", "tsx", "js", "jsx"],
  "pattern": "(http|https)://[a-z0-9]+\\.com",
  "category": "Security"
}
```

When a developer commits code with `https://api.example.com`, Code Guardian finds it with the regex pattern and **blocks the commit** with severity "error".

---

#### **2. `overrides` Object — Change Existing Rule Severity**

Code Guardian has 50+ built-in rules. You can change their severity levels:

```json
{
  "overrides": {
    "max-component-lines": {
      "severity": "error"              // Make this stricter
    },
    "react-no-inline-styles": {
      "severity": "error"              // Was warning → now error
    }
  }
}
```

**Severity levels:**
- `error` — 🔴 **Blocks the commit** (must be fixed)
- `warning` — 🟡 **Allows commit** but shows message (should fix soon)
- `info` — 🔵 **Informational only** (best practice tip)

---

#### **3. `disabledRules` Array — Turn Off Rules**

Disable specific rules you don't want to enforce:

```json
{
  "disabledRules": [
    "nextjs-page-metadata",             // Don't check for metadata exports
    "no-custom-css"                     // Allow custom CSS
  ]
}
```

When a rule is disabled, Code Guardian skips it entirely.

---

#### **4. `aiGuidelines` String — Guide AI Assistants**

This text is **automatically added** to all your AI config files:
- `.cursor/rules/cursor.mdc`
- `.github/copilot-instructions.md`
- `.claude/CLAUDE.md`
- `.gemini/GEMINI.md`
- `.windsurf/rules/guidelines.md`
- `.junie/guidelines.md`
- `AGENTS.md`
- `.aider.conf.yml`

So your AI assistants follow the same standards as Code Guardian:

```json
{
  "aiGuidelines": "## Company Standards\n- Use environment variables for config\n- Validate all inputs\n- Use TypeScript strict mode"
}
```

When you use Cursor or Copilot, these guidelines appear in their instruction files and they'll follow them automatically.

---

### Adding Custom Rules

Edit `.code-guardian/custom-rules.json`:

```json
{
  "customRules": [
    {
      "id": "company-no-fetch",
      "label": "Use company HTTP client",
      "description": "Use the company HTTP client wrapper instead of raw fetch().",
      "severity": "warning",
      "fileExtensions": ["ts", "tsx", "js", "jsx"],
      "pattern": "\\bfetch\\s*\\(",
      "applicableTo": [],
      "category": "Company Standards"
    }
  ],
  "overrides": {
    "max-component-lines": {
      "severity": "warning"
    }
  },
  "disabledRules": ["no-custom-css"],
  "aiGuidelines": "# Your company AI guidelines here"
}
```

### Inline Suppression

Suppress a specific rule on a specific line:

```typescript
// code-guardian-disable no-settimeout
setTimeout(() => retryConnection(), 5000);

// Or suppress for the entire file (put at top):
// code-guardian-disable-file no-magic-numbers
```

### Custom Structure Rules

Edit `.code-guardian/structure-rules.json`:

```json
[
  {
    "path": "src/shared",
    "required": true,
    "description": "Shared code across features"
  }
]
```

### Custom Naming Rules

Edit `.code-guardian/naming-rules.json`:

```json
[
  {
    "filePattern": "\\.helper\\.(ts|js)$",
    "convention": "kebab-case",
    "description": "Helper files should use kebab-case: date.helper.ts"
  }
]
```

---

## 11. AI Assistant Integration

Code Guardian generates configuration files for **8 AI assistants**:

| Assistant          | Config File               | Location           |
| ------------------ | ------------------------- | ------------------ |
| **Cursor**         | `cursor.mdc`              | `.cursor/rules/`   |
| **GitHub Copilot** | `copilot-instructions.md` | `.github/`         |
| **Claude**         | `CLAUDE.md`               | `.claude/`         |
| **Gemini**         | `GEMINI.md`               | `.gemini/`         |
| **Windsurf**       | `guidelines.md`           | `.windsurf/rules/` |
| **Junie**          | `guidelines.md`           | `.junie/`          |
| **Antigravity**    | `AGENTS.md`               | Project root       |
| **Aider**          | `.aider.conf.yml`         | Project root       |

Each config contains:

- Your framework's rules (React hooks, Angular patterns, etc.)
- Code quality standards (no `any`, proper typing, etc.)
- Your custom company guidelines from `.code-guardian/custom-rules.json`
- Naming and structure conventions

### Adding Custom AI Rules

There are two ways to add your own company-specific rules to the AI configurations:

1.  **Global Custom Rules (Recommended)**
    Edit `.code-guardian/custom-rules.json` and add your rules to the `aiGuidelines` field. These will be automatically included in **all** generated AI configs (Cursor, Copilot, etc.) whenever you run `init` or `add-ai`.

    ```json
    {
      "aiGuidelines": "## Company Standards\n- Always use Hexagonal Architecture\n- Prefer Zod for validation"
    }
    ```

2.  **Direct File Editing**
    You can manually edit `.cursor/rules/*.mdc`, `.github/copilot-instructions.md`, etc. for quick changes.
    Since Code Guardian **appends** to these files (if the marker isn't found), your manual changes will be preserved as long as you don't remove the Code Guardian marker.

```bash
# Add a single AI assistant config
code-guard add-ai cursor      # Generates .cursor/rules/cursor.mdc
code-guard add-ai copilot     # Generates .github/copilot-instructions.md
code-guard add-ai claude      # Generates .claude/CLAUDE.md
code-guard add-ai gemini      # Generates .gemini/GEMINI.md
code-guard add-ai windsurf    # Generates .windsurf/rules/guidelines.md
code-guard add-ai junie       # Generates .junie/guidelines.md
code-guard add-ai antigravity # Generates AGENTS.md
code-guard add-ai aider       # Generates .aider.conf.yml

# List all available configs
code-guard list-ai
```

---

## 12. Framework Support

### Auto-Detection Priority

Code Guardian detects frameworks in this order (first match wins):

1. **Nuxt** — `nuxt` dependency
2. **Next.js** — `next` dependency
3. **Angular** — `@angular/core` dependency
4. **Svelte** — `svelte` or `@sveltejs/kit` dependency
5. **Vue** — `vue` dependency
6. **React** — `react` dependency
7. **Node.js** — `express`/`fastify`/`koa`/`@nestjs/core` dependency
8. **Unknown** — Fallback (only shared rules apply)

### Framework-Specific Features

| Feature              | React                                  | Angular                         | Next.js                                  |
| -------------------- | -------------------------------------- | ------------------------------- | ---------------------------------------- |
| Custom rules         | 14 rules                               | 10 rules                        | 5 rules + inherits React                 |
| ESLint config        | React + hooks + a11y plugins           | Angular + RxJS plugins          | Next.js + React plugins                  |
| Structure validation | `src/components`, `src/hooks`, etc.    | `src/app`, `src/services`, etc. | `app/`, `components/`, `lib/`            |
| Naming conventions   | PascalCase components, camelCase hooks | kebab-case everywhere           | PascalCase components, special filenames |

### What Gets Detected

```
┌─────────────────────────────────┐
│  detectProject() returns:       │
│                                 │
│  • type: "react"                │
│  • label: "React"               │
│  • usesTypeScript: true/false   │
│  • packageManager: npm/yarn/... │
│  • monorepo: nx/turborepo/none  │
│  • existingTooling:             │
│      ├── hasEslint              │
│      ├── hasPrettier            │
│      ├── hasTypescript          │
│      ├── hasHusky               │
│      ├── hasLintStaged          │

│      ├── hasEditorConfig        │
│      ├── hasCursorRules         │
│      ├── hasCopilotInstructions │
│      └── hasAgentRules          │
└─────────────────────────────────┘
```

---

## 13. Expected Behavior & What to Expect

### After Setup

1. **Every commit is automatically checked** — ESLint, Prettier, and Code Guardian rules run on staged files
2. **Auto-fix** — Prettier will auto-format and re-stage files that have formatting issues
3. **Commit message enforcement** — Commits must follow conventional format: `type(scope): subject`
4. **Feature doc reminders** — On `feat/*` or `feature/*` branches, you'll be reminded to create docs

### Example Commit Scenarios

#### ✅ Clean Commit

```bash
$ git add src/components/UserCard.tsx
$ git commit -m "feat(user): add user card component"

🛡️  Code Guardian — Pre-commit checks...
✅ lint-staged passed
✅ ESLint check passed
✅ Prettier check passed
✅ All 14 rules passed — 0 violations
✅ All checks passed — commit allowed!
```

#### ❌ Blocked Commit (component too large)

```bash
$ git add src/components/UserCard.tsx   # Contains 500+ lines
$ git commit -m "feat(user): add user card"

🛡️  Code Guardian — Pre-commit checks...
❌ Code Quality: max-component-lines
   src/components/UserCard.tsx — Component exceeds 400 lines. Split into smaller components.

❌ Commit BLOCKED — fix the errors and try again.
   To bypass: use "#bypass-rules" in commit message
```

#### ⚠️ Commit with Warnings

```bash
$ git add src/components/UserCard.tsx   # Contains inline style
$ git commit -m "style(user): adjust card layout"

🛡️  Code Guardian — Pre-commit checks...
⚠️  Styling: react-no-inline-styles
   src/components/UserCard.tsx:15 — Avoid style={{}}. Use CSS modules.

⚠️  Commit allowed with warnings. Please address them soon.
```

#### ❌ Bad Commit Message

```bash
$ git commit -m "test"

🛡️  Code Guardian — Pre-commit checks...
✅ lint-staged passed
✅ ESLint check passed
✅ Prettier check passed
✅ All checks passed — commit allowed!
```

### Validate Command Output

```bash
$ npx code-guard validate

📡 Framework: React
📂 Folder Structure:
  ✓ All folder structure checks passed

📝 File Naming:
  ⚠ src/components/user_profile.tsx: PascalCase expected
  ⚠ src/hooks/authHook.ts: Should start with "use"

⚠️  Found 2 issue(s) to review.
```

---

## 14. Troubleshooting

### Common Issues

| Issue                             | Solution                                                                         |
| --------------------------------- | -------------------------------------------------------------------------------- |
| `code-guard: command not found`   | Run `npx code-guard` or install globally: `npm i -g @hatem427/code-guard-ci`     |
| ESLint config conflicts           | Delete old `.eslintrc.*` / `eslint.config.*` files and re-run `code-guard init`  |
| Husky hooks not running           | Run `npx husky init` then `code-guard init --skip-hooks` won't overwrite         |
| TypeScript version mismatch       | Check `@typescript-eslint/*` version compatibility                               |
| `BYPASS_RULES=true` not working   | Make sure the env var is set in the same shell session                           |
| Bypass password forgotten         | Delete `.code-guardian/bypass-password.hash` — defaults to `"bypass123"`         |
| bypass-log.json read-only error   | The log is intentionally read-only. Code Guardian manages permissions internally |
| lint-staged ignoring config files | `.lintstagedrc.json` has `--ignore-pattern "*.config.*"` for this                |

### Reset Everything

```bash
# Remove all Code Guardian generated configs
rm -f eslint.config.mjs .eslintignore .eslintrc.* .prettierrc.json .prettierignore
rm -f .lintstagedrc.json .editorconfig
rm -f tsconfig.strict.json AGENTS.md .aider.conf.yml
rm -rf .cursor/rules/cursor.mdc
rm -rf .github/copilot-instructions.md
rm -rf .claude/CLAUDE.md
rm -rf .gemini/GEMINI.md
rm -rf .windsurf/rules/guidelines.md
rm -rf .junie/guidelines.md
rm -rf .vscode/settings.json .vscode/extensions.json

# Re-initialize
npx code-guard init --force
```

### Debug Mode

```bash
# Run checks manually to see all output
npx code-guard check

# Validate project structure and naming
npx code-guard validate

# Dry run to see what init would do
npx code-guard init --dry-run
```

---

## 15. Advanced: Modifying Core Defaults

If you are maintaining the `@hatem427/code-guard-ci` package itself and want to change the **global default rules** used by `init`, you must edit the source code and rebuild.

### Source Code Map

| Logic Type          | File Location                                      | Description                                                         |
| :------------------ | :------------------------------------------------- | :------------------------------------------------------------------ |
| **AI Instructions** | `scripts/config-generators/ai-config-generator.ts` | Hardcoded prompts for Cursor, Copilot, etc. (e.g. "Use React.memo") |
| **ESLint Rules**    | `scripts/config-generators/eslint-generator.ts`    | Default ESLint rules and plugins injected into `eslint.config.mjs`  |
| **Core Rules**      | `config/guidelines.config.ts`                      | The 50+ built-in rules (max-component-lines, etc.)                  |
| **Framework Logic** | `scripts/utils/project-detector.ts`                | How frameworks are detected (dependencies, file structures)         |
| **CLI Steps**       | `scripts/cli.ts`                                   | The step-by-step logic of `code-guard init`                         |

### How to Rebuild

After modifying any file in `scripts/` or `config/`:

```bash
# In the roles/ directory
npm run build
```

This compiles the TypeScript code to JavaScript in the `dist/` folder, which is what `npx` actually runs.

---

## Appendix: Rule Categories Summary

### Performance Rules (14 total)

- React: lazy loading, React.memo, useMemo, useCallback, object deps, bundle imports
- Angular: OnPush change detection, trackBy, lazy load modules, defer blocks

### Best Practices (18 total)

- Code quality, early returns, fragments, controlled components, error boundaries
- Modern syntax: optional chaining, nullish coalescing, template literals, arrow functions, const assertions

### Security (4 total)

- No eval, hardcoded credentials, HTTPS requirements, XSS prevention

### Accessibility (2 total)

- Alt text, button types

### Deprecated APIs (5 total - Angular)

- ng-deep, CommonModule, ngClass, ngStyle, ngOnInit

### Memory Management (4 total)

- Effect cleanup, takeUntilDestroyed, async pipe, unsubscribe patterns

**Total Rules: 60** (12 shared + 26 React + 17 Angular + 5 Next.js)

---

_Generated by Code Guardian v2.0.0 — Last updated: 2026-02-16_