Skip to content

cortex-tms review

The cortex-tms review command (Guardian) analyzes code files against your project’s documented patterns and domain logic using AI. It catches architectural violations before they reach production.

Terminal window
cortex-tms review <file> [options]

Guardian: Pattern Violation Detection. Guardian uses LLMs to review code against your project-specific standards documented in PATTERNS.md and DOMAIN-LOGIC.md. Unlike generic linters, Guardian understands:

  • Project Context: Reviews against YOUR architectural patterns, not generic rules
  • Business Logic: Validates domain rules and constraints specific to your app
  • Semantic Analysis: Catches violations that static analysis tools miss
  • Line-Level Precision: References exact line numbers in violation reports

Typical usage:

Terminal window
# Review a TypeScript file
cortex-tms review src/components/Button.tsx
# Safe Mode: only high-confidence violations
cortex-tms review src/components/Button.tsx --safe
# Output:
# 🛡️ Guardian Code Review
#
# 📖 Reading project patterns...
# 🤖 Analyzing code with anthropic ...
#
# ✅ Analysis Complete
#
# ## Summary
# ⚠️ Minor Issues (2 violations)
#
# ## Violations
#
# ### 1. Pattern Violation: Component Naming
# **Line**: 15
# **Issue**: Component uses PascalCase for internal helper function
# **Recommendation**: Use camelCase for non-exported functions per PATTERNS.md
# **Confidence**: 85%
#
# [...]

Path to the file to review (required).

Supported file types:

  • TypeScript/JavaScript (.ts, .tsx, .js, .jsx)
  • Python (.py)
  • Rust (.rs)
  • Go (.go)
  • Any text-based source code

Examples:

Terminal window
# Review TypeScript file
cortex-tms review src/utils/validator.ts
# Review component
cortex-tms review src/components/LoginForm.tsx
# Review Python module
cortex-tms review api/services/auth.py

Path resolution:

  • Relative to current working directory
  • Absolute paths supported

LLM provider to use.

Valid values: openai | anthropic

Default: anthropic

Examples:

Terminal window
# Use Anthropic (default)
cortex-tms review src/file.ts
# Use OpenAI
cortex-tms review src/file.ts --provider openai

Provider comparison:

ProviderDefault ModelCost/1M tokensStrengths
Anthropicclaude-3-5-sonnet-20241022$3 in, $15 outBetter at code reasoning, context understanding
OpenAIgpt-4-turbo-preview$10 in, $30 outFaster responses, wider availability

Specific model to use (overrides provider default).

Anthropic models:

  • claude-3-5-sonnet-20241022 (default, recommended)
  • claude-opus-4-5-20251101 (most capable, slower)
  • claude-3-haiku-20240307 (fastest, cheapest)

OpenAI models:

  • gpt-4-turbo-preview (default)
  • gpt-4o (faster, multimodal)
  • gpt-3.5-turbo (cheapest, less accurate)

Examples:

Terminal window
# Use Claude Opus for complex analysis
cortex-tms review src/core/engine.ts --model claude-opus-4-5-20251101
# Use GPT-4o for faster analysis
cortex-tms review src/utils.ts --provider openai --model gpt-4o
# Use Haiku for quick/cheap reviews
cortex-tms review src/types.ts --model claude-3-haiku-20240307

API key for LLM provider (alternative to environment variable).

Security warning: Only use in secure environments. Prefer environment variables.

Examples:

Terminal window
# Pass API key directly
cortex-tms review src/file.ts --api-key sk-ant-xxx
# Better: Use environment variable
export ANTHROPIC_API_KEY=sk-ant-xxx
cortex-tms review src/file.ts

Safe Mode: Filter violations to only show high-confidence issues (≥70%).

Purpose: Reduce false positive noise and increase trust in Guardian’s recommendations.

How it works:

  • Guardian assigns confidence scores (0-1) to each violation
  • Safe Mode filters to only show violations with ≥70% confidence
  • Lower confidence violations are hidden but counted in summary
  • Backwards compatible (works with older responses without confidence scores)

