{"id":29123080,"url":"https://github.com/diullei/codeguardian","last_synced_at":"2025-06-29T18:05:44.668Z","repository":{"id":300205101,"uuid":"1005004727","full_name":"Diullei/codeguardian","owner":"Diullei","description":"Code Guardian is an experimental developer tool designed to validate and enforce architectural rules in codebases, especially valuable when dealing with AI-generated code. It automatically analyzes code after every change to preserve architectural integrity, enforce predefined standards, and reduce the risk of AI hallucinations, ensuring consistent","archived":false,"fork":false,"pushed_at":"2025-06-28T10:15:21.000Z","size":451,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-28T10:23:42.612Z","etag":null,"topics":["ai-code-validation","ai-generated-code","code-quality","llm-tools","static-analysis"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Diullei.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-19T14:09:21.000Z","updated_at":"2025-06-28T10:15:18.000Z","dependencies_parsed_at":"2025-06-20T12:11:41.099Z","dependency_job_id":"71ad095d-c801-4006-8cdd-e56aeee289e8","html_url":"https://github.com/Diullei/codeguardian","commit_stats":null,"previous_names":["diullei/codeguardian"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Diullei/codeguardian","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diullei%2Fcodeguardian","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diullei%2Fcodeguardian/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diullei%2Fcodeguardian/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diullei%2Fcodeguardian/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Diullei","download_url":"https://codeload.github.com/Diullei/codeguardian/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Diullei%2Fcodeguardian/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262642951,"owners_count":23341817,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-code-validation","ai-generated-code","code-quality","llm-tools","static-analysis"],"created_at":"2025-06-29T18:05:43.510Z","updated_at":"2025-06-29T18:05:44.657Z","avatar_url":"https://github.com/Diullei.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Code Guardian\n\n**Code Guardian** is an **experimental** developer tool designed to validate and enforce architectural rules in codebases—especially valuable when dealing with AI-generated code. It automatically analyzes code after every change to preserve architectural integrity, enforce predefined standards, and reduce the risk of AI hallucinations, ensuring consistent, high-quality software structures.\n\n\u003e ⚠️ **Experimental Project**: Currently in beta. APIs and features may change.\n\n## Overview\n\nCode Guardian is a Git-aware validation tool that protects your codebase from unwanted changes—particularly useful when working with AI coding assistants. It enforces architectural boundaries, protects critical folders from modifications, and ensures dependency flow rules are followed.\n\n**Key benefits:**\n- **Protect critical code**: Prevent AI agents from modifying protected folders or files\n- **Enforce architecture**: Ensure domain code doesn't import from infrastructure layers\n- **Validate changes early**: Catch issues in Git diffs before they reach your main branch\n- **Compose simple rules**: Build complex validations from reusable primitives\n\nCode Guardian analyzes only what changed (by default), making it fast and focused. It can validate committed changes between branches, uncommitted changes in your working directory, or perform deep analysis of the entire codebase when needed.\n\n## Installation\n\nCode Guardian is currently in beta. Install it globally:\n\n```bash\nnpm install -g @diullei/codeguardian@beta\n```\n\nOr add it as a development dependency to your project:\n\n```bash\nnpm install --save-dev @diullei/codeguardian@beta\n```\n\n### Running Without Installation\n\nYou can also run Code Guardian directly using `npx`:\n\n```bash\nnpx @diullei/codeguardian@beta check\n```\n\n### Contributing\n\nWant to contribute or run Code Guardian from source? See our [Contributing Guide](CONTRIBUTING.md) for development setup instructions.\n\n## Quick Start\n\n1. Create a rule configuration file to protect your codebase:\n\n```yaml\n# protect-critical-code.yaml\nid: protect-core-auth\ndescription: Prevent modifications to authentication and security modules\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: 'src/{auth,security}/**/*'\n    assert:\n        type: assert_property\n        property_path: 'status'\n        expected_value: 'unchanged'\n        operator: '=='\n        message: 'Critical security code should not be modified without review'\n```\n\n2. Enforce architectural boundaries:\n\n```yaml\n# enforce-architecture.yaml\nid: clean-architecture\ndescription: Ensure domain logic doesn't depend on infrastructure\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: 'src/domain/**/*.{ts,js}'\n    assert:\n        type: none_of\n        rules:\n            - type: assert_match\n              pattern: 'from\\s+[\"\\'].*infrastructure'\n              message: 'Domain layer cannot import from infrastructure'\n            - type: assert_match\n              pattern: 'from\\s+[\"\\'].*database'\n              message: 'Domain layer cannot directly access database'\n```\n\n3. Run validation on your changes:\n\n```bash\n# Check changes between your feature branch and main\ncodeguardian check -c protect-critical-code.yaml -b main\n\n# Check all rules in a directory\ncodeguardian check -c \"rules/*.yaml\" -b main\n```\n\n4. **AI Coding Agent Workflow**: When using AI coding assistants, instruct them to run `codeguardian check` periodically or after completing tasks. The command provides clear violation information that helps the AI self-correct and stay aligned with your architectural rules:\n\n```bash\n# In your AI prompt, include:\n\"After implementing the feature, run 'codeguardian check' to validate the changes \nagainst our architectural rules. Fix any violations before considering the task complete.\"\n\n# If the AI forgets to check, prompt it:\n\"Please run 'codeguardian check' to ensure your implementation follows our rules.\"\n```\n\nThis workflow works similarly to instructing AI agents to run tests or linters—Code Guardian acts as an architectural linter that helps AI agents recover from potential hallucinations and maintain code quality.\n\n## Rule Primitives\n\n### Selectors\n\nSelectors find and return items to validate:\n\n- **select_files** - Select files by path pattern and status\n  - By default: only selects files that have changed (added/modified/deleted/renamed)\n  - With `select_all: true`: selects from all files in the repository\n- **select_lines** - Select lines matching a pattern within file content\n- **select_ast_nodes** - Select AST nodes using ast-grep queries\n- **select_file_changes** - Select files based on percentage of lines changed\n- **select_command_output** - Execute shell commands and capture their output (stdout, stderr, exit code)\n\n### Assertions\n\nAssertions check properties of selected items:\n\n- **assert_match** - Check if text matches a pattern\n- **assert_count** - Check the count of items\n- **assert_property** - Check object properties (supports regex extraction from strings)\n- **assert_command_output** - Validate command execution results (exit code, stdout, stderr)\n\n### Combinators\n\nCombinators compose rules using logical operations:\n\n- **all_of** - All rules must pass (AND)\n- **any_of** - At least one rule must pass (OR)\n- **none_of** - No rules should pass (NOT)\n- **for_each** - Apply assertion to each selected item\n\n## Examples\n\n### Real-World Mode Example: Catching Untracked Violations\n\nImagine you accidentally create a test file in the wrong location:\n\n```bash\n# Oops! Created a test file outside the tests/ directory\necho \"describe('test', () =\u003e {});\" \u003e src/mytest.test.js\n```\n\nWith **default mode (diff)**, this violation won't be caught until you stage it:\n```bash\ncodeguardian check              # ✅ Passes - file is untracked\ngit add src/mytest.test.js     # Stage the file\ncodeguardian check              # ❌ NOW it fails!\n```\n\nWith **all mode**, violations are caught immediately:\n```bash\ncodeguardian check --mode=all   # ❌ Fails immediately - catches untracked file!\n```\n\nThis is why protective rules often benefit from `--mode=all` or `select_all: true`.\n\n### Protect Critical Infrastructure from AI Modifications\n\nWhen working with AI coding assistants, protect your critical infrastructure code:\n\n```yaml\n# protect-payment-system.yaml\nid: protect-payment-infrastructure\ndescription: Prevent AI from modifying payment processing code\nrule:\n    type: none_of\n    rules:\n        # Block any modifications to payment processing\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: 'src/payments/**/*'\n              status: ['modified', 'deleted']\n          assert:\n              type: assert_match\n              pattern: '.*'\n              should_match: true\n              message: 'Payment system files cannot be modified by AI agents'\n        \n        # Block creation of new payment-related files\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: '**/payment*'\n              status: ['added']\n          assert:\n              type: assert_match\n              pattern: '.*'\n              should_match: true\n              message: 'New payment files require human review'\n```\n\n### Prevent AI from Breaking Architecture Boundaries\n\nEnsure AI respects your architectural decisions:\n\n```yaml\n# enforce-clean-architecture.yaml\nid: enforce-layer-boundaries\ndescription: Maintain architectural integrity across layers\nrule:\n    type: all_of\n    rules:\n        # Domain layer independence\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: 'src/domain/**/*.{ts,js}'\n          assert:\n              type: none_of\n              rules:\n                  - type: assert_match\n                    pattern: 'from\\s+[\"\\'].*/(infrastructure|adapters|ui)'\n                    message: 'Domain layer must remain pure - no infrastructure dependencies'\n                  - type: assert_match\n                    pattern: 'import.*express|axios|prisma|mongoose'\n                    message: 'Domain layer cannot use framework-specific libraries'\n        \n        # Application layer can only depend on domain\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: 'src/application/**/*.{ts,js}'\n          assert:\n              type: assert_match\n              pattern: 'from\\s+[\"\\'].*/(infrastructure|adapters)'\n              should_match: false\n              message: 'Application layer cannot directly access infrastructure'\n```\n\n### Validate AI Task Implementation\n\nWhen AI completes a task, validate it actually did what was requested:\n\n```yaml\n# validate-auth-feature.yaml\nid: validate-jwt-implementation\ndescription: Ensure JWT authentication was properly implemented\nrule:\n    type: all_of\n    rules:\n        # Check the feature exists\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: 'src/auth/jwt.{ts,js}'\n              select_all: true  # Check current state, not just diff\n          assert:\n              type: all_of\n              rules:\n                  - type: assert_match\n                    pattern: 'verify.*token|jwt\\.verify'\n                    message: 'JWT verification must be implemented'\n                  - type: assert_match\n                    pattern: 'sign.*token|jwt\\.sign'\n                    message: 'JWT signing must be implemented'\n                  - type: assert_match\n                    pattern: 'RS256|ES256'  # Secure algorithms\n                    message: 'Must use secure signing algorithm'\n        \n        # Ensure no insecure patterns\n        - type: for_each\n          select:\n              type: select_files\n              path_pattern: 'src/auth/**/*.{ts,js}'\n          assert:\n              type: assert_match\n              pattern: 'algorithm.*HS256|none'  # Weak algorithms\n              should_match: false\n              message: 'Cannot use weak JWT algorithms'\n```\n\n### Monitor File Change Magnitude\n\nPrevent AI from making massive rewrites:\n\n```yaml\n# limit-ai-changes.yaml\nid: prevent-large-rewrites\ndescription: Ensure AI makes incremental changes, not complete rewrites\nrule:\n    type: all_of\n    rules:\n        # Flag files that are mostly rewritten\n        - type: for_each\n          select:\n              type: select_file_changes\n              min_percentage: 70\n          assert:\n              type: assert_match\n              pattern: '.*'\n              should_match: true\n              message: 'File rewritten by \u003e70% - requires careful review'\n        \n        # Protect critical configs from large changes\n        - type: assert_count\n          select:\n              type: select_file_changes\n              min_percentage: 20\n          assert:\n              type: assert_match\n              pattern: 'package\\.json|tsconfig|webpack\\.config|.env'\n              should_match: false\n              message: 'Configuration files should not change more than 20%'\n```\n\n### AST-Based Validation\n\nCode Guardian uses [ast-grep](https://ast-grep.github.io/) for powerful pattern matching. Here are some advanced patterns:\n\n#### Basic Pattern with Meta Variables\n\n```yaml\nid: no-direct-dom-manipulation\ndescription: Prevent direct DOM manipulation in React components\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: '**/*.{jsx,tsx}'\n    assert:\n        type: for_each\n        select:\n            type: select_ast_nodes\n            query: 'document.$METHOD($ARG)'  # Matches document.getElementById(...), etc.\n            language: 'typescript'\n        assert:\n            type: assert_match\n            pattern: '.'\n            should_match: false\n            message: 'Direct DOM manipulation detected. Use React refs instead.'\n```\n\n#### Capturing and Reusing Variables\n\n```yaml\nid: consistent-error-handling\ndescription: Ensure caught errors are properly handled\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: '**/*.ts'\n    assert:\n        type: for_each\n        select:\n            type: select_ast_nodes\n            # $ERR matches the error variable name and ensures it's used in the catch block\n            query: |\n                try { $$$ } catch ($ERR) { $$CATCH_BODY }\n            language: 'typescript'\n        assert:\n            type: assert_property\n            property_path: 'text'\n            expected_value: '$ERR'  # Ensures the error is referenced\n            operator: 'includes'\n```\n\n#### Multi Meta Variables for Flexible Matching\n\n```yaml\nid: no-console-in-production\ndescription: Prevent console statements with any number of arguments\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: 'src/**/*.{js,ts}'\n        exclude_pattern: '**/*.test.*'\n    assert:\n        type: for_each\n        select:\n            type: select_ast_nodes\n            query: 'console.$METHOD($$ARGS)'  # Matches console.log(...), console.error(...), etc.\n            language: 'javascript'\n        assert:\n            type: assert_match\n            pattern: '.'\n            should_match: false\n            message: 'Remove console statements from production code'\n```\n\n### Check for Required Features (Absolute Validation)\n\n```yaml\nid: ensure-logging-configured\ndescription: Verify logging is properly configured in the application\nrule:\n    type: for_each\n    select:\n        type: select_files\n        path_pattern: '**/config/logger.ts'\n        select_all: true # Check all files, not just changed ones\n    assert:\n        type: all_of\n        rules:\n            - type: assert_match\n              pattern: 'winston|pino|bunyan'\n              message: Logger configuration must use a proper logging library\n            - type: assert_match\n              pattern: 'createLogger|getLogger'\n              message: Logger must be properly initialized\n```\n\nThis example uses `select_all: true` to validate that certain features exist in the codebase regardless of what files have changed. This is useful for enforcing architectural requirements or ensuring critical configurations are in place.\n\n### Validate Build Output and Metrics\n\nCode Guardian can execute shell commands and validate their output, making it perfect for checking build results, test coverage, or other metrics:\n\n```yaml\nid: validate-build-metrics\ndescription: Ensure build succeeds and bundle size is within limits\nrule:\n    type: all_of\n    rules:\n        # Check that build succeeds\n        - type: for_each\n          select:\n              type: select_command_output\n              command: 'npm run build'\n          assert:\n              type: assert_command_output\n              target: 'exitCode'\n              condition: '=='\n              value: 0\n              suggestion: 'Build failed - check build logs for errors'\n        \n        # Extract and validate bundle size from build output\n        - type: for_each\n          select:\n              type: select_command_output\n              command: 'npm run build:stats'\n          assert:\n              type: assert_property\n              property_path: 'stdout'\n              # Extract numeric value from output like \"Bundle size: 1,245 KB\"\n              extract_pattern: 'Bundle size:\\s*([\\d,]+)\\s*KB'\n              operator: '\u003c='\n              expected_value: 2000\n              suggestion: 'Bundle size exceeds 2MB limit'\n```\n\nThis example shows how to:\n- Run build commands and check their exit codes\n- Extract numeric values from command output using regex patterns\n- Validate that metrics stay within acceptable thresholds\n\n## CLI Usage\n\n### Check Command\n\n```bash\ncodeguardian check [options]\n\nConfiguration Options:\n  -c, --config   Path to rule configuration file or glob pattern [optional]\n                 (auto-discovers if not provided)\n  -e, --exclude  Glob patterns to exclude from config file search [array]\n\nRepository Options:\n  -r, --repo     Repository path                          [default: \".\"]\n  -b, --base     Base branch for comparison               [default: \"main\"]\n      --head     Head branch for comparison               [default: \"HEAD\"]\n\nOutput Options:\n  -f, --format   Output format (console/json)             [default: \"console\"]\n\n  -h, --help     Show help\n```\n\n\n### Analysis Modes\n\nCode Guardian offers three validation modes to check different scopes of your codebase:\n\n#### 1. **Diff Mode** (default) - Check Only Changed Files\nValidates files that have changed between two Git branches/commits. Perfect for CI/CD and PR reviews.\n\n```bash\n# Check changes between your branch and main\ncodeguardian check              # Default: compares HEAD with main\ncodeguardian check -b develop   # Compare HEAD with develop\n```\n\n**Use when**: You want fast, focused validation on what's changed\n\n#### 2. **All Mode** - Check Entire Working Directory\nValidates ALL files including tracked, untracked, and ignored files. Catches violations immediately, even before committing.\n\n```bash\n# Check everything in your working directory\ncodeguardian check --mode=all\ncodeguardian check -m all      # Short form\n```\n\n**Use when**: \n- Enforcing project-wide standards (no yarn.lock, no test files outside tests/)\n- Catching violations in newly created files before staging\n- Running comprehensive validation\n\n#### 3. **Staged Mode** - Check Only Staged Files\nValidates only files in your Git staging area. Ideal for pre-commit hooks.\n\n```bash\n# Check only what you're about to commit\ncodeguardian check --mode=staged\ncodeguardian check -m staged    # Short form\n```\n\n**Use when**: Setting up pre-commit hooks or validating before committing\n\n### Mode vs select_all: What's the Difference?\n\n- **Mode** controls which files Code Guardian sees from your filesystem\n- **select_all** in rules controls whether to check against the diff or all repository files\n\nExample:\n```yaml\n# This rule with select_all: true ALWAYS checks all repository files\n# regardless of the --mode flag\ntype: for_each\nselect:\n  type: select_files\n  path_pattern: 'yarn.lock'\n  select_all: true  # Ignores mode, always checks if yarn.lock exists anywhere\n```\n\n### Configuration File Discovery\n\nCode Guardian supports multiple ways to specify configuration files:\n\n1. **Auto-discovery** (no --config flag): Automatically searches for:\n\n    - `*.codeguardian.yaml`, `*.codeguardian.yml`\n    - `*.cg.yaml`, `*.cg.yml`\n    - `.codeguardian.yaml`, `.codeguardian.yml`\n    - `.cg.yaml`, `.cg.yml`\n    - `.codeguardian/*.yaml`, `.codeguardian/*.yml`\n    - `.codeguardian/*.cg.yaml`, `.codeguardian/*.codeguardian.yaml`\n\n2. **Specific file**: `codeguardian check -c my-rules.yaml`\n\n3. **Glob pattern**: `codeguardian check -c \"rules/*.yaml\"`\n\n### Multiple Configuration Files\n\nWhen multiple configuration files are found, Code Guardian evaluates each file separately and reports results for each one. This allows you to:\n\n- See which specific configuration file has violations\n- Organize rules into logical groups (e.g., security.yaml, architecture.yaml)\n- Get detailed feedback for each rule set\n\n```bash\n# Auto-discover and check all config files\ncodeguardian check\n\n# Use glob pattern to check specific files\ncodeguardian check -c \"rules/*.cg.yaml\"\n\n# Exclude test and vendor directories\ncodeguardian check --exclude \"**/test/**\" \"**/vendor/**\"\n```\n\n**Note:** Code Guardian analyzes the Git diff between the base branch and head branch/commit. Only files that have been added, modified, deleted, or renamed in this diff will be validated. This ensures efficient validation focused on actual changes rather than the entire codebase.\n\n## Rule Configuration Schema\n\n```yaml\nid: \u003crule-id\u003e\ndescription: \u003cdescription\u003e\nrule:\n    type: \u003crule-type\u003e\n    # Rule-specific configuration\n```\n\n### File Selector\n\n```yaml\ntype: select_files\npath_pattern: '**/*.js' # Glob pattern to match against changed files\nstatus: ['added', 'modified'] # Filter by Git status (added/modified/deleted/renamed)\nexclude_pattern: '**/*.test.js' # Exclude files matching this pattern\nselect_all: false # If true, selects from all files in repo (not just diff)\n```\n\nThe file selector operates on files from the Git diff between base and head branches by default. It uses minimatch for glob pattern matching. When `select_all` is set to `true`, it will select from all files in the repository, which is useful for validating that certain features or patterns exist in the codebase regardless of recent changes.\n\n## Rule Protection Levels\n\nCode Guardian supports two protection levels for rules, each serving different purposes:\n\n### Protective Rules (Absolute Protection)\n\nUse `select_all: true` for rules that must **always** pass across the entire codebase:\n\n- **Runtime Safety**: Patterns that would crash your application\n- **Security**: No secrets, no vulnerable code patterns  \n- **Project Standards**: Package manager consistency (no yarn.lock if using npm)\n- **Legal/Compliance**: License headers, regulatory requirements\n\n```yaml\n# Example: Prevent runtime errors\ntype: for_each\nselect:\n  type: select_files\n  path_pattern: '**/*.ts'\n  select_all: true  # Always check entire codebase\nassert:\n  type: assert_match\n  pattern: 'eval\\(|Function\\('\n  should_match: false\n  message: 'Dynamic code execution is forbidden'\n```\n\n### Development Rules (Progressive Protection)\n\nUse diff-based checking (default) for rules that improve code quality incrementally:\n\n- **Code Patterns**: Enforce conventions on new/modified code\n- **Architecture**: Maintain boundaries in changes\n- **Style**: Apply standards progressively\n- **Refactoring**: Improve quality over time\n\n```yaml\n# Example: Enforce naming on new files\ntype: for_each\nselect:\n  type: select_files\n  path_pattern: 'src/**/*.ts'\n  status: ['added']  # Only new files\nassert:\n  type: assert_match\n  pattern: '^[A-Z][a-zA-Z]+\\.ts$'\n  message: 'New TypeScript files must use PascalCase'\n```\n\n### Best Practice: Separate Rule Files\n\nOrganize your rules by protection level:\n\n```\n.codeguardian/\n  protective-rules.yaml   # select_all: true - critical checks\n  development-rules.yaml  # diff-based - progressive improvements\n```\n\nThis separation makes it clear which rules are absolute requirements versus progressive improvements.\n\n### Line Selector\n\n```yaml\ntype: select_lines\npattern: 'TODO' # Regex pattern\nflags: 'i' # Regex flags\ninclude_context: 2 # Context lines\n```\n\n### AST Node Selector\n\n```yaml\ntype: select_ast_nodes\nquery: 'function_declaration' # AST query\nlanguage: 'typescript' # Language\n```\n\n### Match Assertion\n\n```yaml\ntype: assert_match\npattern: 'console\\.log' # Regex pattern\nshould_match: false # Expected result\n```\n\n### Count Assertion\n\n```yaml\ntype: assert_count\ncondition: '\u003e=' # Comparison operator\nvalue: 1 # Expected value\n```\n\n### Property Assertion\n\n```yaml\ntype: assert_property\nproperty_path: 'status' # Property path\nexpected_value: 'added' # Expected value\noperator: '==' # Comparison operator\n```\n\n## Generating Rules with AI\n\nCode Guardian provides a comprehensive [Cheat Sheet](Cheat_Sheet.md) that serves as both a reference guide and a foundation for AI-assisted rule generation. This document contains detailed information about all available selectors, assertions, combinators, and common patterns.\n\n### Two Approaches for Rule Generation\n\n#### 1. Manual Reference\nRead the [Cheat Sheet](Cheat_Sheet.md) to understand how to write rules directly. The cheat sheet includes:\n- Complete syntax reference for all rule types\n- Common patterns and examples\n- Best practices for different validation scenarios\n- Special notes for task validation rules\n\n#### 2. AI-Assisted Generation\nUse the Cheat Sheet content with AI tools to generate rules automatically:\n\n1. **Prepare your context**: Use a tool like [Repomix](https://repomix.com/) to generate a comprehensive summary of your codebase\n2. **Create your prompt**: Combine:\n   - The full content of [Cheat_Sheet.md](Cheat_Sheet.md)\n   - Your codebase information (from Repomix or similar)\n   - Your specific validation requirements\n3. **Generate rules**: Ask your preferred AI (Claude, ChatGPT, etc.) to create Code Guardian rules based on your requirements\n\n### Example AI Prompt Structure\n\n```\nHere's the Code Guardian rule syntax guide:\n[paste Cheat_Sheet.md content]\n\nHere's my codebase structure:\n[paste Repomix output or codebase summary]\n\nPlease generate a Code Guardian rule that:\n- Ensures no console.log statements in production code\n- Validates that all async functions have try-catch blocks\n- Enforces that domain layer doesn't import from infrastructure\n```\n\n### Tips for Effective Rule Generation\n\n- **Be specific**: Clearly describe what you want to validate\n- **Provide context**: Include relevant code examples or architectural decisions\n- **Start simple**: Begin with basic rules and gradually add complexity\n- **Test iteratively**: Generate, test, and refine your rules\n- **Use task validation**: For temporary validation of specific implementations, remember to use `select_all: true`\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiullei%2Fcodeguardian","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdiullei%2Fcodeguardian","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiullei%2Fcodeguardian/lists"}