Skip to content

juspay/yama

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

βš”οΈ Yama

Enterprise-grade Pull Request automation toolkit with AI-powered code review and description enhancement

Version License TypeScript

🎯 What is Yama?

Yama is the code quality judge that combines and optimizes the functionality from pr-police.js and pr-describe.js into a unified, enterprise-grade toolkit. It provides AI-powered code review and intelligent description enhancement with 90% fewer API calls through unified context gathering.

Named after the Hindu deity of justice and death, Yama judges code quality and ensures only the worthy changes pass through.


✨ Core Features

πŸ” AI-Powered Code Review

  • πŸ”’ Security Analysis: SQL injection, XSS, hardcoded secrets detection
  • ⚑ Performance Review: N+1 queries, memory leaks, algorithm efficiency
  • πŸ—οΈ Code Quality: SOLID principles, maintainability, best practices
  • πŸ’¬ Smart Comments: Contextual inline comments with actionable suggestions
  • πŸ“Š Severity Levels: CRITICAL, MAJOR, MINOR, SUGGESTION with intelligent categorization

πŸ“ Intelligent Description Enhancement

  • πŸ“Ž Content Preservation: Never removes screenshots, links, or existing explanations
  • πŸ“‹ Required Sections: Configurable sections (Changelog, Test Cases, Config Changes, etc.)
  • πŸ€– AI Enhancement: Automatically improves incomplete descriptions while preserving content
  • 🧠 Project Context: Uses memory-bank and .clinerules for contextual enhancement

πŸš€ Unified Context System (Core Innovation)

  • ⚑ One-Time Gathering: Collect all PR context once, reuse across all operations
  • 🧠 Smart Diff Strategy: Automatically chooses whole diff vs file-by-file based on PR size
  • πŸ’Ύ Intelligent Caching: 90% reduction in API calls through multi-layer caching
  • πŸ“¦ Batch Processing: Process large PRs efficiently with intelligent file batching

πŸ—οΈ Enterprise Ready

  • 🌐 Multi-Platform: Bitbucket Server (Phase 1), GitHub/GitLab (Future phases)
  • πŸ“˜ Full TypeScript: Complete type safety and excellent developer experience
  • βš™οΈ Highly Configurable: YAML/JSON configuration with validation and hot-reload
  • πŸ› οΈ CLI + API: Use as command-line tool or programmatic library

πŸš€ Performance Benefits

Metric Individual Scripts Yama Improvement
API Calls ~50-100 per operation ~10-20 total 90% reduction
Execution Time 3-5 minutes each 2-3 minutes total 3x faster
Memory Usage High duplication Shared context 50% reduction
Cache Efficiency None 80-90% hit ratio New capability
Large PRs (40+ files) Often fails/timeouts Intelligent batching Reliable processing

πŸ“¦ Installation

# Install globally for CLI usage
npm install -g @juspay/yama

# Or install locally for programmatic usage
npm install @juspay/yama

⚑ Quick Start

1. Initialize Configuration

# Interactive setup
yama init --interactive

# Quick setup with defaults
yama init

2. Basic Usage

Unified Processing (Recommended)

# Process PR with both review and description enhancement
yama process --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth

# Process specific operations
yama process --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth --operations review,enhance

Individual Operations

# Code review only
yama review --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth

# Description enhancement only
yama enhance --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth

Backward Compatibility

# Still works exactly like pr-police.js
yama police --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth

# Still works exactly like pr-describe.js / pr-scribe.js
yama scribe --workspace YOUR_WORKSPACE --repository my-repo --branch feature/auth

πŸ”§ Advanced Configuration

File Exclusion Patterns

# Exclude specific file types and directories
yama process \
  --workspace YOUR_WORKSPACE \
  --repository my-repo \
  --branch feature/auth \
  --exclude "*.lock,*.svg,*.min.js,dist/**,node_modules/**,coverage/**"

# Different exclusions for different operations
yama review --exclude "*.lock,*.svg,**/*.test.js"
yama enhance --exclude "*.md"  # Don't process existing markdown files

Context and Performance Tuning

# More context lines for better AI analysis
yama review --context-lines 5 --exclude "*.lock"

# Dry run to preview changes
yama process --dry-run --verbose

# Force cache refresh
yama process --force-refresh

βš™οΈ Configuration File

Create yama.config.yaml in your project root:

# AI Provider Configuration
ai:
  provider: "auto" # auto, google-ai, openai, anthropic
  enableFallback: true
  enableAnalytics: true
  timeout: "5m"
  temperature: 0.7