Confidence Scale:

  • 0.9-1.0: Very high - Clear, unambiguous violation
  • 0.7-0.9: High - Likely violation, context strongly supports it
  • 0.5-0.7: Medium - Possible violation, some ambiguity (filtered in Safe Mode)
  • 0.0-0.5: Low - Uncertain, may be false positive (filtered in Safe Mode)

Examples:

Terminal window
# Normal mode (shows all violations)
cortex-tms review src/complex.ts
# Safe Mode (only high-confidence violations)
cortex-tms review src/complex.ts --safe

Example Output (Safe Mode):

🛡️ Guardian Code Review
✅ Analysis Complete
## Summary
✅ Compliant - No high-confidence violations found
(Safe Mode filtered 2 low-confidence issues)
## Positive Observations
✅ Good error handling patterns

When to use:

  • New projects: Start with Safe Mode to build trust in Guardian
  • Code reviews: Focus on clear violations, ignore ambiguous cases
  • CI/CD: Fail builds only on high-confidence violations
  • Learning: Understand what Guardian considers “certain” vs “possible”

When NOT to use:

  • Comprehensive audits: Want to see all potential issues
  • Pattern documentation: Testing if patterns are clear enough
  • Debugging Guardian: Investigating false positives

1. Get API Key:

2. Set Environment Variable:

Terminal window
# Linux/macOS (add to ~/.bashrc or ~/.zshrc)
export ANTHROPIC_API_KEY=sk-ant-xxx
# Windows (PowerShell)
$env:ANTHROPIC_API_KEY="sk-ant-xxx"
# Windows (CMD)
set ANTHROPIC_API_KEY=sk-ant-xxx

3. Verify:

Terminal window
echo $ANTHROPIC_API_KEY # Should show your key
# Or test with Guardian
cortex-tms review src/test.ts
# Should not prompt for API key

Guardian requires a Cortex TMS project with pattern documentation:

Mandatory:

  • docs/core/PATTERNS.md - Coding patterns and conventions

Optional but recommended:

  • docs/core/DOMAIN-LOGIC.md - Business rules and constraints

Check requirements:

Terminal window
# Verify TMS files exist
ls docs/core/PATTERNS.md docs/core/DOMAIN-LOGIC.md
# If missing, initialize TMS
cortex-tms init --scope standard

Terminal window
# Review a single file
cortex-tms review src/services/auth.ts
# Safe Mode: only high-confidence violations
cortex-tms review src/services/auth.ts --safe

Output:

🛡️ Guardian Code Review
📖 Reading project patterns...
🤖 Analyzing code with anthropic ...
✅ Analysis Complete
## Summary
✅ Compliant - No violations found
## Positive Observations
1. **Pattern Compliance**: All functions follow the documented naming
conventions from PATTERNS.md
2. **Error Handling**: Consistent error handling using try/catch blocks
as specified in the Error Handling pattern
3. **Type Safety**: Proper TypeScript types used throughout
📊 Tokens: 2,345 total (1,800 prompt + 545 completion)

File: src/utils/helpers.ts

// VIOLATION: Uses export default (not allowed per PATTERNS.md)
export default function ParseUserInput(input: string) {
return input.trim().toLowerCase();
}

Guardian Review:

Terminal window
cortex-tms review src/utils/helpers.ts

Output:

## Summary
❌ Major Violations (2 issues)
## Violations
### 1. Pattern Violation: No Default Exports
**Line**: 2
**Issue**: Using `export default` violates Pattern 5 (Named Exports Only)
**Recommendation**: Change to named export:
```typescript
export function parseUserInput(input: string) {
return input.trim().toLowerCase();
}

Line: 2 Issue: Function name uses PascalCase (ParseUserInput) instead of camelCase Recommendation: Rename to parseUserInput per PATTERNS.md Section 2

---
### Pre-Commit Hook Integration
**Use Guardian in Git hooks**:
**.husky/pre-commit**:
```bash
#!/bin/bash
# Get staged .ts files
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.ts$')
if [ -n "$FILES" ]; then
echo "🛡️ Running Guardian on staged files..."
for FILE in $FILES; do
echo "Reviewing: $FILE"
cortex-tms review "$FILE" || exit 1
done
fi

