360 Secure SkillHub
360 安全技能中心

Nl Code Reviewer

本地 Python CLI 工具包,可校验 AI 代码标签合规性、分析代码质量与安全模式、统计 AI 代码占比,并基于 Git diff 审查 PR 变更,输出 Markdown/JSON 报告及 GitHub/GitLab 评论。

FloatingClouds
FloatingClouds
热度 19.44
最近更新 2026-03-19 20:40:34
分类:开发依赖:代码执行 / 读写文件 / 第三方 API应用场景:代码审查 / 报告撰写 / 工作流 / DevOps ...

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add nl-code-reviewer
Metadata
name
nl-code-reviewer
version
2.3.2
description
Comprehensive code review toolkit for AI-generated code compliance checking, quality assessment, statistical reporting, and Pull Request review with [TAG-AICODE] annotation support. Use when reviewing code with AI-generated code tags, validating annotation standards, generating code review reports, analyzing AI code usage statistics, reviewing Pull Requests, or performing Git-based code reviews in Python, JavaScript/TypeScript, or multi-language codebases.
license
MIT
author
OpenClaw Team
category
code-quality
tags
["code-review","ai-code","compliance","security","quality-assurance","git","pull-request"]
minOpenClawVersion
2025.1.0
repository
https://github.com/openclaw/nl-code-reviewer

安全说明

数据安全

  • 本工具在本地运行,不上传代码到外部服务器
  • 所有扫描结果仅存储在用户本地文件系统
  • 支持离线使用,无需网络连接(除自动更新检查外)

权限要求

  • 文件系统读取权限(扫描代码文件)
  • 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

  1. Tag Compliance Validation - Ensures [TAG-AICODE] labels are properly formatted and matched
  2. Code Quality Assessment - Security, maintainability, and best practices analysis
  3. AI Code Statistics - Calculates AI code percentage, line counts, and block metrics
  4. Multi-format Reporting - Generates Markdown and JSON review reports
  5. Pull Request Review - Review PR changes with Git integration and diff analysis
  6. 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: nlcr command 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

  1. Understand Scope

    • Identify target files or directories
    • Determine programming language(s)
    • Clarify review depth (quick check vs. comprehensive)
  2. 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

  1. Security Checks

    • SQL injection vulnerabilities
    • XSS vulnerabilities (web code)
    • Hardcoded credentials/keys
    • Unsafe deserialization
    • Cryptographic issues
  2. Maintainability Assessment

    • Code complexity (cyclomatic complexity)
    • Naming conventions
    • Documentation completeness
    • Function/module length
    • Code duplication
  3. 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:

  1. Run tag validation: scripts/validate_tags.py
  2. Check for critical security issues only
  3. 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:

  1. Run tag validation
  2. Run quality analysis (security + maintainability)
  3. Compute statistics
  4. 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:

  1. Run tag validation
  2. Run full quality analysis (all dimensions)
  3. Compute statistics
  4. Generate JSON reports for CI/CD
  5. 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

  1. Always use scripts as black boxes - Run with --help first, invoke directly without reading source code unless customization is absolutely necessary
  2. Load reference files selectively - Only load language-specific guides when working with that language
  3. Follow progressive disclosure - Start with quick check, escalate depth based on findings
  4. Maintain context budget - Report summaries first, provide details on-demand
  5. Use batch processing for large codebases - Leverage parallelization and incremental reporting (Level 3)

For Effective Tagging

  1. Tag all AI-generated code - Even partial AI assistance should be marked
  2. Use dedicated tag lines - Don't inline tags with code
  3. Match tags precisely - Every START must have END
  4. Avoid nesting - Keep AI blocks flat and sequential
  5. Document AI modifications - Use comments to explain AI-assisted changes

For Actionable Reports

  1. Prioritize findings - Critical > High > Medium > Low
  2. Provide specific line numbers - Exact location for each issue
  3. Include code snippets - Show problematic code in context
  4. Suggest remediation - Don't just identify problems, provide solutions
  5. 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 approvals tool to submit review reports for approval
  • Implementation Logging: Log review findings using log-implementation tool
  • 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:

Language-Specific Guides:

Reporting:

Checklists:


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-check flag or set NLCR_SKIP_UPDATE_CHECK environment 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