# Git Platform Configuration
git:
  platform: "bitbucket"
  credentials:
    username: "${BITBUCKET_USERNAME}"
    token: "${BITBUCKET_TOKEN}"
    baseUrl: "https://your-bitbucket-server.com"
  defaultWorkspace: "${DEFAULT_WORKSPACE}"

# Feature Configuration
features:
  codeReview:
    enabled: true
    severityLevels: ["CRITICAL", "MAJOR", "MINOR", "SUGGESTION"]
    excludePatterns:
      - "*.lock"
      - "*.svg"
      - "*.min.js"
      - "node_modules/**"
      - "dist/**"
      - "build/**"
      - "coverage/**"
    contextLines: 3

    # Custom AI Prompts for Code Review (Advanced)
    systemPrompt: |
      You are an Expert Security Code Reviewer focusing on enterprise standards.
      Prioritize security vulnerabilities, performance issues, and code quality.
      Provide actionable feedback with specific examples and solutions.

    focusAreas:
      - "πŸ”’ Security Analysis (CRITICAL PRIORITY)"
      - "⚑ Performance Review"
      - "πŸ—οΈ Code Quality & Best Practices"
      - "πŸ§ͺ Testing & Error Handling"
      - "πŸ“– Documentation & Maintainability"

  descriptionEnhancement:
    enabled: true
    preserveContent: true # NEVER remove existing content
    requiredSections:
      # Default sections
      - key: "changelog"
        name: "πŸ“‹ Changelog (Modules Modified)"
        required: true

      - key: "testcases"
        name: "πŸ§ͺ Test Cases (What to be tested)"
        required: true

      - key: "config_changes"
        name: "βš™οΈ Config Changes (CAC/Service Config)"
        required: true

      # Optional custom sections
      - key: "breaking_changes"
        name: "⚠️ Breaking Changes"
        required: false

      - key: "migration_notes"
        name: "πŸ”„ Migration Notes"
        required: false

      - key: "performance_impact"
        name: "⚑ Performance Impact"
        required: false

      - key: "security_considerations"
        name: "πŸ”’ Security Considerations"
        required: false

    # Custom AI Prompts and Templates (Advanced)
    systemPrompt: |
      You are an Expert Technical Writer specializing in pull request documentation.
      Focus on clarity, completeness, and helping reviewers understand the changes.
      CRITICAL: Return ONLY the enhanced description without meta-commentary.

    enhancementInstructions: |
      Return ONLY the enhanced PR description as clean markdown.
      Start directly with the enhanced description content.

    outputTemplate: |
      # {{PR_TITLE}}

      ## Summary
      [Clear overview of what this PR accomplishes]

      ## Changes Made
      [Specific technical changes with file references]

      ## Testing Strategy
      [How changes were tested and validated]

      ## Impact & Considerations
      [Business impact, performance implications, breaking changes]

# Performance Configuration
cache:
  enabled: true
  ttl: "1h"
  maxSize: "100mb"
  storage: "memory"

# Monitoring and Analytics
monitoring:
  enabled: true
  metrics: ["performance", "cache", "api_calls"]

πŸ€– Programmatic Usage

Basic Setup

import { Guardian, createGuardian } from "@juspay/yama";

// Create Guardian instance
const guardian = createGuardian({
  providers: {
    ai: {
      provider: "google-ai",
      enableAnalytics: true,
    },
    git: {
      platform: "bitbucket",
      credentials: {
        username: process.env.BITBUCKET_USERNAME!,
        token: process.env.BITBUCKET_TOKEN!,
        baseUrl: "https://your-bitbucket-server.com",
      },
    },
  },
});

// Initialize
await guardian.initialize();

Unified Processing

// Process PR with multiple operations using shared context
const result = await guardian.processPR({
  workspace: "YOUR_WORKSPACE",
  repository: "my-repo",
  branch: "feature/auth",
  operations: ["review", "enhance-description"],
});

console.log(`Processed ${result.operations.length} operations`);
console.log(`API calls saved: ${result.performance.apiCallsSaved}`);
console.log(`Cache hit ratio: ${result.performance.cacheHitRatio}%`);

Streaming Processing with Real-time Updates

// Real-time progress updates
for await (const update of guardian.processPRStream({
  workspace: "YOUR_WORKSPACE",
  repository: "my-repo",
  branch: "feature/auth",
  operations: ["review", "enhance-description"],
})) {
  console.log(`${update.operation}: ${update.status} - ${update.message}`);

  if (update.progress) {
    console.log(`Progress: ${update.progress}%`);
  }
}