Result: All commits must pass Guardian review


GitHub Actions Example:

.github/workflows/guardian.yml:

name: Guardian Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
- name: Install Cortex TMS
run: npm install -g cortex-tms
- name: Guardian Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# Review all changed files in PR
gh pr diff --name-only | while read file; do
if [[ $file == *.ts || $file == *.tsx ]]; then
echo "Reviewing: $file"
cortex-tms review "$file"
fi
done

Add API key to GitHub Secrets:

  1. Repository → Settings → Secrets
  2. Add ANTHROPIC_API_KEY or OPENAI_API_KEY

Review multiple files:

Terminal window
# Loop through files
for file in src/**/*.ts; do
echo "Reviewing: $file"
cortex-tms review "$file"
done
# Or use find
find src -name "*.ts" -exec cortex-tms review {} \;

Batch script (review-all.sh):

#!/bin/bash
FILES=$(find src -name "*.ts" -o -name "*.tsx")
FAILED=0
for FILE in $FILES; do
echo "==> Reviewing: $FILE"
if ! cortex-tms review "$FILE"; then
FAILED=$((FAILED + 1))
fi
echo ""
done
echo "Review complete: $FAILED violations found"
exit $FAILED

Guardian provides three levels of assessment:

✅ Compliant: No violations

  • Code follows all documented patterns
  • Ready for merge
  • Example: Utility functions following naming conventions

⚠️ Minor Issues: Non-critical violations

  • Code works but doesn’t match preferred style
  • Should fix but not blocking
  • Example: Missing JSDoc comment on public function

❌ Major Violations: Critical issues

  • Breaks architectural rules or domain logic
  • Must fix before merge
  • Example: Skipping authentication check, using deprecated pattern

Each violation includes:

1. Pattern Reference

Pattern Violation: Error Handling

Which pattern from PATTERNS.md was violated

2. Line Number

Line: 42

Approximate location (AI-inferred, may be ±2 lines)

3. Issue Description

Issue: Catching generic Error instead of specific exception types

What’s wrong with the current code

4. Recommendation

Recommendation: Catch specific exceptions (ValidationError, NetworkError)
per PATTERNS.md Section 8

How to fix it with reference to documentation

5. Confidence Score (when available)

Confidence: 85%

How certain Guardian is about this violation (0-100%). Use --safe to filter to ≥70%.


Guardian reports token consumption:

📊 Tokens: 2,345 total (1,800 prompt + 545 completion)

Typical costs (Anthropic Claude 3.5 Sonnet):

  • Small file (<200 lines): ~$0.01
  • Medium file (200-500 lines): ~$0.02
  • Large file (500-1000 lines): ~$0.05

Cost optimization:

  • Review changed files only (not entire codebase)
  • Use Haiku model for quick checks
  • Batch reviews in CI/CD (review all PR files once)

Problem: Not running from Cortex TMS project or missing documentation

❌ Error: PATTERNS.md not found at docs/core/PATTERNS.md
Guardian requires a Cortex TMS project with pattern documentation.
Run cortex-tms init to set up TMS files.

Solution:

Terminal window
# Initialize TMS
cortex-tms init --scope standard
# Or check working directory
pwd # Should be project root
cd /path/to/project
cortex-tms review src/file.ts

Problem: Invalid file path

❌ Error: File not found: src/nonexistent.ts

Solution:

Terminal window
# Verify file exists
ls src/nonexistent.ts
# Use correct path
cortex-tms review src/existing-file.ts
# For files with spaces, use quotes
cortex-tms review "src/my file.ts"

Problem: No API key configured

Solution:

