安全说明
数据安全
- 本工具在本地运行,不上传代码到外部服务器
- 所有扫描结果仅存储在用户本地文件系统
- 支持离线使用,无需网络连接(除自动更新检查外)
权限要求
- 文件系统读取权限(扫描代码文件)
- Git 仓库访问权限(PR review 功能)
- 网络访问(可选,用于自动更新检查)
代码安全
- 不会修改或删除用户代码文件
- 仅进行读取和分析操作
- 生成的报告文件需用户明确指定输出路径
依赖安全
- 所有 Python 依赖均为知名开源库
- 定期更新依赖以修复安全漏洞
- 建议在虚拟环境中安装
NL Code Reviewer
Automated code review system for validating AI-generated code annotations, assessing code quality, and reviewing Pull Requests with [TAG-AICODE] standard support and Git integration.
Core Capabilities
- Tag Compliance Validation - Ensures [TAG-AICODE] labels are properly formatted and matched
- Code Quality Assessment - Security, maintainability, and best practices analysis
- AI Code Statistics - Calculates AI code percentage, line counts, and block metrics
- Multi-format Reporting - Generates Markdown and JSON review reports
- Pull Request Review - Review PR changes with Git integration and diff analysis
- Unified CLI Interface - Single command (
nlcr) for all review operations
What's New in v2.0
🚀 PR Review Capabilities
- Git Integration: Native support for Git repositories
- Diff Analysis: Parse and analyze unified diff format
- Change-Focused Review: Analyze only changed lines in files
- Branch Comparison: Compare branches for PR review
- Commit Review: Review individual commits
- Staged Changes: Review staged changes before commit
💬 Enhanced Comment System
- Multi-Format Comments: Generate GitHub, GitLab, and Markdown comments
- PR Description Generation: Auto-generate PR descriptions with review summaries
- Structured Feedback: Actionable suggestions with code snippets
- Severity-Based Reporting: CRITICAL, HIGH, MEDIUM, LOW, INFO levels
🛠️ Unified CLI
- Single Entry Point:
nlcrcommand for all operations - Intuitive Subcommands:
validate,analyze,stats,report,pr-review,diff,comments - Consistent Interface: Same options across all commands
When to Use This Skill
Invoke this skill when:
- Reviewing code containing [TAG-AICODE] annotations
- Validating AI-generated code labeling compliance
- Generating code review reports
- Analyzing AI code usage statistics
- Performing security or quality audits
- Checking codebases for tag compliance before deployment
- Reviewing Pull Requests or merge requests
- Analyzing Git diffs and code changes
- Performing pre-commit or pre-push reviews
Decision Tree: Choosing Review Strategy
User Request → What type of review?
├─ Tag Compliance Check → Use: nlcr validate or scripts/validate_tags.py
│ └─ Output: Validation report with issues
│
├─ Code Quality Review → What language?
│ ├─ Python → Load: references/language_guides/python_review.md
│ ├─ JavaScript/TypeScript → Load: references/language_guides/javascript_review.md
│ └─ Other → Load: references/language_guides/general_review.md
│ └─ Use: nlcr analyze or scripts/analyze_code_quality.py
│
├─ Statistical Analysis → Use: nlcr stats or scripts/compute_statistics.py
│ └─ Output: AI usage metrics and ratios
│
├─ Pull Request Review → Use: nlcr pr-review
│ ├─ Staged changes: nlcr pr-review --staged
│ ├─ Branch comparison: nlcr pr-review --base main --head feature
│ └─ Commit review: nlcr pr-review --commit <hash>
│ └─ Output: Comprehensive PR review with focused analysis
│
├─ Full Review Report → Use: nlcr report or scripts/generate_report.py
│ └─ Combines: validation + quality + statistics
│
└─ Comment Generation → Use: nlcr comments
└─ Output: Formatted GitHub/GitLab/Markdown comments
Workflow: Complete Code Review
Phase 1: Preparation
-
Understand Scope
- Identify target files or directories
- Determine programming language(s)
- Clarify review depth (quick check vs. comprehensive)
-
Select Review Components
- Tag validation (always required for tagged code)
- Quality checks (optional, based on requirements)
- Statistical analysis (optional, for reporting)
Phase 2: Tag Compliance Validation
Always start here for code with [TAG-AICODE] annotations.
Tag Format Standard
AI GENERATED CODE START [TAG-AICODE]
<AI-generated code here>
AI GENERATED CODE END [TAG-AICODE]
Validation Rules
- Every START tag must have a matching END tag
- Tags must use exact format:
[TAG-AICODE](case-sensitive) - No nested AI code blocks allowed
- Tags must be on dedicated lines (not inline with code)
Execution
# Run validation with --help first
python scripts/validate_tags.py --help
# Validate single file
python scripts/validate_tags.py path/to/file.py
# Validate directory recursively
python scripts/validate_tags.py --directory path/to/code/ --recursive
# With output format
python scripts/validate_tags.py path/to/file.py --format json
Interpret Results
- PASS: All tags properly formatted
- FAIL: Missing tags, mismatched pairs, formatting errors
- WARNING: Non-standard formatting (e.g., inline tags)
Phase 3: Code Quality Assessment (Optional)
Load language-specific reference guide first:
- Python:
references/language_guides/python_review.md - JavaScript/TypeScript:
references/language_guides/javascript_review.md - Multi-language:
references/language_guides/general_review.md
Quality Dimensions
-
Security Checks
- SQL injection vulnerabilities
- XSS vulnerabilities (web code)
- Hardcoded credentials/keys
- Unsafe deserialization
- Cryptographic issues
-
Maintainability Assessment
- Code complexity (cyclomatic complexity)
- Naming conventions
- Documentation completeness
- Function/module length
- Code duplication
-
Best Practices Verification
- Language-specific idioms
- Design pattern usage
- Error handling
- Testing coverage indicators
- Type safety (for TypeScript)
Execution
# Run quality analysis with --help first
python scripts/analyze_code_quality.py --help
# Analyze single file
python scripts/analyze_code_quality.py path/to/file.py --language python
# Comprehensive analysis with all checks
python scripts/analyze_code_quality.py path/to/file.py --language python --check security,maintainability
# Include AI-tagged code only
python scripts/analyze_code_quality.py path/to/file.py --ai-code-only
Phase 4: Statistical Analysis (Optional)
For reporting AI code usage metrics.
Metrics Calculated
- Total Lines of Code (LOC) - Physical lines (excluding blank/comments)
- AI-Generated Lines - LOC within [TAG-AICODE] blocks
- AI Code Percentage - (AI Lines / Total Lines) × 100
- Number of AI Blocks - Count of tagged code sections
- Average Block Size - AI Lines / Number of Blocks
Execution
# Compute statistics with --help first
python scripts/compute_statistics.py --help
# Single file statistics
python scripts/compute_statistics.py path/to/file.py
# Directory-wide statistics
python scripts/compute_statistics.py --directory path/to/code/ --recursive
Phase 5: Report Generation
Combine all review components into comprehensive report.
Report Formats
- Markdown - Human-readable, suitable for documentation
- JSON - Machine-readable for integration with CI/CD
Execution
# Generate report with --help first
python scripts/generate_report.py --help
# Generate comprehensive Markdown report
python scripts/generate_report.py \
--input path/to/code/ \
--format markdown \
--output review_report.md \
--include validation,quality,statistics
# JSON report for CI/CD integration
python scripts/generate_report.py \
--input path/to/code/ \
--format json \
--output review_results.json \
--include validation,quality,statistics
Progressive Disclosure: Review Depth Options
Level 1: Quick Compliance Check (1-2 minutes)
Use when: Rapid validation before commit/deploy
Steps:
- Run tag validation:
scripts/validate_tags.py - Check for critical security issues only
- Generate simple pass/fail report
Output: Minimal report with compliance status
Level 2: Standard Review (5-10 minutes)
Use when: Regular code review workflow
Steps:
- Run tag validation
- Run quality analysis (security + maintainability)
- Compute statistics
- Generate Markdown report
Output: Comprehensive Markdown report with all findings
Level 3: Deep Analysis (15-30 minutes)
Use when: Critical code, production readiness assessment
Steps:
- Run tag validation
- Run full quality analysis (all dimensions)
- Compute statistics
- Generate JSON reports for CI/CD
- Create actionable recommendations
Output: Detailed multi-format report with prioritized action items
Error Handling and Edge Cases
Common Issues and Solutions
Issue: Missing END Tag
Detection: Unmatched START tag Solution: Report exact line number, provide context, suggest insertion point
Issue: Nested AI Code Blocks
Detection: START tag found within existing AI block Solution: Flag as error, explain nesting prohibition, provide correct pattern
Issue: Mixed Languages in File
Detection: Multiple file extensions or polyglot code
Solution: Use general_review.md guide, run language-specific checks separately
Issue: Large Files (>10,000 lines)
Detection: File size threshold Solution: Process in chunks, provide summary with option to drill down
Issue: No Tags Found
Detection: Zero [TAG-AICODE] markers in file Solution: Confirm if code is human-written, suggest adding tags if AI-generated
Best Practices
For Consistent Reviews
- Always use scripts as black boxes - Run with
--helpfirst, invoke directly without reading source code unless customization is absolutely necessary - Load reference files selectively - Only load language-specific guides when working with that language
- Follow progressive disclosure - Start with quick check, escalate depth based on findings
- Maintain context budget - Report summaries first, provide details on-demand
- Use batch processing for large codebases - Leverage parallelization and incremental reporting (Level 3)
For Effective Tagging
- Tag all AI-generated code - Even partial AI assistance should be marked
- Use dedicated tag lines - Don't inline tags with code
- Match tags precisely - Every START must have END
- Avoid nesting - Keep AI blocks flat and sequential
- Document AI modifications - Use comments to explain AI-assisted changes
For Actionable Reports
- Prioritize findings - Critical > High > Medium > Low
- Provide specific line numbers - Exact location for each issue
- Include code snippets - Show problematic code in context
- Suggest remediation - Don't just identify problems, provide solutions
- Track metrics over time - Compare against previous reviews
Integration with Spec Workflow
This skill integrates with the nl-coder-reviwer project's spec-workflow tools:
- Approval Requests: Use
approvalstool to submit review reports for approval - Implementation Logging: Log review findings using
log-implementationtool - Spec Progress Tracking: Update spec tasks with review results
Example integration:
# After generating review report, request approval
# (uses the spec-workflow MCP server tools)
Troubleshooting
Script Execution Failures
Problem: Script fails with import error
Solution: Install dependencies: pip install -r scripts/requirements.txt
Problem: Permission denied on script execution
Solution: Make scripts executable: chmod +x scripts/*.py
Problem: Out of memory on large files
Solution: Use --chunk-size parameter to process in smaller batches (Level 3)
False Positives
Problem: Valid code flagged as security issue
Solution: Review references/security_patterns.md for exception handling
Problem: AI code not detected Solution: Verify tag format matches standard exactly (case-sensitive)
Reference Files
Load these reference files as needed to inform specific review aspects:
Tag Standards:
- 📋 Tag Standards - Complete [TAG-AICODE] annotation specification
Quality Assessment:
- 🔒 Security Patterns - Common vulnerabilities and detection patterns
- 📊 Quality Metrics - Code quality metric definitions and thresholds
Language-Specific Guides:
- 🐍 Python Review - Python-specific review patterns and best practices
- ⚡ JavaScript/TypeScript Review - JS/TS-specific patterns
- 📝 General Review - Multi-language review guidelines
Reporting:
- 📄 Report Templates - Report format specifications and customization
Checklists:
- ✅ Review Checklist - Comprehensive code review checklist
Example Usage Scenarios
Scenario 1: Pre-Commit Validation
# Quick tag check before git commit
python scripts/validate_tags.py src/main.py
Scenario 2: Pull Request Review
# Comprehensive review of changed files
python scripts/generate_report.py \
--directory src/ \
--format markdown \
--output pr_review.md \
--include validation,quality,statistics
Scenario 3: Compliance Audit
# Full codebase audit with statistics
python scripts/generate_report.py \
--directory . \
--format json \
--output audit_results.json \
--include validation,statistics
Scenario 4: CI/CD Integration
# Automated validation in pipeline
python scripts/validate_tags.py --directory src/ --format json > validation_results.json
# Exit code 0 if pass, 1 if fail
Scenario 5: AI Usage Analysis
# Calculate AI code statistics for reporting
python scripts/compute_statistics.py \
--directory src/ \
--recursive \
--format json > ai_metrics.json
Pull Request Review Workflow (New in v2.0)
Quick Start with Unified CLI
All operations can now be performed through the unified nlcr command:
# Review staged changes before committing
nlcr pr-review --staged
# Review branch comparison for PR
nlcr pr-review --base main --head feature/new-feature
# Review specific commit
nlcr pr-review --commit abc123
# Generate GitHub-formatted comments
nlcr pr-review --base main --head feature --format json > review.json
nlcr comments --input review.json --format github --output pr_comments.md
PR Review Features
1. Staged Changes Review
Review changes before committing:
nlcr pr-review --staged
2. Branch Comparison
Compare two branches for PR review:
nlcr pr-review --base main --head feature-branch
3. Commit Review
Review a specific commit:
nlcr pr-review --commit <commit-hash>
4. Customized Review
Control what aspects to review:
# Only security checks
nlcr pr-review --staged --check security --no-tags --no-stats
# Skip quality analysis
nlcr pr-review --base main --head feature --no-quality
# Review only AI-tagged code
nlcr analyze src/main.py --ai-code-only
Comment Generation
Generate GitHub Comments
# Run review and save as JSON
nlcr pr-review --base main --head feature --format json --output review.json
# Generate GitHub-formatted comments
nlcr comments --input review.json --format github --output comments.md
Generate PR Description
# Auto-generate PR description with review summary
nlcr comments --input review.json --pr-description --output pr_description.md
Integration with CI/CD
Pre-commit Hook
# .git/hooks/pre-commit
#!/bin/bash
nlcr pr-review --staged --format json > review.json
if [ $? -ne 0 ]; then
echo "Code review failed. Please review the issues."
cat review.json
exit 1
fi
GitHub Actions Integration
# .github/workflows/code-review.yml
name: Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Install nl-code-reviewer
run: |
cd nl-code-reviewer
pip install -r scripts/requirements.txt
- name: Run PR Review
run: |
nlcr pr-review --base ${{ github.base_ref }} --head HEAD --format json --output review.json
- name: Generate Comments
run: |
nlcr comments --input review.json --format github --output comments.md
- name: Post Comments
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const comments = fs.readFileSync('comments.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comments
});
CLI Command Reference
Unified CLI: nlcr
nlcr validate
Validate [TAG-AICODE] annotations:
nlcr validate <file> [options]
nlcr validate <directory> --directory --recursive [options]
Options:
--directory, -d: Treat input as directory--recursive, -r: Process subdirectories--format, -f: Output format (text, json)--strict, -s: Treat warnings as errors--output, -o: Output file
nlcr analyze
Analyze code quality:
nlcr analyze <file> --language <lang> [options]
Options:
--language, -l: Programming language (python, javascript, typescript, general)--check, -c: Quality checks (security, maintainability, best_practices)--ai-code-only: Only analyze AI-tagged code--format, -f: Output format (text, json)--output, -o: Output file
nlcr stats
Compute AI code statistics:
nlcr stats <file|directory> [options]
Options:
--directory, -d: Treat input as directory--recursive, -r: Process subdirectories--format, -f: Output format (text, json)--output, -o: Output file
nlcr report
Generate comprehensive report:
nlcr report --input <path> [options]
Options:
--input, -i: Input path--format, -f: Report format (markdown, json)--output, -o: Output file--include, -I: Components to include (validation, quality, statistics)
nlcr pr-review
Review Pull Request changes:
nlcr pr-review --base <branch> --head <branch> [options]
nlcr pr-review --staged [options]
nlcr pr-review --commit <hash> [options]
Options:
--base, -b: Base branch/commit--head, -H: Head branch/commit--commit, -c: Review specific commit--staged, -s: Review staged changes--repo, -r: Path to Git repository--language, -l: Programming language--check: Quality checks to perform--no-tags: Skip tag validation--no-quality: Skip quality analysis--no-stats: Skip AI statistics--format, -f: Output format (text, json)--output, -o: Output file
nlcr diff
Parse Git diff:
git diff HEAD~1 | nlcr diff
nlcr diff --file <diff-file> [options]
Options:
--file, -f: Read diff from file--format, -F: Output format (summary, detailed, json)
nlcr comments
Generate formatted comments:
nlcr comments --input <review.json> [options]
Options:
--input, -i: Input JSON file--format, -f: Comment format (markdown, github, gitlab, json)--output, -o: Output file--pr-description: Generate PR description instead
nlcr check-update
Check for nl-code-reviewer updates:
nlcr check-update [options]
Options:
--force, -f: Force check (ignore daily check limit)--check, -c: Only check, do not ask to install--remote, -r: Remote repository name (default: origin)--branch, -b: Branch name (default: master)
Behavior:
- Interactive mode (default): Check updates and ask user if they want to install
- Check-only mode (
--check): Only display version information, no interaction - Auto-check: Runs automatically when using any nlcr command (once per day)
- Skip auto-check: Use
--skip-update-checkflag or setNLCR_SKIP_UPDATE_CHECKenvironment variable
Examples:
# Interactive check and update
nlcr check-update
# Force check (ignore daily limit)
nlcr check-update --force
# Check only, don't ask to install
nlcr check-update --check
# Skip auto-check for other commands
nlcr validate file.py --skip-update-check
Legacy Script Interface
All individual scripts remain accessible for backward compatibility:
# Tag validation
python scripts/validate_tags.py <file>
# Code quality analysis
python scripts/analyze_code_quality.py <file> --language python
# Statistics
python scripts/compute_statistics.py <file>
# Report generation
python scripts/generate_report.py --input <path>
# PR review
python scripts/pr_reviewer.py --base main --head feature
# Diff parsing
python scripts/diff_parser.py --file changes.diff
# Comment generation
python scripts/review_comments.py --input review.json --format github