Individual Operations

// Code review only
const reviewResult = await guardian.reviewCode({
  workspace: "YOUR_WORKSPACE",
  repository: "my-repo",
  branch: "feature/auth",
  excludePatterns: ["*.lock", "*.svg"],
});

// Description enhancement only
const enhancementResult = await guardian.enhanceDescription({
  workspace: "YOUR_WORKSPACE",
  repository: "my-repo",
  branch: "feature/auth",
  customSections: [
    { key: "summary", name: "πŸ“ Summary", required: true },
    { key: "rollback", name: "πŸ”„ Rollback Plan", required: true },
  ],
});

Configuration Hot-Reload

import { configManager } from "@juspay/yama";

// Enable hot-reload for configuration changes
const stopWatching = configManager.enableHotReload((newConfig) => {
  console.log("Configuration updated:", newConfig);
  // Optionally reinitialize Guardian with new config
});

// Stop watching when done
process.on("SIGINT", () => {
  stopWatching();
  process.exit(0);
});

🧠 Smart Diff Strategy

Yama automatically chooses the optimal diff processing strategy:

Strategy Selection

// File count ≀ 5: Whole diff strategy
if (fileCount <= 5) {
  strategy = "whole"; // Fast, provides full context
  reason = "Small PR, whole diff provides better context";
}

// File count 6-20: Still whole diff (manageable)
else if (fileCount <= 20) {
  strategy = "whole";
  reason = "Moderate PR size, whole diff manageable";
}

// File count 21-50: File-by-file with batching
else if (fileCount <= 50) {
  strategy = "file-by-file"; // Batch process 5 files at a time
  reason = "Large PR, file-by-file more efficient";
}

// File count > 50: Essential batching for performance
else {
  strategy = "file-by-file";
  reason = "Very large PR, batching required for performance";
}

Batch Processing for Large PRs

// Process files in optimized batches
const batchSize = 5;
for (let i = 0; i < filteredFiles.length; i += batchSize) {
  const batch = filteredFiles.slice(i, i + batchSize);

  // Process batch in parallel with intelligent caching
  const batchResults = await Promise.all(
    batch.map((file) => processFileWithCache(file)),
  );
}

🎯 File Exclusion Patterns

Built-in Smart Exclusions

# Default exclusions (always applied unless overridden)
excludePatterns:
  - "*.lock" # Package lock files
  - "*.svg" # SVG images
  - "*.min.js" # Minified JavaScript
  - "*.min.css" # Minified CSS
  - "node_modules/**" # Dependencies
  - "dist/**" # Build outputs
  - "build/**" # Build outputs
  - "coverage/**" # Test coverage

Pattern Syntax

# Examples of supported patterns:
--exclude "*.lock"                    # All lock files
--exclude "**/*.test.js"              # Test files in any directory
--exclude "src/generated/**"          # Entire generated directory
--exclude "*.{lock,svg,min.js}"       # Multiple extensions
--exclude "!important.lock"           # Exclude everything except important.lock

Context-Aware Exclusions

// Different exclusions for different operations
const reviewExclusions = ["*.lock", "*.svg", "**/*.test.js"];
const enhancementExclusions = ["*.lock"]; // Allow SVGs in descriptions

await guardian.processPR({
  operations: [
    {
      type: "review",
      excludePatterns: reviewExclusions,
    },
    {
      type: "enhance-description",
      excludePatterns: enhancementExclusions,
    },
  ],
});

πŸ“‹ Configurable Description Sections

Default Required Sections

const defaultSections = [
  { key: "changelog", name: "πŸ“‹ Changelog (Modules Modified)", required: true },
  {
    key: "testcases",
    name: "πŸ§ͺ Test Cases (What to be tested)",
    required: true,
  },
  { key: "config_changes", name: "βš™οΈ Config Changes", required: true },
];

Custom Section Examples

# Enterprise setup
requiredSections:
  - key: "summary"
    name: "πŸ“ Executive Summary"
    required: true

  - key: "business_impact"
    name: "πŸ’Ό Business Impact"
    required: true

  - key: "technical_changes"
    name: "πŸ”§ Technical Changes"
    required: true

  - key: "testing_strategy"
    name: "πŸ§ͺ Testing Strategy"
    required: true

  - key: "rollback_plan"
    name: "πŸ”„ Rollback Plan"
    required: true

  - key: "monitoring"
    name: "πŸ“Š Monitoring & Alerts"
    required: false

  - key: "documentation"
    name: "πŸ“– Documentation Updates"
    required: false

