Review Before Committing
Run Guardian on changed files before git commit. Catch violations early.
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.
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:
Typical usage:
# Review a TypeScript filecortex-tms review src/components/Button.tsx
# 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## [...]<file>Path to the file to review (required).
Supported file types:
.ts, .tsx, .js, .jsx).py).rs).go)Examples:
# Review TypeScript filecortex-tms review src/utils/validator.ts
# Review componentcortex-tms review src/components/LoginForm.tsx
# Review Python modulecortex-tms review api/services/auth.pyPath resolution:
-p, --provider <provider>LLM provider to use.
Valid values: openai | anthropic
Default: anthropic
Examples:
# Use Anthropic (default)cortex-tms review src/file.ts
# Use OpenAIcortex-tms review src/file.ts --provider openaiProvider comparison:
| Provider | Default Model | Cost/1M tokens | Strengths |
|---|---|---|---|
| Anthropic | claude-3-5-sonnet-20241022 | $3 in, $15 out | Better at code reasoning, context understanding |
| OpenAI | gpt-4-turbo-preview | $10 in, $30 out | Faster responses, wider availability |
-m, --model <model>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:
# Use Claude Opus for complex analysiscortex-tms review src/core/engine.ts --model claude-opus-4-5-20251101
# Use GPT-4o for faster analysiscortex-tms review src/utils.ts --provider openai --model gpt-4o
# Use Haiku for quick/cheap reviewscortex-tms review src/types.ts --model claude-3-haiku-20240307--api-key <key>API key for LLM provider (alternative to environment variable).
Security warning: Only use in secure environments. Prefer environment variables.
Examples:
# Pass API key directlycortex-tms review src/file.ts --api-key sk-ant-xxx
# Better: Use environment variableexport ANTHROPIC_API_KEY=sk-ant-xxxcortex-tms review src/file.ts1. Get API Key:
2. Set Environment Variable:
# 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-xxx3. Verify:
echo $ANTHROPIC_API_KEY # Should show your key
# Or test with Guardiancortex-tms review src/test.ts# Should not prompt for API key1. Get API Key:
2. Set Environment Variable:
# Linux/macOSexport OPENAI_API_KEY=sk-xxx
# Windows (PowerShell)$env:OPENAI_API_KEY="sk-xxx"3. Test:
cortex-tms review src/test.ts --provider openaiGuardian requires a Cortex TMS project with pattern documentation:
Mandatory:
docs/core/PATTERNS.md - Coding patterns and conventionsOptional but recommended:
docs/core/DOMAIN-LOGIC.md - Business rules and constraintsCheck requirements:
# Verify TMS files existls docs/core/PATTERNS.md docs/core/DOMAIN-LOGIC.md
# If missing, initialize TMScortex-tms init --scope standard# Review a single filecortex-tms review src/services/auth.tsOutput:
๐ก๏ธ 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:
cortex-tms review src/utils/helpers.tsOutput:
## 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:```typescriptexport 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 filesFILES=$(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 donefiResult: 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 doneAdd API key to GitHub Secrets:
ANTHROPIC_API_KEY or OPENAI_API_KEYReview multiple files:
# Loop through filesfor file in src/**/*.ts; do echo "Reviewing: $file" cortex-tms review "$file"done
# Or use findfind 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 $FAILEDGuardian provides three levels of assessment:
โ Compliant: No violations
โ ๏ธ Minor Issues: Non-critical violations
โ Major Violations: Critical issues
Each violation includes:
1. Pattern Reference
Pattern Violation: Error HandlingWhich pattern from PATTERNS.md was violated
2. Line Number
Line: 42Approximate location (AI-inferred, may be ยฑ2 lines)
3. Issue Description
Issue: Catching generic Error instead of specific exception typesWhatโs wrong with the current code
4. Recommendation
Recommendation: Catch specific exceptions (ValidationError, NetworkError)per PATTERNS.md Section 8How to fix it with reference to documentation
Guardian reports token consumption:
๐ Tokens: 2,345 total (1,800 prompt + 545 completion)Typical costs (Anthropic Claude 3.5 Sonnet):
Cost optimization:
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:
# Initialize TMScortex-tms init --scope standard
# Or check working directorypwd # Should be project rootcd /path/to/projectcortex-tms review src/file.tsProblem: Invalid file path
โ Error: File not found: src/nonexistent.tsSolution:
# Verify file existsls src/nonexistent.ts
# Use correct pathcortex-tms review src/existing-file.ts
# For files with spaces, use quotescortex-tms review "src/my file.ts"Problem: No API key configured
Solution:
# Set environment variableexport ANTHROPIC_API_KEY=sk-ant-xxx
# Or pass directlycortex-tms review src/file.ts --api-key sk-ant-xxx
# Verify environment variableecho $ANTHROPIC_API_KEYProblem: Too many requests to LLM provider
โ Error: Anthropic API error: 429 rate_limit_errorSolutions:
Wait and retry:
sleep 60cortex-tms review src/file.tsBatch reviews:
# Don't review every file individually# Review all changed files in one PR review cycleUpgrade API tier: Check provider dashboard for rate limits
Problem: Incorrect or expired API key
โ Error: Anthropic API error: 401 Invalid API keySolution:
# Check key formatecho $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 variableexport ANTHROPIC_API_KEY=sk-ant-NEW-KEYReview 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.
Make Code Changes
# Implement featurevim src/features/auth.tsRun Guardian
# Review changed filecortex-tms review src/features/auth.tsFix Violations
Re-Review
# Verify compliancecortex-tms review src/features/auth.ts# Should show: โ
CompliantCommit
git add src/features/auth.tsgit commit -m "feat: add authentication"Discover New Pattern
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 invalidTest Guardian
# Guardian now enforces this patterncortex-tms review src/routes/admin.ts# Will catch missing auth checksGuardian uses built-in prompts optimized for pattern detection. Custom prompt support planned for v2.8.
Compare analysis quality:
# Test with both providerscortex-tms review src/complex.ts --provider anthropic > anthropic-review.txtcortex-tms review src/complex.ts --provider openai > openai-review.txt
# Compare resultsdiff anthropic-review.txt openai-review.txtTrack Guardian API costs:
# Extract token usage from review outputcortex-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| Code | Meaning | Scenario |
|---|---|---|
0 | Success | Review completed (violations may exist but reported) |
1 | Error | Missing 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):
Planned Improvements (v2.8+):
cortex-tms init - Initialize TMS (creates PATTERNS.md)cortex-tms validate - Validate TMS file integritycortex-tms status - View project state