Terminal window
# Set environment variable
export ANTHROPIC_API_KEY=sk-ant-xxx
# Or pass directly
cortex-tms review src/file.ts --api-key sk-ant-xxx
# Verify environment variable
echo $ANTHROPIC_API_KEY

Problem: Too many requests to LLM provider

❌ Error: Anthropic API error: 429 rate_limit_error

Solutions:

  1. Wait and retry:

    Terminal window
    sleep 60
    cortex-tms review src/file.ts
  2. Batch reviews:

    Terminal window
    # Don't review every file individually
    # Review all changed files in one PR review cycle
  3. Upgrade API tier: Check provider dashboard for rate limits


Problem: Incorrect or expired API key

❌ Error: Anthropic API error: 401 Invalid API key

Solution:

Terminal window
# Check key format
echo $ANTHROPIC_API_KEY
# Should start with: sk-ant-xxx (Anthropic) or sk-xxx (OpenAI)
# Generate new key
# Visit console.anthropic.com or platform.openai.com
# Update environment variable
export ANTHROPIC_API_KEY=sk-ant-NEW-KEY

Review Before Committing

Run Guardian on changed files before git commit. Catch violations early.

Use in Pre-Commit Hooks

Automate Guardian in Git hooks. Enforces pattern compliance on every commit.

Target Changed Files Only

Don’t review entire codebase. Review files changed in PR to save costs.

Update PATTERNS.md Regularly

Keep pattern documentation current. Guardian is only as good as your docs.


  1. Make Code Changes

    Terminal window
    # Implement feature
    vim src/features/auth.ts
  2. Run Guardian

    Terminal window
    # Review changed file
    cortex-tms review src/features/auth.ts
  3. Fix Violations

    • Address each violation reported
    • Update code to match patterns
  4. Re-Review

    Terminal window
    # Verify compliance
    cortex-tms review src/features/auth.ts
    # Should show: ✅ Compliant
  5. Commit

    Terminal window
    git add src/features/auth.ts
    git commit -m "feat: add authentication"

  1. Discover New Pattern

    • Implement feature
    • Identify reusable pattern
  2. Document in PATTERNS.md

    ## Pattern 11: Authentication Flow
    **When to use**: All routes requiring user authentication
    **Canonical example**: `src/middleware/auth.ts:15-30`
    **Implementation**:
    - Check JWT token in request headers
    - Validate signature
    - Attach user to request context
    - Return 401 if invalid
  3. Test Guardian

    Terminal window
    # Guardian now enforces this pattern
    cortex-tms review src/routes/admin.ts
    # Will catch missing auth checks

Guardian uses built-in prompts optimized for pattern detection. Custom prompt support planned for a future release. See roadmap for upcoming features.


Compare analysis quality:

Terminal window
# Test with both providers
cortex-tms review src/complex.ts --provider anthropic > anthropic-review.txt
cortex-tms review src/complex.ts --provider openai > openai-review.txt
# Compare results
diff anthropic-review.txt openai-review.txt

Track Guardian API costs:

Terminal window
# Extract token usage from review output
cortex-tms review src/file.ts | grep "Tokens:"
# Calculate cost (example: Claude 3.5 Sonnet)
# $3 per 1M input tokens, $15 per 1M output tokens
# 1,800 input + 545 output = $0.0054 + $0.0082 = ~$0.014

CodeMeaningScenario
0SuccessReview completed (violations may exist but reported)
1ErrorMissing PATTERNS.md, file not found, API error

Note: Guardian doesn’t fail builds on violations. It reports them. Integrate with CI to enforce.


Current Limitations (v2.7):

  1. Single File Review: Guardian reviews one file at a time (no cross-file analysis)
  2. AI Accuracy: ~70% accuracy on pattern violations (false positives/negatives possible)
  3. No Auto-Fix: Guardian reports violations but doesn’t fix code
  4. Line Numbers: Approximate (AI-inferred, may be ±2 lines off)

Planned Improvements (upcoming):

  • GitHub Action with PR comments
  • Cross-file analysis
  • Auto-fix suggestions with diffs
  • Hosted service (no API key needed)