Section Auto-Detection

// Smart pattern matching for existing sections
const sectionPatterns = {
  changelog: [
    /##.*?[Cc]hangelog/i,
    /##.*?[Mm]odules?\s+[Mm]odified/i,
    /πŸ“‹.*?[Cc]hangelog/i,
  ],
  testcases: [/##.*?[Tt]est\s+[Cc]ases?/i, /##.*?[Tt]esting/i, /πŸ§ͺ.*?[Tt]est/i],
  security: [/##.*?[Ss]ecurity/i, /πŸ”’.*?[Ss]ecurity/i, /##.*?[Vv]ulnerabilit/i],
};

πŸ› οΈ Utility Commands

Health and Status

# Check system health
yama status --detailed

# Output:
# βš”οΈ Yama Status
# βœ… Overall Health: Healthy
#
# πŸ“Š Component Status:
#   βœ… ai: OK
#   βœ… git: OK
#   βœ… cache: OK
#   βœ… config: OK
#
# πŸ“ˆ Statistics:
# {
#   "totalOperations": 45,
#   "successRate": 0.98,
#   "avgProcessingTime": 120,
#   "apiCallsSaved": 1250
# }
#
# πŸ’Ύ Cache: 67 keys, 423 hits, 89% hit ratio

Cache Management

# View cache statistics
yama cache stats

# Output:
# πŸ’Ύ Cache Statistics
# Keys: 67
# Hits: 423
# Misses: 52
# Hit Ratio: 89%
#
# πŸ“Š Detailed Stats:
# {
#   "pr": { "hits": 45, "misses": 5 },
#   "file-diff": { "hits": 234, "misses": 28 },
#   "context": { "hits": 144, "misses": 19 }
# }

# Clear caches
yama cache clear

Configuration Management

# Validate configuration
yama config validate

# Show current configuration (sensitive data masked)
yama config show

# Output:
# βš™οΈ Current Configuration
# {
#   "ai": {
#     "provider": "google-ai",
#     "enableAnalytics": true
#   },
#   "git": {
#     "platform": "bitbucket",
#     "credentials": {
#       "token": "***MASKED***"
#     }
#   }
# }

πŸ”„ Migration from Individual Scripts

Yama provides 100% backward compatibility with your existing workflows:

From pr-police.js

# Old way
node pr-police.js --workspace YOUR_WORKSPACE --repository repo --branch branch

# New way (identical functionality + optimizations)
yama review --workspace YOUR_WORKSPACE --repository repo --branch branch

# OR use the direct alias
yama police --workspace YOUR_WORKSPACE --repository repo --branch branch

From pr-describe.js / pr-scribe.js

# Old way
node pr-describe.js --workspace YOUR_WORKSPACE --repository repo --branch branch

# New way (identical functionality + optimizations)
yama enhance --workspace YOUR_WORKSPACE --repository repo --branch branch

# OR use the direct alias
yama scribe --workspace YOUR_WORKSPACE --repository repo --branch branch

New Unified Approach (Best Performance)

# Best of both worlds + 90% performance improvement
yama process --workspace YOUR_WORKSPACE --repository repo --branch branch --operations all

πŸ—οΈ Architecture Overview

βš”οΈ YAMA ARCHITECTURE βš”οΈ
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  πŸ” UNIFIED CONTEXT GATHERING (Once for all operations)    β”‚
β”‚     β”œβ”€β”€ πŸ” Find Open PR (by branch or PR ID)               β”‚
β”‚     β”œβ”€β”€ πŸ“„ Get PR Details (title, description, comments)   β”‚
β”‚     β”œβ”€β”€ 🧠 Get Memory Bank Context (project rules)         β”‚
β”‚     β”œβ”€β”€ πŸ“Š Smart Diff Strategy (whole vs file-by-file)     β”‚
β”‚     └── πŸ“Ž Apply File Exclusions & Filters                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  ⚑ OPTIMIZED OPERATIONS (Use shared context)              β”‚
β”‚     β”œβ”€β”€ πŸ›‘οΈ Code Review (security, performance, quality)    β”‚
β”‚     β”œβ”€β”€ πŸ“ Description Enhancement (preserve + enhance)    β”‚
β”‚     β”œβ”€β”€ πŸ”’ Security Scan (future)                          β”‚
β”‚     └── πŸ“Š Analytics & Reporting (future)                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  πŸš€ PERFORMANCE LAYER                                      β”‚
β”‚     β”œβ”€β”€ πŸ’Ύ Multi-Layer Caching (90% fewer API calls)      β”‚
β”‚     β”œβ”€β”€ πŸ”— Connection Reuse (single MCP connection)        β”‚
β”‚     β”œβ”€β”€ πŸ“¦ Intelligent Batching (5 files per batch)       β”‚
β”‚     └── πŸ”„ Smart Retry Logic (exponential backoff)         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🌟 Why Yama?

vs Individual Scripts

  1. πŸš€ 90% Performance Gain: Unified context eliminates duplicate API calls
  2. 🧠 Shared Intelligence: AI analysis benefits from complete PR context
  3. πŸ’Ύ Intelligent Caching: Multi-layer caching with 80-90% hit rates
  4. πŸ“¦ Batch Processing: Handles large PRs (50+ files) that would fail before
  5. πŸ”§ Enterprise Features: Health monitoring, configuration management, analytics
  6. πŸ“˜ Type Safety: Complete TypeScript implementation with IntelliSense
  7. πŸ”„ Backward Compatible: Existing workflows work unchanged

vs Other Tools

  1. 🎯 Purpose-Built: Specifically designed for enterprise PR workflows
  2. πŸ”’ Security-First: Built-in security analysis and hardcoded secret detection
  3. πŸ€– AI-Native: Deep integration with multiple AI providers with fallbacks
  4. βš™οΈ Highly Configurable: Every aspect can be customized via configuration
  5. πŸ“Š Analytics Ready: Built-in performance monitoring and metrics collection

πŸ›‘οΈ Security & Privacy

  • πŸ” No Data Storage: All processing is ephemeral, no permanent data storage
  • πŸ”’ Token Security: All credentials are handled securely and never logged
  • 🌐 Local Processing: Diffs and code analysis happen locally before AI submission
  • 🚫 No Tracking: No usage analytics sent to external services (unless explicitly enabled)
  • πŸ›‘οΈ Content Filtering: Automatic detection and filtering of sensitive data before AI processing

πŸ“ˆ Performance Monitoring

Built-in Metrics

const stats = guardian.getStats();

console.log({
  performance: {
    totalOperations: stats.totalOperations,
    avgProcessingTime: stats.avgProcessingTime,
    successRate: stats.successRate,
    apiCallsSaved: stats.apiCallsSaved,
  },
  cache: {
    hitRatio: stats.cache.hitRatio,
    totalHits: stats.cache.hits,
    keyCount: stats.cache.keys,
  },
  resources: {
    memoryUsage: stats.memory,
    activeConnections: stats.connections,
  },
});

Performance Tracking

# View performance metrics
yama status --detailed

# Example output shows:
# - 90% reduction in API calls vs individual scripts
# - 3x faster execution through shared context
# - 89% cache hit ratio
# - Average processing time: 2.3 minutes for medium PRs

πŸš€ Coming Soon (Future Phases)

  • πŸ”’ Advanced Security Scanning: Dependency vulnerability analysis, SAST integration
  • 🌐 Multi-Platform Support: GitHub, GitLab, Azure DevOps integration
  • πŸ“Š Advanced Analytics: Team productivity metrics, code quality trends
  • πŸ€– Custom AI Rules: Train models on your codebase patterns
  • ⚑ Parallel Processing: Multi-PR batch processing for CI/CD integration
  • πŸ”— IDE Integration: VSCode, IntelliJ plugins for real-time analysis

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ†˜ Support


🎯 Environment Variables

# Required
BITBUCKET_USERNAME=your-username
BITBUCKET_TOKEN=your-personal-access-token
GOOGLE_AI_API_KEY=your-google-ai-api-key

# Optional
BITBUCKET_BASE_URL=https://your-bitbucket-server.com
AI_PROVIDER=google-ai
AI_MODEL=gemini-2.5-pro
DEFAULT_WORKSPACE=YOUR_WORKSPACE
ENABLE_CACHE=true
YAMA_DEBUG=false

βš”οΈ Built with ❀️ by the Juspay team β€’ Powered by AI & Enterprise Security β€’ Code Quality Justice

"In the realm of code, Yama stands as the eternal judge, ensuring only the worthy changes pass through to enlightenment."

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 5