diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 2444667..34e7a90 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,11 +11,13 @@ This major release transforms Context Manager from a CLI tool into a comprehensi #### Breaking Changes **Architecture:** + - Complete modular refactor with new `lib/core/` directory - Plugin-based system for extensibility - Event-driven architecture **No Breaking API Changes:** + - All existing CLI commands work as before - Backward compatible with v2.3.x configurations - Existing scripts and integrations continue to work @@ -23,39 +25,46 @@ This major release transforms Context Manager from a CLI tool into a comprehensi #### Added **🏗️ Modular Core (4 modules):** + - `Scanner.js` - File system scanning (2491 files in 100ms) - `Analyzer.js` - Token & method analysis with parallel processing - `ContextBuilder.js` - Smart context generation - `Reporter.js` - Multi-format reports **🔌 Plugin System:** + - `PluginManager.js` - Lazy-loading plugin management - `LanguagePlugin` & `ExporterPlugin` base classes - Auto-discovery from plugin directories - Event-driven communication **🔀 Git Integration (3 modules):** + - `GitClient.js` - Git operations - `DiffAnalyzer.js` - Change impact analysis - `BlameTracker.js` - Author attribution - CLI: `--changed-only`, `--changed-since`, `--with-authors` **👁️ Watch Mode:** + - `FileWatcher.js` - Real-time file watching with debounce - `IncrementalAnalyzer.js` - Smart re-analysis - CLI: `context-manager watch` **⚡ Performance:** + - `CacheManager.js` - Disk/memory caching (>80% hit rate target) - Parallel processing (4 workers) - Lazy loading modules **🌐 REST API:** + - `APIServer.js` - HTTP server (port 3000) - 6 endpoints: analyze, methods, stats, diff, context, docs - CLI: `context-manager serve` #### CLI Enhancements + ```bash # Git Integration context-manager --changed-only @@ -68,12 +77,14 @@ context-manager watch --debounce 1000 ``` #### Performance + - Scan: 2491 files in ~100ms - Analysis: ~30ms/file with cache - Plugin load: <50ms - Tests: 12/12 passing ✅ #### New npm Scripts + - `npm run serve` - Start API server - `npm run watch` - Start watch mode - `npm run test:v3` - v3.0.0 tests @@ -92,6 +103,7 @@ This release introduces a powerful wizard profiles system that enables multiple #### Added **Wizard Profiles System:** + - ✨ **6 pre-configured analysis profiles** with comprehensive filter sets: - 👀 **Code Review** - For reviewing code changes and PRs (~20K-80K tokens) - 🔒 **Security Audit** - For security assessments and vulnerability analysis (~15K-60K tokens) @@ -101,6 +113,7 @@ This release introduces a powerful wizard profiles system that enables multiple - 📦 **Full** - For comprehensive codebase analysis (~50K-500K+ tokens) **Each Profile Contains:** + - `profile.json` - Metadata (name, description, icon, token budgets, best practices) - `.contextinclude` - File-level include filters - `.contextignore` - File-level exclude filters @@ -108,18 +121,21 @@ This release introduces a powerful wizard profiles system that enables multiple - `.methodignore` - Method-level exclude filters **Named Configuration System:** + - 📋 **Profile-specific configs**: `.contextinclude-code-review`, `.methodinclude-security-audit` - 🔄 **Multiple profiles coexist**: Switch between profiles without losing configurations - ✅ **Active configs**: `.contextinclude` → active profile's configuration - 🎨 **Custom profiles**: Users can create their own profiles easily **Wizard Integration:** + - 🧙 **Dynamic profile discovery** - Automatically detects profiles from `.context-manager/wizard-profiles/` - 📊 **Profile metadata display** - Shows token budgets, descriptions, and best practices - ⚙️ **Custom option** - Uses existing root config files for one-off analyses - ✅ **Visual feedback** - Shows copied and active configuration files **Directory Structure:** + ``` .context-manager/ └── wizard-profiles/ # Active profiles (editable) @@ -142,6 +158,7 @@ examples/ ``` **Profile Switching Workflow:** + ```bash # Run wizard context-manager --wizard @@ -165,6 +182,7 @@ context-manager --wizard ``` **Manual Profile Management:** + ```bash # Restore default profiles cp -r examples/wizard-profiles/* .context-manager/wizard-profiles/ @@ -177,19 +195,23 @@ cp -r .context-manager/wizard-profiles/code-review .context-manager/wizard-profi #### Technical Implementation **New Directories:** + - `.context-manager/wizard-profiles/` - Active wizard profiles (6 profiles × 5 files = 30 files) - `examples/wizard-profiles/` - Reference backup profiles **New Files:** + - `examples/custom-llm-profiles.example.json` - Moved from .context-manager/ - `examples/README.md` - Comprehensive profile management guide **Enhanced Files:** + - `lib/ui/wizard.js` - Profile discovery, metadata parsing, named config copying - `package.json` - Version bump to 2.3.8, includes .context-manager/ and examples/ -- `.gitignore` - Ignores named configs (.contextinclude-*, .methodinclude-*) +- `.gitignore` - Ignores named configs (.contextinclude-_, .methodinclude-_) **New Functions:** + - `discoverProfiles()` - Scans .context-manager/wizard-profiles/ for profiles - `copyProfileFiles(profilePath, profileId, projectRoot)` - Creates named configs - Profile metadata loading from profile.json @@ -197,36 +219,40 @@ cp -r .context-manager/wizard-profiles/code-review .context-manager/wizard-profi #### Benefits **vs Simple File Copying:** + - ✅ **Multiple profiles coexist** - Keep code-review AND security-audit configs simultaneously - ✅ **Easy switching** - Change profiles without losing previous configurations - ✅ **Named configs** - Clear which profile each config belongs to - ✅ **Full control** - Both include AND ignore filters for fine-grained control **vs Preset System:** + - ✅ **No complex runtime** - Simple file copying, no preset engine needed - ✅ **Transparent** - Users see exactly what filters are active - ✅ **Customizable** - Profiles are just files, easy to modify - ✅ **Versionable** - Profiles can be committed to git for team sharing **vs Manual Configuration:** + - ✅ **Faster setup** - Pre-configured best practices for common scenarios - ✅ **Educational** - profile.json documents why filters are chosen - ✅ **Restorable** - examples/ directory provides backup/reference #### Token Budget Guidelines -| Profile | Small Project | Medium Project | Large Project | -|---------|---------------|----------------|---------------| -| Minimal | 5K-10K | 10K-25K | 25K-50K | -| Code Review | 20K-40K | 40K-80K | 80K-150K | -| Security Audit | 15K-30K | 30K-60K | 60K-120K | -| Documentation | 18K-35K | 35K-70K | 70K-140K | -| LLM Explain | 25K-50K | 50K-100K | 100K-200K | -| Full | 50K-100K | 100K-250K | 250K-500K+ | +| Profile | Small Project | Medium Project | Large Project | +| -------------- | ------------- | -------------- | ------------- | +| Minimal | 5K-10K | 10K-25K | 25K-50K | +| Code Review | 20K-40K | 40K-80K | 80K-150K | +| Security Audit | 15K-30K | 30K-60K | 60K-120K | +| Documentation | 18K-35K | 35K-70K | 70K-140K | +| LLM Explain | 25K-50K | 50K-100K | 100K-200K | +| Full | 50K-100K | 100K-250K | 250K-500K+ | #### Migration No migration needed. Existing workflows continue to work: + - Existing `.contextinclude`/`.contextignore` files are respected - Wizard's "Custom" option uses existing root configurations - Profiles are optional, not required @@ -243,6 +269,7 @@ This release introduces automatic LLM model detection and context window optimiz #### Added **LLM Auto-Detection:** + - ✨ **Automatic model detection** from environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_API_KEY) - 🎯 **9+ built-in LLM profiles** with context window specifications - Anthropic: Claude Sonnet 4.5, Claude Opus 4 @@ -254,16 +281,19 @@ This release introduces automatic LLM model detection and context window optimiz - 📋 **JSON-based profile system** stored in `.context-manager/llm-profiles.json` **CLI Enhancements:** + - `--target-model MODEL` - Optimize for specific LLM model - `--auto-detect-llm` - Auto-detect from environment - `--list-llms` - List all supported models with details **Wizard Integration:** + - 🧙 Dynamic LLM model selection in wizard - ✨ "Auto-detect from environment" option - Grouped by vendor (Anthropic, OpenAI, Google, etc.) **Context Fit Analysis Display:** + ``` 📊 Context Window Analysis: Target Model: Claude Sonnet 4.5 @@ -277,18 +307,21 @@ This release introduces automatic LLM model detection and context window optimiz #### Technical Implementation **New Files:** + - `.context-manager/llm-profiles.json` - Built-in LLM model profiles - `.context-manager/custom-profiles.example.json` - Template for custom models - `lib/utils/llm-detector.js` - LLM detection and optimization logic - `test/test-llm-detection.js` - Comprehensive test suite (12 tests) **Updated Files:** + - `lib/ui/wizard.js` - Dynamic model list from JSON config - `bin/cli.js` - LLM flags and help text - `lib/analyzers/token-calculator.js` - Context fit analysis display - `package.json` - v2.3.7 **Architecture:** + - Lazy-loading profile cache for performance (<100ms) - Fallback to hardcoded profiles if JSON fails - Merge built-in + custom profiles (custom overrides built-in) @@ -297,6 +330,7 @@ This release introduces automatic LLM model detection and context window optimiz #### Use Cases **Automatic Optimization:** + ```bash # Set your API key export ANTHROPIC_API_KEY=sk-... @@ -312,6 +346,7 @@ context-manager ``` **Explicit Model Selection:** + ```bash # Optimize for specific model context-manager --target-model claude-sonnet-4.5 @@ -320,6 +355,7 @@ context-manager --target-model gemini-2.0-flash ``` **Custom Models:** + ```json // .context-manager/custom-profiles.json { @@ -345,11 +381,13 @@ context-manager --target-model gemini-2.0-flash #### Migration Notes **For Users:** + - No breaking changes - all existing commands work as before - New `--target-model` flag is optional - Auto-detection is opt-in (requires API key in environment) **For Developers:** + - LLM profiles stored in `.context-manager/llm-profiles.json` - Custom profiles: `.context-manager/custom-profiles.json` - Programmatic API: `LLMDetector.detect()`, `LLMDetector.getProfile()` @@ -365,6 +403,7 @@ This patch release brings direct GitHub repository support and completes the mod #### Added **GitHub Integration:** + - 🔗 **Direct GitHub Repository Support** - Generate GitIngest from GitHub URLs - Support for multiple URL formats (github.com, raw.githubusercontent.com) - Automatic shallow cloning for faster processing @@ -376,6 +415,7 @@ This patch release brings direct GitHub repository support and completes the mod #### Enhanced **Modern Stack Migration:** + - ⚛️ **React 19 Upgrade** - Upgraded from React 18.2.0 to React 19.2.0 - Latest React features and performance improvements - Better TypeScript support @@ -398,6 +438,7 @@ This patch release brings direct GitHub repository support and completes the mod - No external dependencies **User Experience:** + - 🧙 **Wizard Mode as Default** - Interactive wizard is now the default interface - More user-friendly for new users - CLI mode available via `--cli` flag @@ -413,6 +454,7 @@ This patch release brings direct GitHub repository support and completes the mod #### Fixed **UI/UX Fixes:** + - 🐛 **Visual Artifacts Eliminated** - Removed terminal rendering glitches - No more duplicate option display - Clean component unmounting @@ -425,11 +467,12 @@ This patch release brings direct GitHub repository support and completes the mod - Graceful fallbacks for limited terminals **Dependency Updates:** + ```json { - "react": "^19.2.0", // was: ^18.2.0 - "ink": "^6.4.0", // was: ^4.4.1 - "ink-spinner": "^5.0.0", // compatible with Ink 6 + "react": "^19.2.0", // was: ^18.2.0 + "ink": "^6.4.0", // was: ^4.4.1 + "ink-spinner": "^5.0.0", // compatible with Ink 6 "ink-text-input": "^6.0.0" // compatible with Ink 6 } ``` @@ -437,11 +480,13 @@ This patch release brings direct GitHub repository support and completes the mod #### Migration Notes **For Users:** + - No breaking changes - all commands work as before - Default mode is now wizard (use `--cli` for old behavior) - Better visual experience with modernized UI **For Developers:** + - All files now use ESM (import/export) - React 19 and Ink 6 APIs available - Custom SelectInput component for UI consistency @@ -449,12 +494,14 @@ This patch release brings direct GitHub repository support and completes the mod #### Technical Details **Files Modified (ESM Migration):** + - 29 files converted to pure ESM - `lib/` directory: All utility, parser, formatter, analyzer files - `bin/` directory: All CLI tools - Test files remain compatible with both systems **Performance:** + - No performance regression - UI rendering: <16ms per frame (maintained) - Startup time: Similar to v2.3.5 @@ -469,12 +516,14 @@ This patch release brings direct GitHub repository support and completes the mod Comprehensive improvements across TOON optimization, format conversion, chunking, error handling, and stability. **v2.3.1 - TOON Optimization:** + - Added `validate()` method - Checks balanced braces/brackets - Added `estimateTokens()` - Token count estimation (~4 chars/token) - Added `optimize()` - Removes unnecessary whitespace - Added `minify()` - Ultra-compact output **v2.3.2 - Format Conversion:** + - New `FormatConverter` class in `lib/utils/format-converter.js` - CLI: `context-manager convert input.json --from json --to toon` - Supports: JSON ↔ TOON, JSON ↔ YAML, JSON ↔ CSV, JSON ↔ XML, CSV → JSON @@ -482,27 +531,32 @@ Comprehensive improvements across TOON optimization, format conversion, chunking - Conversion statistics (size, savings, percentage) **v2.3.3 - GitIngest Chunking:** + - Chunk overlap (default 500 tokens) for context continuity - Enhanced metadata (languages, directories, cross-refs) - Shared directory detection between chunks - Improved context preservation (95%+) **v2.3.4 - Error Handling:** + - New `ErrorHandler` class in `lib/utils/error-handler.js` - User-friendly error messages with suggestions - Optional error logging to file - Format validation, async error wrapping **v2.3.5 - Stability & Polish:** + - Performance optimizations - Documentation updates - Edge case fixes #### 📦 New Files + - `lib/utils/format-converter.js` (v2.3.2) - `lib/utils/error-handler.js` (v2.3.4) #### 🔄 Updated Files + - `lib/formatters/toon-formatter.js` - Validation & optimization - `lib/formatters/gitingest-formatter.js` - Overlap & metadata - `bin/cli.js` - Format conversion command @@ -521,6 +575,7 @@ This release introduces revolutionary output capabilities with the new TOON form #### ✨ New Features **1. TOON Format (Tabular Object Oriented Notation)** + - 40-50% token reduction compared to JSON - Tabular format for arrays of objects - Compact field declarations @@ -529,6 +584,7 @@ This release introduces revolutionary output capabilities with the new TOON form - Comparison tools to measure savings **2. Multi-Format Support (8 Formats)** + - **TOON** - Ultra-efficient (40-50% reduction) - **JSON** - Standard format - **JSON Compact** - Minified JSON @@ -539,6 +595,7 @@ This release introduces revolutionary output capabilities with the new TOON form - **GitIngest** - Single-file digest **3. FormatRegistry System** + - Central registry for all output formatters - Easy format switching via `--output` flag - Custom formatter registration support @@ -546,6 +603,7 @@ This release introduces revolutionary output capabilities with the new TOON form - `--list-formats` command to show all available formats **4. Smart GitIngest Chunking** + - Multiple chunking strategies: - **Smart** - AI-based semantic grouping (directory-aware) - **Size** - Fixed token size chunks @@ -558,6 +616,7 @@ This release introduces revolutionary output capabilities with the new TOON form - `--chunk`, `--chunk-strategy`, `--chunk-size` options **5. Ink-Based Terminal UI** + - React-based interactive components - Modern, beautiful CLI experience - Real-time progress indicators @@ -570,6 +629,7 @@ This release introduces revolutionary output capabilities with the new TOON form - `Dashboard` - Live statistics **6. Interactive Wizard Mode** + - `--wizard` flag for guided setup - Use case selection (bug-fix, feature, code-review, etc.) - Target LLM selection (Claude, GPT-4, Gemini) @@ -577,6 +637,7 @@ This release introduces revolutionary output capabilities with the new TOON form - Visual, step-by-step configuration **7. Enhanced CLI Options** + ```bash # Format options -o, --output FORMAT # Choose output format @@ -604,6 +665,7 @@ This release introduces revolutionary output capabilities with the new TOON form #### 🏗️ Architecture Changes **New Modules:** + ``` lib/ ├── formatters/ @@ -618,6 +680,7 @@ lib/ ``` **Updated Files:** + - `bin/cli.js` - Complete rewrite with new options - `index.js` - Added ToonFormatter and FormatRegistry exports - `package.json` - Updated to v2.3.0, added Ink dependencies @@ -652,10 +715,12 @@ lib/ No breaking changes! All existing commands work as before. **New default behavior:** + - Default output format is now TOON (was JSON) - To use JSON format: `context-manager --output json` **To take advantage of new features:** + ```bash # Use TOON format (new default) context-manager @@ -694,6 +759,7 @@ context-manager --output csv Complete architectural overhaul from monolithic (1340 lines) to modular design (236 lines orchestrator + focused modules). #### Breaking Changes + - **NONE!** All existing APIs maintained for backward compatibility - `TokenAnalyzer` alias still works (points to `TokenCalculator`) - All CLI commands unchanged @@ -702,6 +768,7 @@ Complete architectural overhaul from monolithic (1340 lines) to modular design ( #### Architecture Changes **New Module Structure:** + ``` lib/ ├── utils/ (4 modules, 337 lines) @@ -720,12 +787,14 @@ lib/ ``` **Main Files:** + - `context-manager.js` - Orchestrator (236 lines, **82.4% reduction**) - `index.js` - Enhanced public API (48 lines) #### Code Quality Improvements **1. Eliminated Duplication:** + - `findConfigFile()` - Removed 2 duplicates → `ConfigUtils.findConfigFile()` - `initMethodFilter()` - Removed 2 duplicates → `ConfigUtils.initMethodFilter()` - Token counting - Unified in `TokenUtils.calculate()` @@ -733,11 +802,13 @@ lib/ - Clipboard - Extracted to `ClipboardUtils.copy()` **2. Single Responsibility:** + - Each module has ONE clear purpose - Utils are independently reusable - Better separation of concerns **3. Better Testability:** + - Utils can be unit tested in isolation - Dependencies can be mocked - Clearer test boundaries @@ -745,55 +816,58 @@ lib/ #### New Public APIs **Enhanced Exports:** + ```javascript const { - // Analyzers - TokenCalculator, - TokenAnalyzer, // Alias (backward compat) - MethodAnalyzer, - - // Parsers - GitIgnoreParser, - MethodFilterParser, - - // Formatters - GitIngestFormatter, - - // Utils (NEW!) - TokenUtils, - FileUtils, - ClipboardUtils, - ConfigUtils, - - // Functions (NEW!) - generateDigestFromReport, - generateDigestFromContext + // Analyzers + TokenCalculator, + TokenAnalyzer, // Alias (backward compat) + MethodAnalyzer, + + // Parsers + GitIgnoreParser, + MethodFilterParser, + + // Formatters + GitIngestFormatter, + + // Utils (NEW!) + TokenUtils, + FileUtils, + ClipboardUtils, + ConfigUtils, + + // Functions (NEW!) + generateDigestFromReport, + generateDigestFromContext, } = require('@hakkisagdic/context-manager'); ``` **Utility Functions:** + ```javascript // Token utilities -TokenUtils.calculate(content, filePath) // Calculate tokens -TokenUtils.format(1500) // "1.5k" -TokenUtils.hasExactCounting() // Check tiktoken availability +TokenUtils.calculate(content, filePath); // Calculate tokens +TokenUtils.format(1500); // "1.5k" +TokenUtils.hasExactCounting(); // Check tiktoken availability // File utilities -FileUtils.isText(filePath) // Is text file? -FileUtils.isCode(filePath) // Is code file? -FileUtils.getType(filePath) // Get category +FileUtils.isText(filePath); // Is text file? +FileUtils.isCode(filePath); // Is code file? +FileUtils.getType(filePath); // Get category // Clipboard utilities -ClipboardUtils.copy(text) // Cross-platform copy -ClipboardUtils.isAvailable() // Check availability +ClipboardUtils.copy(text); // Cross-platform copy +ClipboardUtils.isAvailable(); // Check availability // Config utilities -ConfigUtils.findConfigFile(root, name) // Find config -ConfigUtils.detectMethodFilters(root) // Detect method filters -ConfigUtils.getConfigPaths(root) // Get all config paths +ConfigUtils.findConfigFile(root, name); // Find config +ConfigUtils.detectMethodFilters(root); // Detect method filters +ConfigUtils.getConfigPaths(root); // Get all config paths ``` #### Files Added + - `lib/utils/token-utils.js` - Token counting and formatting - `lib/utils/file-utils.js` - File type detection - `lib/utils/clipboard-utils.js` - Clipboard operations @@ -806,12 +880,14 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - `REFACTORING_REPORT.md` - Detailed refactoring documentation #### Performance + - **No regression**: Cold start ~2.5s (unchanged) - **Memory savings**: 3MB reduction (45MB → 42MB) - **Test time**: +0.1s (8.2s → 8.3s, acceptable) - **Module loading**: Faster parsing (multiple small files vs 1 large) #### Test Results + ``` ✅ Basic tests: 25/25 passed (100%) ✅ Unit tests: 34/34 passed (100%) @@ -824,10 +900,12 @@ ConfigUtils.getConfigPaths(root) // Get all config paths #### Migration Notes **For Users:** + - No changes required - all commands work as before - All features available **For Developers:** + - More APIs available for programmatic use - Better module isolation for testing - Clearer dependency structure @@ -835,6 +913,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths ## [1.2.2] - 2025-10-13 ### Added + - 🎯 **Method-Aware GitIngest** - Automatic method-level filtering in digest generation - GitIngestFormatter now auto-detects `.methodinclude` and `.methodignore` files - If method filters exist, digest automatically shows only filtered methods @@ -844,6 +923,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - Compatible with all GitIngest modes (live, from-report, from-context) ### Changed + - 📄 **GitIngest Output** - Now respects method-level filters when present - Code files (.js, .ts, .jsx, .tsx) use method extraction - Non-code files (config, docs) use full content @@ -851,6 +931,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - Method extraction with smart brace counting (up to 100 lines per method) ### Technical + - Added `detectMethodFilters()` - Auto-detects method filter config - Added `generateFilteredFileContent()` - Extracts and filters methods - Added `extractMethodBlock()` - Smart method body extraction @@ -859,6 +940,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths ## [1.2.1] - 2025-10-13 ### Added + - ⚡ **JSON-Based Digest Generation** - Generate digest from existing JSON files - `--gitingest-from-report ` - Create digest from token-analysis-report.json - `--gitingest-from-context ` - Create digest from llm-context.json @@ -875,6 +957,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - 📦 **New npm script**: `test:gitingest-json` - Run JSON-based digest tests ### Changed + - 📚 **README.md** - Added JSON-based digest workflow documentation - Performance benefits explained - Two-step workflow examples @@ -885,12 +968,14 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - 🧪 **Test Suite** - Updated `test:comprehensive` to include JSON-based tests ### Performance + - ⚡ JSON-based digest generation: **~0.1 seconds** (vs ~2-3 seconds for live scan) - 🚀 **20-30x faster** than live file scanning ## [1.2.0] - 2025-10-13 ### Added + - 🎯 **GitIngest Format Export** - Generate single-file digest for LLM consumption - New `GitIngestFormatter` class for digest generation - `--gitingest` / `-g` CLI flag for digest export @@ -924,23 +1009,27 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - Help messages updated with new flags ### Changed + - 📤 **Interactive Export Menu** - Added GitIngest as option 4 (was 4 options, now 5) - 🔧 **Token Output** - Added `token-analysis-report.json` to `.gitignore` ## [1.1.2] - 2025-10-13 ### Fixed + - 🐛 **LLM Context Path Generation** - Fixed hardcoded `utility-mcp/src/` prefix in `generateCompactPaths` method - Paths now correctly use project-relative structure - Root directory files grouped under `/` instead of empty string - Eliminates incorrect path prefixes in LLM context exports ### Added + - ✨ **GitHub Actions Manual Trigger** - Added `workflow_dispatch` to npm-publish workflow for manual testing ## [1.1.1] - 2025-10-09 ### Fixed + - 🐛 **Package.json bin path** - Fixed bin script path format for npm standards ## [1.1.0] - 2025-10-09 @@ -948,6 +1037,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths ### 🎉 Major Quality & Feature Release #### Fixed (7 Critical Bugs) + - 🐛 **Method duplication bug** - Fixed duplicate method extraction using Map-based deduplication with `name:line` keys - 🐛 **NaN in average calculation** - Added conditional check when totalFiles is 0, now shows "N/A" - 🐛 **Class method detection** - Added shorthand pattern to properly detect class methods @@ -957,15 +1047,14 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - 🐛 **Test suite paths** - Corrected all test file paths from `token-analysis/` to root directory #### Added + - ✨ **Comprehensive test suite** - 70+ tests with 100% success rate - `test/unit-tests.js` - 34 comprehensive unit tests - Enhanced `test/test.js` - 25 tests (improved from 3) - Enhanced `test/test-suite.js` - 17+ integration tests - ✨ **Support section** - Added "Buy Me A Coffee" button and QR code to README files - ✨ **Turkish documentation** - Complete translation of all 17 documentation files - - docs/content-tr/ with full Turkish translations - Technical terms kept in English for clarity - - Organized in Temel-Ozellikler/ and Yapilandirma/ directories - ✨ **CLAUDE.md** - AI assistant guidance documentation for Claude Code - ✨ **Test documentation** - TEST_SUMMARY.md with detailed test coverage information - ✨ **Improvement docs** - CODE_IMPROVEMENTS.md and IMPROVEMENTS_COMPLETED.md @@ -978,6 +1067,7 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - Sorun-Giderme.md, Gelismis-Yapilandirma.md, Programatik-API.md, Katki-Rehberi.md #### Changed + - 🔧 **Method extraction patterns** - Enhanced regex patterns with better type tagging - Support for export functions: `export function name()` - Support for async functions: `async function name()` @@ -990,12 +1080,14 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - 🎯 **Test coverage** - Increased from ~60% to ~95% #### Improved + - 📊 **Test quality** - 100% success rate across all test suites - 🔍 **Method detection** - Now captures class methods, getters, setters correctly - 🎯 **Edge case handling** - Tests for empty code, nested functions, Unicode, special chars - 📈 **Code quality** - Better separation of concerns, clearer pattern definitions ### Technical Details + - **Total Tests:** 70+ (25 basic + 34 unit + 17+ integration) - **Test Success Rate:** 100% across all suites - **Bug Fixes:** 7 critical issues resolved @@ -1004,11 +1096,13 @@ ConfigUtils.getConfigPaths(root) // Get all config paths - **Performance:** < 30 seconds for all tests ### Breaking Changes + None - Fully backward compatible ## [1.0.3] - 2024-10-09 ### Changed + - 📝 **File naming consistency** - Renamed `token-calculator.js` to `context-manager.js` for better alignment with package identity - 🔧 **Help text update** - Updated direct usage examples to show `node context-manager.js` - 📋 **Package files** - Added `context-manager.js` to NPM package files list @@ -1017,8 +1111,9 @@ None - Fully backward compatible ## [1.0.2] - 2024-10-09 ### Fixed + - 📝 **Documentation consistency** - Updated all command examples to use `context-manager` instead of old script paths -- 🎯 **Title correction** - Changed from "Token Analysis Tools" to "Context Manager" +- 🎯 **Title correction** - Changed from "Token Analysis Tools" to "Context Manager" - 🔧 **Help text alignment** - CLI help now matches documentation examples - 🌍 **Turkish README** - Updated Turkish documentation with consistent command examples - ✨ **Branding consistency** - All documentation now properly reflects the Context Manager identity @@ -1026,11 +1121,13 @@ None - Fully backward compatible ## [1.0.1] - 2024-10-09 ### Fixed + - 📝 **Documentation cleanup** - Removed references to deleted `analyze-tokens.js` wrapper script -- 🔧 **Package branding** - Updated from "Code Analyzer" to "Context Manager" +- 🔧 **Package branding** - Updated from "Code Analyzer" to "Context Manager" - 📋 **NPM page accuracy** - Fixed documentation to reflect actual package structure ### Changed + - 🎯 **Package name** - Rebranded to `@hakkisagdic/context-manager` for better LLM focus - 📦 **CLI command** - Updated to `context-manager` for consistency - 📖 **Documentation** - Updated all references to use new package name @@ -1038,6 +1135,7 @@ None - Fully backward compatible ## [1.0.0] - 2024-10-09 ### Added + - 🎉 **Initial release** of Context Manager - 📊 **File-level analysis** with gitignore support - 🔧 **Method-level analysis** for JavaScript/TypeScript files @@ -1049,9 +1147,10 @@ None - Fully backward compatible - ⚡ **Performance optimization** (36% smaller codebase) - 📚 **Documentation** with examples -*Created by Hakkı Sağdıç* +_Created by Hakkı Sağdıç_ ### Features + - File-level token analysis with directory organization - Method-level granular analysis with line numbers - LLM context optimization (99.76% size reduction) @@ -1064,6 +1163,7 @@ None - Fully backward compatible - Verbose mode for debugging ### CLI Options + - `--save-report, -s` - Save detailed JSON report - `--verbose, -v` - Show included files and directories - `--context-export` - Generate LLM context file @@ -1072,18 +1172,21 @@ None - Fully backward compatible - `--help, -h` - Show help message ### Configuration Files + - `.contextinclude` - Include only specified files - `.contextignore` - Exclude specified files - `.methodinclude` - Include only specified methods - `.methodignore` - Exclude specified methods ### API Classes + - `TokenAnalyzer` - Main analysis class - `MethodAnalyzer` - Method extraction and analysis - `MethodFilterParser` - Method filtering logic - `GitIgnoreParser` - File filtering logic ### Use Cases + - LLM context optimization for AI assistants - Codebase complexity analysis - Method-level debugging and analysis @@ -1091,6 +1194,7 @@ None - Fully backward compatible - Development workflow optimization ### Technical Details + - Node.js >= 14.0.0 support - Optional tiktoken dependency for exact counts - Cross-platform compatibility (macOS, Linux, Windows) @@ -1100,6 +1204,7 @@ None - Fully backward compatible - Error handling and validation ### Documentation + - Comprehensive README with examples - API reference documentation - Configuration guide @@ -1108,6 +1213,7 @@ None - Fully backward compatible - Test suite and validation ### Performance + - Analyzes 64 files (181k tokens) in <2 seconds - Reduces context size by 99.76% for LLM use - Memory efficient processing @@ -1115,6 +1221,7 @@ None - Fully backward compatible - Minimal dependencies ### Package Structure + ``` @hakkisagdic/context-manager/ ├── index.js # Main entry point @@ -1131,6 +1238,7 @@ None - Fully backward compatible ## Development Notes ### Code Quality + - 36% reduction in code size while adding major features - Best practices implementation - Comprehensive error handling @@ -1138,6 +1246,7 @@ None - Fully backward compatible - Modular architecture ### Testing + - 15+ test scenarios covered - 100% success rate in validation - Method extraction accuracy verified @@ -1145,8 +1254,9 @@ None - Fully backward compatible - API completeness confirmed ### Future Enhancements + - Support for additional languages (Python, Java, etc.) - Advanced method complexity analysis - Integration with popular IDEs - Web interface for analysis -- Cloud-based processing options \ No newline at end of file +- Cloud-based processing options diff --git a/docs/INK-UI-DEMO.md b/docs/INK-UI-DEMO.md deleted file mode 100644 index a3b7e0e..0000000 --- a/docs/INK-UI-DEMO.md +++ /dev/null @@ -1,366 +0,0 @@ -# Ink UI Interactive Demo - -**Version:** 2.3.6+ -**Status:** Production Ready -**Last Updated:** November 3, 2025 - ---- - -## 🎨 Interactive UI Demo Ekranı - -Context Manager'ın tüm Ink UI component'lerini test edebileceğiniz interaktif bir demo uygulaması. - -## 🚀 Hızlı Başlangıç - -### Çalıştırma - -```bash -# NPM script ile (önerilen) -npm run test:ink - -# Veya direkt -node test/test-ink-ui.js -``` - -### Gereksinimler - -- ✅ Node.js 14+ -- ✅ Ink dependencies yüklü (`npm install`) -- ✅ Interactive terminal (iTerm2, Terminal.app, gnome-terminal) -- ❌ VSCode integrated terminal (Raw mode desteklemiyor) - ---- - -## 📋 Demo Menüsü - -Test ekranını başlattığınızda şu menü gelecek: - -``` -╔══════════════════════════════════════════════════════════╗ -║ 🎨 Ink UI Test Screen ║ -║ ║ -║ Select a test to run: ║ -║ ║ -║ ❯ 🎨 Test Colors ║ -║ 📊 Test Progress Bar ║ -║ 🔄 Test Spinners ║ -║ 📝 Test Input ║ -║ 🧙 Test Wizard ║ -║ 📈 Test Dashboard ║ -║ ❌ Exit ║ -║ ║ -║ [↑↓] Navigate [Enter] Select [Q] Quit ║ -╚══════════════════════════════════════════════════════════╝ -``` - -### Keyboard Kontrolleri - -| Tuş | Aksiyon | -|-----|---------| -| `↑` | Yukarı git | -| `↓` | Aşağı git | -| `Enter` | Seç | -| `Q` | Çıkış | -| `Esc` | Çıkış | - ---- - -## 🎯 Test Seçenekleri - -### 1. 🎨 Test Colors - -Tüm renk paleti ve text stilleri: - -``` -🌈 Color Test - -🔴 Red Text -🟢 Green Text -🟡 Yellow Text -🔵 Blue Text -🟣 Magenta Text -🔷 Cyan Text - -✨ Bold 🌑 Dim -``` - -**Test Edilen:** -- Color options: red, green, yellow, blue, magenta, cyan -- Text styles: bold, dim, italic, underline -- Color combinations - -### 2. 📊 Test Progress Bar - -Animasyonlu progress bar: - -``` -📈 Progress Bar Test - -Progress: 67% -▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░ -⏳ Processing... -``` - -**Özellikler:** -- Real-time progress (0% → 100%) -- Visual bar with filled/empty states -- Auto-completes in ~4 seconds -- Percentage display - -### 3. 🔄 Test Spinners - -Multiple spinner types: - -``` -🔄 Spinner Test - -⠋ Scanning files... -⠙ Calculating tokens... -✓ Analysis complete! -``` - -**Spinner Types:** -- Dots spinner (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏) -- Line spinner (-\|/) -- Status indicators (○ ⏳ ✓ ✗) - -### 4. 📝 Test Input - -Interactive text input: - -``` -📝 Text Input Test - -Enter your name: -Hakki▊ - -Hello, Hakki! 👋 -``` - -**Test Edilen:** -- Live typing -- onChange events -- Placeholder text -- Real-time feedback - -### 5. 🧙 Test Wizard - -Full wizard flow (3 steps): - -``` -🧙 Context Generation Wizard - -What are you working on today? - -❯ 🐛 Bug Fix - ✨ New Feature - 👀 Code Review - ... -``` - -**Steps:** -1. Use Case Selection → 7 options -2. Target Model → 6 AI models -3. Output Format → 6 formats -4. Summary & Complete - -### 6. 📈 Test Dashboard - -Live stats dashboard: - -``` -📊 Live Analysis Dashboard (complete) - -Files: 64 Methods: - Tokens: 181,480 -Size: 0.75 MB Lines: 28,721 Avg: 2,836 tok/file - -Top Languages: - ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ .js (64 files) - -Largest Files: - • server.js 12,388 tokens ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ (6.8%) - • handler.js 11,007 tokens ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ (6.1%) - • security.js 7,814 tokens ▓▓▓▓▓▓▓▓▓▓▓▓▓ (4.3%) - -┌────────────────────────────────────────────────────────┐ -│ [R] Refresh [S] Save [E] Export [Q] Quit │ -└────────────────────────────────────────────────────────┘ -``` - -**Özellikler:** -- Real-time stats -- Visual graphs with bars -- Language distribution -- Top files ranking -- Keyboard controls - ---- - -## 🐛 Troubleshooting - -### "Raw mode is not supported" - -**Sorun:** -``` -ERROR Raw mode is not supported on the current process.stdin -``` - -**Çözüm:** -Bu hata **automated test environment**'ta normal. Interactive terminal'de çalışmayacak. - -**Nerede Çalışır:** -- ✅ iTerm2 (macOS) -- ✅ Terminal.app (macOS) -- ✅ gnome-terminal (Linux) -- ✅ Windows Terminal -- ✅ PowerShell (Windows) - -**Nerede Çalışmaz:** -- ❌ VSCode integrated terminal -- ❌ CI/CD pipelines -- ❌ SSH sessions (bazı durumlarda) -- ❌ Piped input/output - -### Çözüm: - -```bash -# iTerm2 veya Terminal.app aç -open -a iTerm -# Veya -open -a Terminal - -# Demo'yu çalıştır -npm run test:ink -``` - -### Dependencies Missing - -```bash -# Tüm dependencies'i yükle -npm install - -# Veya sadece Ink -npm install ink react ink-select-input ink-spinner ink-text-input -``` - ---- - -## 💻 Terminalinizde Deneyin - -### macOS - -```bash -# iTerm2 (önerilen) -open -a iTerm -cd /path/to/context-manager -npm run test:ink - -# Terminal.app -open -a Terminal -cd /path/to/context-manager -npm run test:ink -``` - -### Linux - -```bash -# GNOME Terminal -gnome-terminal -- bash -c "cd /path/to/context-manager && npm run test:ink" - -# Konsole (KDE) -konsole -e "cd /path/to/context-manager && npm run test:ink" -``` - -### Windows - -```powershell -# Windows Terminal (önerilen) -wt.exe -d C:\path\to\context-manager npm run test:ink - -# PowerShell -cd C:\path\to\context-manager -npm run test:ink -``` - ---- - -## 🎯 Ne Test Ediliyor? - -### Component'ler -- ✅ Box (layout, flexbox, borders, padding) -- ✅ Text (colors, styles, formatting) -- ✅ SelectInput (navigation, selection) -- ✅ TextInput (typing, onChange) -- ✅ Spinner (animations, types) -- ✅ Newline, Spacer - -### Features -- ✅ State management (useState) -- ✅ Effects (useEffect for animations) -- ✅ Input handling (useInput) -- ✅ Conditional rendering -- ✅ Component composition -- ✅ Props injection (ESM workaround) - -### Custom Components -- ✅ Wizard (3-step flow) -- ✅ Dashboard (live stats) -- ✅ ProgressBar (with components prop) - ---- - -## 📚 İlgili Dosyalar - -| Dosya | Açıklama | -|-------|----------| -| `test/test-ink-ui.js` | Interactive demo app | -| `test/INK-UI-TEST-README.md` | Kullanım kılavuzu | -| `lib/ui/wizard.js` | Wizard component | -| `lib/ui/dashboard.js` | Dashboard component | -| `lib/ui/progress-bar.js` | Progress bar component | -| `docs/WIZARD-DASHBOARD-SETUP.md` | Setup guide | - ---- - -## 🎬 Demo Video Çekmek İçin - -1. **Terminal'i aç** (iTerm2 önerilen) -2. **Ekranı temizle:** `clear` -3. **Demo'yu başlat:** `npm run test:ink` -4. **Menüden seç:** Colors → Progress → Wizard → Dashboard -5. **Kaydı durdur:** `Q` tuşuna bas - ---- - -## ✅ Başarı Kriterleri - -Test screen başarılı sayılır eğer: - -1. ✅ Menü render ediliyor -2. ✅ Oklar ile navigate edilebiliyor -3. ✅ Seçimler çalışıyor -4. ✅ Her test ekranı görüntüleniyor -5. ✅ Wizard 3 adımı tamamlanabiliyor -6. ✅ Dashboard stats gösteriyor -7. ✅ Q ile çıkış çalışıyor - ---- - -## 🚀 Production Kullanım - -Demo başarılıysa, gerçek wizard ve dashboard hazır: - -```bash -# Production wizard -context-manager --wizard - -# Production dashboard -context-manager --dashboard -``` - ---- - -**Version:** 2.3.6+ -**Ink Version:** 4.4.1 -**Requires:** Interactive TTY terminal -**Not Supported:** VSCode integrated terminal, CI/CD diff --git a/docs/INSTALLATION-GUIDE.md b/docs/INSTALLATION-GUIDE.md index e7b7ea7..4f4925e 100644 --- a/docs/INSTALLATION-GUIDE.md +++ b/docs/INSTALLATION-GUIDE.md @@ -1,7 +1,7 @@ # Context Manager - Installation Guide -**Version:** 2.3.6+ -**Last Updated:** November 3, 2025 +**Version:** 3.0.0 +**Last Updated:** April 2, 2026 --- @@ -32,11 +32,13 @@ context-manager --help ### One-Line Installers #### macOS / Linux + ```bash bash <(curl -fsSL https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/install.sh) ``` #### Windows (PowerShell) + ```powershell irm https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/install.ps1 | iex ``` @@ -48,6 +50,7 @@ irm https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/i ### macOS #### Option 1: Homebrew (Recommended) + ```bash # Add tap (once) brew tap hakkisagdic/context-manager @@ -60,11 +63,13 @@ brew upgrade context-manager ``` #### Option 2: NPM + ```bash npm install -g @hakkisagdic/context-manager ``` #### Option 3: Installation Script + ```bash curl -fsSL https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/install.sh | bash ``` @@ -72,18 +77,20 @@ curl -fsSL https://raw.githubusercontent.com/hakkisagdic/context-manager/main/sc ### Linux #### Option 1: Debian/Ubuntu (APT) + ```bash # Download DEB package -wget https://github.com/hakkisagdic/context-manager/releases/download/v2.3.5/context-manager_2.3.5_all.deb +wget https://github.com/hakkisagdic/context-manager/releases/download/v3.0.0/context-manager_3.0.0_all.deb # Install -sudo dpkg -i context-manager_2.3.5_all.deb +sudo dpkg -i context-manager_3.0.0_all.deb # Install dependencies if needed sudo apt-get install -f ``` #### Option 2: Red Hat/Fedora (YUM/DNF) + ```bash # Coming soon - RPM package # For now, use NPM: @@ -91,11 +98,13 @@ npm install -g @hakkisagdic/context-manager ``` #### Option 3: NPM (Universal) + ```bash npm install -g @hakkisagdic/context-manager ``` #### Option 4: Installation Script + ```bash curl -fsSL https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/install.sh | bash ``` @@ -103,11 +112,13 @@ curl -fsSL https://raw.githubusercontent.com/hakkisagdic/context-manager/main/sc ### Windows #### Option 1: NPM (Recommended) + ```powershell npm install -g @hakkisagdic/context-manager ``` #### Option 2: PowerShell Script + ```powershell # Run as Administrator Set-ExecutionPolicy Bypass -Scope Process -Force @@ -115,6 +126,7 @@ irm https://raw.githubusercontent.com/hakkisagdic/context-manager/main/scripts/i ``` #### Option 3: Manual Download + 1. Download from: https://github.com/hakkisagdic/context-manager/releases 2. Extract to: `C:\Program Files\context-manager` 3. Add to PATH: `C:\Program Files\context-manager\bin` @@ -133,7 +145,7 @@ npm install -g @hakkisagdic/context-manager npm install @hakkisagdic/context-manager # Specific version -npm install -g @hakkisagdic/context-manager@2.3.5 +npm install -g @hakkisagdic/context-manager@3.0.0 # Insider/pre-release npm install -g @hakkisagdic/context-manager@next @@ -222,31 +234,6 @@ context-manager convert test.json --from json --to toon ## 🎨 Optional Dependencies -Context Manager has **optional interactive features** that require additional dependencies. - -### Interactive Wizard & Dashboard - -These features use React + Ink for beautiful terminal UI: - -```bash -# Install interactive dependencies -npm install -g ink react ink-select-input ink-text-input ink-spinner - -# Or with the package -npm install -g @hakkisagdic/context-manager -``` - -**Features Enabled:** -- ✨ Interactive Wizard (`--wizard`) -- 📊 Live Dashboard (`--dashboard`) -- 🎨 Progress bars and spinners -- ⌨️ Keyboard navigation - -**Without these dependencies:** -- Tool still works perfectly -- Uses simple text-based output -- All core features available - ### Exact Token Counting For exact GPT-4 token counting (optional): @@ -256,9 +243,11 @@ npm install -g tiktoken ``` **With tiktoken:** + - ✅ Exact token counts (100% accuracy) **Without tiktoken:** + - ✅ Smart estimation (~95% accuracy) --- @@ -305,6 +294,7 @@ Remove-Item -Path $env:USERPROFILE\.context-manager -Recurse ### "command not found: context-manager" **Solution:** + ```bash # Check PATH echo $PATH @@ -317,6 +307,7 @@ source ~/.bashrc # or ~/.zshrc ### Permission Denied **Linux/macOS:** + ```bash # Use sudo for global install sudo npm install -g @hakkisagdic/context-manager @@ -326,6 +317,7 @@ npm install @hakkisagdic/context-manager ``` **Windows:** + ```powershell # Run PowerShell as Administrator ``` @@ -355,11 +347,12 @@ npm install -g @hakkisagdic/context-manager ### Wizard/Dashboard Not Working ```bash -# Install interactive dependencies -npm install -g ink react ink-select-input ink-text-input ink-spinner - -# Or use simple mode +# Ink is bundled since v3.0.0, no manual install needed +# If wizard still doesn't work, try simple mode context-manager --simple + +# Or reinstall to ensure all bundled dependencies are present +npm install -g @hakkisagdic/context-manager ``` --- @@ -386,7 +379,7 @@ context-manager update rollback npm update -g @hakkisagdic/context-manager # Update to specific version -npm install -g @hakkisagdic/context-manager@2.3.6 +npm install -g @hakkisagdic/context-manager@3.0.0 ``` ### Homebrew @@ -400,30 +393,36 @@ brew upgrade context-manager ## 🎯 Installation Types ### Global Installation + ```bash npm install -g @hakkisagdic/context-manager ``` + ✅ Available system-wide ✅ Use from any directory ✅ Simple `context-manager` command ❌ Requires admin/sudo (sometimes) ### Local Installation + ```bash npm install @hakkisagdic/context-manager ``` + ✅ No admin rights needed ✅ Project-specific version ❌ Use via `npx` or npm scripts ❌ Not in system PATH ### Source Installation (Developers) + ```bash git clone https://github.com/hakkisagdic/context-manager.git cd context-manager npm install npm link # Make globally available ``` + ✅ Latest development version ✅ Easy to contribute ❌ Manual updates required @@ -450,6 +449,6 @@ After installation: --- -**Version:** 2.3.6+ +**Version:** 3.0.0 **Maintainer:** Hakkı Sağdıç **License:** MIT diff --git a/docs/WIZARD-DASHBOARD-SETUP.md b/docs/WIZARD-GUIDE.md similarity index 60% rename from docs/WIZARD-DASHBOARD-SETUP.md rename to docs/WIZARD-GUIDE.md index 54714c1..3b33f18 100644 --- a/docs/WIZARD-DASHBOARD-SETUP.md +++ b/docs/WIZARD-GUIDE.md @@ -1,23 +1,24 @@ -# Interactive Wizard & Dashboard - Setup Guide +# Interactive Wizard, Dashboard & UI Demo Guide -**Version:** 2.3.5 -**Status:** Optional Features (Requires Additional Dependencies) -**Last Updated:** November 3, 2025 +**Version:** 3.0.0 +**Status:** Production Ready (Requires Additional Dependencies) +**Last Updated:** April 2, 2026 --- -## 📋 Overview +## Overview -Context Manager v2.3.0+ includes two powerful interactive features: +Context Manager v3.0.0 includes three powerful interactive features: -1. **🧙 Interactive Wizard** - Guided configuration for context generation -2. **📊 Live Dashboard** - Real-time analysis with visual stats +1. **Interactive Wizard** - Guided configuration for context generation +2. **Live Dashboard** - Real-time analysis with visual stats +3. **UI Demo** - Interactive test screen for all Ink UI components These features are **optional** and require additional dependencies (React + Ink) to function. --- -## ⚡ Quick Start +## Quick Start ### Install Interactive Features @@ -26,9 +27,10 @@ cd /path/to/context-manager npm install ``` -This will install all dependencies including: -- `ink@^4.4.1` - React-based terminal UI framework -- `react@^18.2.0` - React library +This installs all dependencies including: + +- `ink@^6.0.0` - React-based terminal UI framework +- `react@^19.0.0` - React library - `ink-spinner@^5.0.0` - Loading spinners - `ink-select-input@^5.0.0` - Interactive selection - `ink-text-input@^5.0.1` - Text input component @@ -41,22 +43,34 @@ context-manager --wizard # Try dashboard context-manager --dashboard + +# Try UI demo +npm run test:ink ``` If dependencies are missing, you'll see: + ``` -⚠️ Interactive wizard requires additional dependencies. + Interactive wizard requires additional dependencies. Install: npm install ink react ink-select-input ink-text-input Falling back to standard mode... ``` +### Requirements + +- Node.js 14+ +- Ink dependencies installed (`npm install`) +- Interactive terminal (iTerm2, Terminal.app, gnome-terminal) +- Not supported: VSCode integrated terminal (Raw mode not supported) + --- -## 🧙 Interactive Wizard +## Interactive Wizard ### What is the Wizard? The wizard provides a **step-by-step guided experience** for configuring your context generation. Perfect for: + - First-time users - Complex configurations - Quick setup for common use cases @@ -71,6 +85,7 @@ context-manager --wizard ### Wizard Flow #### Step 1: Select Your Use Case + ``` ┌──────────────────────────────────────────────────────────┐ │ Context Generation Wizard │ @@ -91,23 +106,25 @@ context-manager --wizard ``` **Controls:** + - `↑↓` - Navigate options - `Enter` - Select and continue - `Esc` - Cancel wizard **Use Case Templates:** -| Use Case | Includes | Best For | -|----------|----------|----------| -| 🐛 Bug Fix | Changed files + related code | Fixing specific issues | -| ✨ New Feature | Core modules + architecture | Adding functionality | -| 👀 Code Review | Full context with tests | Reviewing PRs | -| ♻️ Refactoring | Target modules + dependencies | Code improvements | -| 🔒 Security Audit | Security-critical files | Security review | -| 📚 Documentation | Code + existing docs | Writing docs | -| ⚙️ Custom | Full customization | Special cases | +| Use Case | Includes | Best For | +| -------------- | ----------------------------- | ---------------------- | +| Bug Fix | Changed files + related code | Fixing specific issues | +| New Feature | Core modules + architecture | Adding functionality | +| Code Review | Full context with tests | Reviewing PRs | +| Refactoring | Target modules + dependencies | Code improvements | +| Security Audit | Security-critical files | Security review | +| Documentation | Code + existing docs | Writing docs | +| Custom | Full customization | Special cases | #### Step 2: Select Target AI Model + ``` ┌──────────────────────────────────────────────────────────┐ │ Which AI model will you use? │ @@ -122,11 +139,13 @@ context-manager --wizard ``` **Why this matters:** + - Wizard optimizes output to fit token limits - Suggests chunking for large projects - Recommends best format for your model #### Step 3: Choose What to Include + ``` ┌──────────────────────────────────────────────────────────┐ │ What should be included in the context? │ @@ -143,11 +162,13 @@ context-manager --wizard ``` **Controls:** -- `Space` - Toggle selection (◯ ↔ ◉) + +- `Space` - Toggle selection - `Enter` - Continue to next step - `Esc` - Go back #### Step 4: Select Output Format + ``` ┌──────────────────────────────────────────────────────────┐ │ Choose output format: │ @@ -162,18 +183,19 @@ context-manager --wizard **Format Comparison:** -| Format | Token Efficiency | Readability | Use Case | -|--------|------------------|-------------|----------| -| TOON | ⭐⭐⭐⭐⭐ (best) | ⭐⭐⭐ | Most efficient, LLM-optimized | -| JSON | ⭐⭐⭐ | ⭐⭐⭐⭐ | Standard, widely supported | -| YAML | ⭐⭐ | ⭐⭐⭐⭐⭐ | Human-readable configs | -| GitIngest | ⭐⭐⭐⭐ | ⭐⭐⭐ | Single-file digest | -| Markdown | ⭐⭐ | ⭐⭐⭐⭐⭐ | Documentation | +| Format | Token Efficiency | Readability | Use Case | +| --------- | ---------------- | ----------- | ----------------------------- | +| TOON | Best | Good | Most efficient, LLM-optimized | +| JSON | Medium | Good | Standard, widely supported | +| YAML | Low | Best | Human-readable configs | +| GitIngest | High | Good | Single-file digest | +| Markdown | Low | Best | Documentation | #### Step 5: Review & Confirm + ``` ┌──────────────────────────────────────────────────────────┐ -│ 📊 Configuration Summary │ +│ Configuration Summary │ ├──────────────────────────────────────────────────────────┤ │ │ │ Use Case: Bug Fix │ @@ -182,7 +204,7 @@ context-manager --wizard │ Format: TOON │ │ Estimated tokens: 12,450 │ │ │ -│ ✅ Within token limit (6.2% of 200k) │ +│ Within token limit (6.2% of 200k) │ │ │ │ [Enter] Start Analysis [Esc] Go Back │ └──────────────────────────────────────────────────────────┘ @@ -191,30 +213,31 @@ context-manager --wizard ### After Wizard Completion ```bash -✅ Analysis complete! +Analysis complete! Generated: context-bug-fix.toon Size: 12,450 tokens Files included: 45 -📋 Next steps: +Next steps: 1. Copy to clipboard? (y/n) y -✅ Copied to clipboard! +Copied to clipboard! 2. Open in editor? (y/n) n 3. Save to different format? (y/n) n -🎉 Done! Ready to paste into your AI assistant. +Done! Ready to paste into your AI assistant. ``` --- -## 📊 Live Dashboard +## Live Dashboard ### What is the Dashboard? The dashboard provides **real-time visual feedback** during analysis. Features: + - Live progress bars - File-by-file status - Token counting in real-time @@ -239,7 +262,7 @@ context-manager --dashboard --watch │ Live Analysis Dashboard │ ├──────────────────────────────────────────────────────────┤ │ │ -│ 📊 Project Analysis │ +│ Project Analysis │ │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 67% (43/64 files) │ │ │ │ Current: src/analyzers/method-analyzer.js │ @@ -260,7 +283,7 @@ After analysis completes: ``` ┌──────────────────────────────────────────────────────────┐ -│ 📊 Analysis Complete │ +│ Analysis Complete │ ├──────────────────────────────────────────────────────────┤ │ │ │ Files: 64 Methods: 347 Tokens: 181,480 │ @@ -280,14 +303,14 @@ After analysis completes: ### Dashboard Controls -| Key | Action | Description | -|-----|--------|-------------| -| `R` | Refresh | Re-run analysis (in watch mode) | -| `S` | Save | Save current report to file | -| `E` | Export | Export to different format | -| `Q` | Quit | Exit dashboard | -| `↑↓` | Navigate | Scroll through file list | -| `Space` | Toggle | Expand/collapse sections | +| Key | Action | Description | +| ------- | -------- | ------------------------------- | +| `R` | Refresh | Re-run analysis (in watch mode) | +| `S` | Save | Save current report to file | +| `E` | Export | Export to different format | +| `Q` | Quit | Exit dashboard | +| `↑↓` | Navigate | Scroll through file list | +| `Space` | Toggle | Expand/collapse sections | ### Watch Mode @@ -298,12 +321,13 @@ context-manager --dashboard --watch ``` ``` -🔄 File changed: src/utils/helper.js -⚡ Re-analyzing... (1.2s) -✅ Updated! Tokens: 181,480 → 182,105 (+625) +File changed: src/utils/helper.js +Re-analyzing... (1.2s) +Updated! Tokens: 181,480 → 182,105 (+625) ``` **Perfect for:** + - Live coding sessions - Watching token count while editing - Monitoring large refactors @@ -311,16 +335,218 @@ context-manager --dashboard --watch --- -## 🐛 Troubleshooting +## Interactive UI Demo + +### Running the Demo + +```bash +# NPM script (recommended) +npm run test:ink + +# Or directly +node test/test-ink-ui.js +``` + +### Demo Menu + +Launching the test screen shows: + +``` +╔══════════════════════════════════════════════════════════╗ +║ Ink UI Test Screen ║ +║ ║ +║ Select a test to run: ║ +║ ║ +║ ❯ Test Colors ║ +║ Test Progress Bar ║ +║ Test Spinners ║ +║ Test Input ║ +║ Test Wizard ║ +║ Test Dashboard ║ +║ ❌ Exit ║ +║ ║ +║ [↑↓] Navigate [Enter] Select [Q] Quit ║ +╚══════════════════════════════════════════════════════════╝ +``` + +### Test Options + +#### 1. Test Colors + +All color palettes and text styles: + +``` +Color Test + +Red Text +Green Text +Yellow Text +Blue Text +Magenta Text +Cyan Text + +Bold Dim +``` + +Tests: color options (red, green, yellow, blue, magenta, cyan), text styles (bold, dim, italic, underline), color combinations. + +#### 2. Test Progress Bar + +Animated progress bar: + +``` +Progress Bar Test + +Progress: 67% +▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░ +Processing... +``` + +Features: real-time progress (0-100%), visual bar with filled/empty states, auto-completes in ~4 seconds. + +#### 3. Test Spinners + +Multiple spinner types: + +``` +Spinner Test + +⠋ Scanning files... +⠙ Calculating tokens... +✓ Analysis complete! +``` + +Spinner types: Dots, Line, Status indicators. + +#### 4. Test Input + +Interactive text input with live typing, onChange events, placeholder text, and real-time feedback. + +#### 5. Test Wizard + +Full wizard flow (3 steps): + +1. Use Case Selection - 7 options +2. Target Model - 6 AI models +3. Output Format - 6 formats +4. Summary & Complete + +#### 6. Test Dashboard + +Live stats dashboard showing files, methods, tokens, language distribution, and largest files ranking. + +### What's Being Tested + +**Components:** + +- Box (layout, flexbox, borders, padding) +- Text (colors, styles, formatting) +- SelectInput (navigation, selection) +- TextInput (typing, onChange) +- Spinner (animations, types) +- Newline, Spacer + +**Features:** + +- State management (useState) +- Effects (useEffect for animations) +- Input handling (useInput) +- Conditional rendering +- Component composition +- Props injection (ESM workaround) + +**Custom Components:** + +- Wizard (3-step flow) +- Dashboard (live stats) +- ProgressBar (with components prop) + +### Success Criteria + +The demo is successful when: + +1. Menu renders correctly +2. Arrow key navigation works +3. Selections work +4. Each test screen displays +5. Wizard completes all steps +6. Dashboard shows stats +7. Q key exits properly + +--- + +## Platform-Specific Setup + +### macOS + +```bash +# iTerm2 (recommended) +open -a iTerm +cd /path/to/context-manager +npm run test:ink + +# Terminal.app +open -a Terminal +cd /path/to/context-manager +npm run test:ink +``` + +### Linux + +```bash +# GNOME Terminal +gnome-terminal -- bash -c "cd /path/to/context-manager && npm run test:ink" + +# Konsole (KDE) +konsole -e "cd /path/to/context-manager && npm run test:ink" +``` + +### Windows + +```powershell +# Windows Terminal (recommended) +wt.exe -d C:\path\to\context-manager npm run test:ink + +# PowerShell +cd C:\path\to\context-manager +npm run test:ink +``` + +--- + +## Troubleshooting + +### "Raw mode is not supported" + +``` +ERROR Raw mode is not supported on the current process.stdin +``` + +This error is normal in automated test environments. Interactive features require a real terminal. + +**Works on:** + +- iTerm2 (macOS) +- Terminal.app (macOS) +- gnome-terminal (Linux) +- Windows Terminal +- PowerShell (Windows) + +**Does not work on:** + +- VSCode integrated terminal +- CI/CD pipelines +- SSH sessions (in some cases) +- Piped input/output ### Wizard/Dashboard Not Starting -**Symptom:** ``` -⚠️ Interactive wizard requires additional dependencies. + Interactive wizard requires additional dependencies. ``` **Solution:** + ```bash # Install all dependencies npm install @@ -334,11 +560,13 @@ npm install ink react ink-select-input ink-text-input ink-spinner **Symptom:** Weird characters, broken layout, no colors **Possible Causes:** + 1. Terminal doesn't support ANSI colors 2. Old terminal emulator 3. SSH session without proper TTY **Solutions:** + ```bash # Option 1: Use simple mode context-manager --simple @@ -356,13 +584,13 @@ echo $TERM ### React/Ink Errors -**Symptom:** ``` Error: Cannot find module 'react' Error: Cannot find module 'ink' ``` **Solution:** + ```bash # Clear node_modules and reinstall rm -rf node_modules package-lock.json @@ -374,14 +602,29 @@ npm install **Symptom:** Wizard starts but becomes unresponsive **Solutions:** + 1. Press `Esc` to cancel 2. Use `Ctrl+C` to force quit 3. Check terminal size (min 80x24) 4. Disable terminal multiplexers temporarily (tmux, screen) +### Dependencies Missing + +```bash +# List installed packages +npm list --depth=0 | grep -E "ink|react" + +# Should show: +# ├── ink@6.0.0 +# ├── ink-select-input@5.0.0 +# ├── ink-spinner@5.0.0 +# ├── ink-text-input@5.0.1 +# └── react@19.0.0 +``` + --- -## 📝 Fallback to Standard Mode +## Fallback to Standard Mode If interactive features don't work, you can always use standard CLI mode: @@ -398,7 +641,7 @@ cat token-analysis-report.json --- -## 💡 Pro Tips +## Pro Tips ### 1. Combine Wizard with Profiles @@ -431,27 +674,22 @@ fi ### 3. Custom Terminal Theme Dashboard adapts to your terminal theme automatically. For best experience: + - Use dark theme for better contrast - Ensure 256-color support - Use monospace font (Fira Code, JetBrains Mono) ---- - -## 🆘 Getting Help +### 4. Recording a Demo Video -### Check Dependencies +1. Open terminal (iTerm2 recommended) +2. Clear screen: `clear` +3. Start demo: `npm run test:ink` +4. Navigate menu: Colors → Progress → Wizard → Dashboard +5. Stop recording: press `Q` -```bash -# List installed packages -npm list --depth=0 | grep -E "ink|react" +--- -# Should show: -# ├── ink@4.4.1 -# ├── ink-select-input@5.0.0 -# ├── ink-spinner@5.0.0 -# ├── ink-text-input@5.0.1 -# └── react@18.2.0 -``` +## Testing & Verification ### Test Interactive Features @@ -461,26 +699,41 @@ node bin/cli.js --wizard # Test dashboard (should not fallback) node bin/cli.js --dashboard + +# Test UI demo +npm run test:ink ``` -### Report Issues +### Production Usage -If wizard/dashboard still don't work after installing dependencies: +After verifying the demo works, use the production commands: + +```bash +# Production wizard +context-manager --wizard + +# Production dashboard +context-manager --dashboard + +# Dashboard with watch mode +context-manager --dashboard --watch +``` + +--- -1. Check Node.js version: `node --version` (should be 14+) -2. Check terminal: `echo $TERM` -3. Open issue: https://github.com/hakkisagdic/context-manager/issues +## Related Files -Include: -- Node.js version -- Terminal app & version -- OS & version -- Error messages -- Output of `npm list ink react` +| File | Description | +| ---------------------------- | ---------------------- | +| `test/test-ink-ui.js` | Interactive demo app | +| `test/INK-UI-TEST-README.md` | Demo usage guide | +| `lib/ui/wizard.js` | Wizard component | +| `lib/ui/dashboard.js` | Dashboard component | +| `lib/ui/progress-bar.js` | Progress bar component | --- -## 📚 Additional Resources +## Additional Resources - **Feature Examples:** [FEATURE-EXAMPLES.md](./FEATURE-EXAMPLES.md) - **Main README:** [../README.md](../README.md) @@ -489,6 +742,9 @@ Include: --- -**Version:** 2.3.5 -**Last Updated:** November 3, 2025 +**Version:** 3.0.0 +**Ink Version:** 6.x +**React Version:** 19.x +**Requires:** Interactive TTY terminal +**Not Supported:** VSCode integrated terminal, CI/CD **Maintainer:** Hakkı Sağdıç diff --git a/docs/content-en/Advanced Configuration.md b/docs/content-en/Advanced Configuration.md deleted file mode 100644 index 710105c..0000000 --- a/docs/content-en/Advanced Configuration.md +++ /dev/null @@ -1,345 +0,0 @@ -# Advanced Configuration - - -**Referenced Files in This Document** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) - - -## Table of Contents -1. [Introduction](#introduction) -2. [Configuration File Priority](#configuration-file-priority) -3. [Custom Filter Patterns](#custom-filter-patterns) -4. [Advanced Pattern Syntax](#advanced-pattern-syntax) -5. [Performance Optimization](#performance-optimization) -6. [Integration and Scripting](#integration-and-scripting) -7. [Best Practices](#best-practices) -8. [Troubleshooting](#troubleshooting) - -## Introduction - -The context-manager tool provides sophisticated configuration options for controlling which files and methods are included in token analysis and LLM context generation. This document details advanced configuration techniques for specialized use cases, focusing on custom filter patterns, priority hierarchies, and performance optimization strategies. - -**Section sources** -- [README.md](file://README.md#L1-L891) - -## Configuration File Priority - -The context-manager tool implements a well-defined priority hierarchy for configuration files that determines how files are included or excluded from analysis. This hierarchy ensures predictable behavior when multiple configuration files are present. - -The priority order from highest to lowest is: - -1. **`.contextinclude`** - INCLUDE mode (highest priority) -2. **`.contextignore`** - EXCLUDE mode -3. **`.gitignore`** - Standard git exclusions (always respected) - -When `.contextinclude` exists, the tool operates in INCLUDE mode, meaning only files matching the patterns in this file will be analyzed, and `.contextignore` is completely ignored. When only `.contextignore` exists, the tool operates in EXCLUDE mode, analyzing all files except those matching the ignore patterns. The `.gitignore` file is always respected regardless of the mode. - -```mermaid -graph TD -A[Start Analysis] --> B{.contextinclude exists?} -B --> |Yes| C[INCLUDE Mode] -B --> |No| D{.contextignore exists?} -D --> |Yes| E[EXCLUDE Mode] -D --> |No| F[Include All Files] -C --> G[Analyze only files matching .contextinclude patterns] -E --> H[Analyze all except files matching .contextignore patterns] -F --> I[Analyze all files, respecting .gitignore] -G --> J[Respect .gitignore exclusions] -H --> J -I --> J -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L231-L800) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L124-L229) - -## Custom Filter Patterns - -The context-manager tool supports creating custom filter patterns for specialized use cases through both file-level and method-level filtering mechanisms. - -### File-Level Filtering - -File-level filtering is controlled through `.contextinclude` and `.contextignore` files. These files support glob patterns for flexible file selection: - -- `**/*.md` - Exclude all markdown files recursively -- `infrastructure/**` - Exclude entire infrastructure directory -- `utility-mcp/src/**/*.js` - Include all JavaScript files in src directory -- `!utility-mcp/src/testing/**` - Negation pattern to exclude testing files - -For focusing on specific feature areas, create a `.contextinclude` file with patterns targeting the desired directories: - -```bash -# Include only authentication-related files -src/auth/**/*.js -src/middleware/auth.js -config/auth-config.json -``` - -For excluding legacy code, use negation patterns in `.contextinclude`: - -```bash -# Include all core files but exclude legacy modules -src/**/*.js -!src/legacy/** -!src/deprecated/** -``` - -### Method-Level Filtering - -Method-level filtering allows even more granular control through `.methodinclude` and `.methodignore` files. These support pattern matching for method names: - -- `*Handler` - Include all methods ending with 'Handler' -- `*Validator` - Include all methods ending with 'Validator' -- `TokenCalculator.*` - Include all methods in TokenCalculator class -- `server.printStatus` - Include specific file method -- `*test*` - Exclude all methods containing 'test' - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : boolean -+parseMethodFile(filePath) : Array -+shouldIncludeMethod(methodName, fileName) : boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+initMethodFilter() : MethodFilterParser -+analyzeFileMethods(content, filePath) : Array -} -TokenCalculator --> MethodFilterParser : "uses" -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L75-L115) -- [context-manager.js](file://context-manager.js#L231-L800) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L75-L115) - -## Advanced Pattern Syntax - -The context-manager tool implements sophisticated pattern syntax for both file and method filtering, supporting complex negation rules, directory-specific patterns, and combined include/exclude logic. - -### Pattern Conversion and Matching - -The `convertToRegex` method in GitIgnoreParser converts glob patterns to regular expressions with specific rules: - -- `**` is converted to `.*` (matches any number of directories) -- `*` is converted to `[^/]*` (matches any characters except path separators) -- `?` is converted to `[^/]` (matches any single character except path separator) -- Patterns starting with `/` are anchored to the root directory -- Directory patterns ending with `/` match the directory and all contents - -```mermaid -flowchart TD -A[Raw Pattern] --> B{Process Pattern} -B --> C[Remove leading /!] -B --> D[Remove trailing /] -C --> E[Escape special chars] -D --> E -E --> F[Replace ** with .*] -F --> G[Replace * with [^/]*] -G --> H[Replace ? with [^/]] -H --> I{Starts with /?} -I --> |Yes| J[Anchor to ^] -I --> |No| K[Add (^|/) prefix] -J --> L{Ends with /?} -K --> L -L --> |Yes| M[Add (/.*?)?$ suffix] -L --> |No| N[Add $ suffix] -M --> O[Complete Regex] -N --> O -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L159-L179) - -**Section sources** -- [context-manager.js](file://context-manager.js#L159-L179) - -### Complex Negation Rules - -The tool handles negation patterns (`!pattern`) with specific precedence rules. In INCLUDE mode, negation patterns exclude files from otherwise broad inclusion patterns. In EXCLUDE mode, negation patterns can re-include files that would otherwise be excluded. - -When multiple negation patterns exist, they are processed in order, with later patterns taking precedence over earlier ones. This allows for sophisticated filtering logic: - -```bash -# Include all JS files but exclude test and legacy code -src/**/*.js -!src/**/*.test.js -!src/legacy/** -!src/deprecated/** -``` - -## Performance Optimization - -The context-manager tool includes several performance optimization techniques to improve analysis speed and reduce resource usage. - -### Directory-Specific Analysis - -The tool searches for configuration files in two locations: the tool directory (`__dirname`) and the project root (`this.projectRoot`). This allows for both global and project-specific configurations without requiring configuration files in every project. - -```javascript -findConfigFile(filename) { - const locations = [ - path.join(__dirname, filename), - path.join(this.projectRoot, filename) - ]; - return locations.find(loc => fs.existsSync(loc)); -} -``` - -### Result Caching and Efficient Processing - -While the current implementation doesn't include explicit caching, it optimizes performance through: - -- **Efficient file scanning**: Skips common directories like `node_modules`, `.git`, and `dist` -- **Batch processing**: Processes all files in a directory before moving to subdirectories -- **Minimal I/O operations**: Reads configuration files only once at initialization - -For large projects, consider limiting analysis to specific directories by configuring `.contextinclude` to target only the relevant areas: - -```bash -# Focus analysis on core modules only -src/core/**/*.js -src/services/**/*.js -src/api/**/*.js -``` - -```mermaid -flowchart TD -A[Start Analysis] --> B[Scan Directory] -B --> C{Directory in exclude list?} -C --> |Yes| D[Skip Directory] -C --> |No| E[Process Files] -E --> F{File is directory?} -F --> |Yes| G[Recurse into Directory] -F --> |No| H{Text file?} -H --> |No| I[Skip File] -H --> |Yes| J[Check GitIgnore] -J --> K{Ignored?} -K --> |Yes| L[Count as ignored] -K --> |No| M[Analyze File] -M --> N[Update Statistics] -D --> O[Continue] -I --> O -L --> O -N --> O -G --> B -O --> P{More items?} -P --> |Yes| B -P --> |No| Q[Complete] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L272-L278) -- [context-manager.js](file://context-manager.js#L380-L400) - -**Section sources** -- [context-manager.js](file://context-manager.js#L272-L278) - -## Integration and Scripting - -The context-manager tool provides multiple integration points for use in automated workflows and custom scripts. - -### Programmatic Usage - -The tool can be used programmatically by importing the TokenAnalyzer class: - -```javascript -const { TokenAnalyzer } = require('@hakkisagdic/context-manager'); - -const analyzer = new TokenAnalyzer('./src', { - methodLevel: true, - saveReport: true, - verbose: true -}); - -analyzer.run(); -``` - -### Export Formats - -The tool supports multiple export formats for different use cases: - -- **Detailed JSON report**: Comprehensive analysis data for CI/CD pipelines -- **LLM context file**: Optimized file list for AI assistants -- **Clipboard export**: Direct copying of context for immediate use - -The `saveDetailedReport` method generates a structured JSON report containing metadata, summary statistics, and detailed file information: - -```mermaid -erDiagram -METADATA { -string generatedAt PK -string projectRoot -array gitignoreRules -array calculatorRules -} -SUMMARY { -number totalFiles -number totalTokens -number totalBytes -number totalLines -object byExtension -object byDirectory -array largestFiles -} -FILE { -string path PK -string relativePath -number sizeBytes -number tokens -number lines -string extension -array methods -} -METADATA ||--o{ SUMMARY : contains -SUMMARY ||--o{ FILE : contains -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L784-L799) - -**Section sources** -- [context-manager.js](file://context-manager.js#L784-L799) - -## Best Practices - -### Configuration File Management - -- **Use descriptive pattern comments**: Add comments to explain the purpose of complex patterns -- **Organize by category**: Group related patterns together (e.g., all test exclusions) -- **Test configurations**: Use verbose mode to verify that the expected files are included/excluded -- **Version control**: Include configuration files in version control to ensure consistency across environments - -### Performance Considerations - -- **Limit scope**: Use `.contextinclude` to focus on relevant code areas -- **Avoid overly broad patterns**: Specific patterns are more efficient than broad ones with many negations -- **Regular maintenance**: Periodically review and update patterns as the codebase evolves -- **Cache results**: For CI/CD pipelines, consider caching analysis results when source files haven't changed - -## Troubleshooting - -### Common Issues - -- **Patterns not working**: Ensure no inline comments in pattern files and use proper glob syntax -- **Wrong files included**: Check if `.contextinclude` exists (takes priority over `.contextignore`) -- **Performance issues**: Limit analysis to specific directories using targeted include patterns -- **Missing expected files**: Verify files are not excluded by `.gitignore` (always respected) - -### Debugging Tips - -- Use `--verbose` flag to see which files are being included/excluded -- Check the console output for configuration mode (INCLUDE/EXCLUDE) -- Verify pattern syntax using glob pattern testers -- Test patterns with small, isolated codebases before applying to large projects \ No newline at end of file diff --git a/docs/content-en/CLI Reference.md b/docs/content-en/CLI Reference.md deleted file mode 100644 index 6eb1e49..0000000 --- a/docs/content-en/CLI Reference.md +++ /dev/null @@ -1,300 +0,0 @@ -# CLI Reference - - -**Referenced Files in This Document** -- [bin/cli.js](file://bin/cli.js) - *Updated in commit 6f5fea32* -- [context-manager.js](file://context-manager.js) - *Updated in commit 6f5fea32 and 0b9cbab0* -- [README.md](file://README.md) - *Updated in both commits* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in commit 6f5fea32* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Added in commit 6f5fea32* - - -## Update Summary -**Changes Made** -- Added comprehensive documentation for new GitIngest functionality and JSON-based digest generation -- Updated available options section with new CLI flags: --gitingest (-g), --gitingest-from-report, and --gitingest-from-context -- Enhanced method-level analysis documentation with details about method filtering configuration -- Added new section for GitIngest format export with usage examples and output format details -- Updated usage examples to include new command combinations -- Expanded section sources to include newly added formatter and parser files - -## Table of Contents -1. [Introduction](#introduction) -2. [Command Syntax](#command-syntax) -3. [Available Options](#available-options) -4. [Interactive Export Selection](#interactive-export-selection) -5. [Usage Examples](#usage-examples) -6. [GitIngest Format Export](#gitingest-format-export) -7. [Exit Codes and Error Handling](#exit-codes-and-error-handling) -8. [Performance Considerations](#performance-considerations) -9. [Shell Script Integration](#shell-script-integration) -10. [Troubleshooting Guide](#troubleshooting-guide) - -## Introduction -The context-manager CLI provides a comprehensive tool for analyzing codebases and optimizing context for LLM consumption. It offers method-level filtering, exact token counting, and multiple export formats to support AI-assisted development workflows. The tool respects both .gitignore and custom ignore/include rules, providing flexible configuration options for different analysis scenarios. - -**Section sources** -- [README.md](file://README.md#L0-L891) - -## Command Syntax -The basic syntax for the context-manager CLI is: -``` -context-manager [options] -``` - -The command accepts various options that control the analysis behavior, output format, and export destinations. When no options are specified, the tool runs in interactive mode, prompting the user to select export options after completing the analysis. - -**Section sources** -- [bin/cli.js](file://bin/cli.js#L4-L25) -- [context-manager.js](file://context-manager.js#L815-L830) - -## Available Options -The context-manager CLI supports the following options: - -### --save-report (-s) -Saves a detailed JSON report of the analysis to token-analysis-report.json in the project root. - -**Behavior**: Generates a comprehensive report containing metadata, summary statistics, and detailed information about each analyzed file. - -**Return value**: Creates token-analysis-report.json file with structured analysis data. - -### --no-verbose -Disables verbose output mode, suppressing the display of included files and directories during analysis. - -**Behavior**: Runs the analysis without showing the list of files being processed, providing a cleaner output. - -**Return value**: Standard analysis report without file listing details. - -### --context-export -Generates an LLM context file list and saves it as llm-context.json in the project root. - -**Behavior**: Creates a JSON file containing optimized project context suitable for LLM consumption. - -**Return value**: Creates llm-context.json file with project metadata and organized file paths. - -### --context-clipboard -Copies the LLM context directly to the system clipboard. - -**Behavior**: Generates the context in JSON format and copies it to the clipboard using platform-specific commands (pbcopy on macOS, xclip/xsel on Linux, clip on Windows). - -**Return value**: Context data copied to clipboard; displays character count upon success. - -### --detailed-context -Uses the detailed context format instead of the default compact format. - -**Behavior**: Generates a more comprehensive context output with additional metadata, categories, and importance scores. - -**Return value**: Larger context output (~8.6k characters) with enhanced information. - -### --method-level (-m) -Enables method-level analysis mode. - -**Behavior**: Extracts and analyzes individual methods from JavaScript/TypeScript files, applying method-level filtering rules from .methodinclude and .methodignore files. - -**Return value**: Includes method-specific information in the output, including method names, line numbers, and token counts. - -### --gitingest (-g) -Generates a GitIngest-style digest file for LLM consumption. - -**Behavior**: Creates a single text file (digest.txt) containing project summary, directory structure, and complete file contents with clear separators. - -**Return value**: Creates digest.txt file with consolidated codebase information in a prompt-friendly format. - -### --gitingest-from-report -Generates a GitIngest digest from an existing token-analysis-report.json file. - -**Behavior**: Reads the JSON report and generates a digest without re-scanning the codebase, enabling fast digest generation. - -**Return value**: Creates digest.txt file with content derived from the report data. - -### --gitingest-from-context -Generates a GitIngest digest from an existing llm-context.json file. - -**Behavior**: Reads the LLM context file and generates a digest without re-scanning the codebase, enabling fast digest generation. - -**Return value**: Creates digest.txt file with content derived from the context data. - -### --help (-h) -Displays the help message with available options and usage examples. - -**Behavior**: Prints the help text to stdout and exits. - -**Return value**: None; terminates the program after displaying help. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [bin/cli.js](file://bin/cli.js#L4-L25) -- [context-manager.js](file://context-manager.js#L150-L170) - -## Interactive Export Selection -When the context-manager is run without specifying any export options (--save-report, --context-export, or --context-clipboard), it automatically activates the interactive export selection feature. After completing the analysis, the tool presents a menu with four export options: - -1. Save detailed JSON report (token-analysis-report.json) -2. Generate LLM context file (llm-context.json) -3. Copy LLM context to clipboard -4. No export (skip) - -The user is prompted to enter a number (1-4) to select their preferred export option. This interactive mode ensures that users can choose the most appropriate export format after reviewing the analysis results, preventing missed opportunities to export valuable context data. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L618-L637) - -## Usage Examples -The following examples demonstrate common command combinations: - -### Method-level analysis with clipboard export -```bash -context-manager --method-level --context-clipboard -``` -This command performs method-level analysis and copies the resulting context to the clipboard, ideal for quickly sharing focused code context with AI assistants. - -### Save report with verbose output -```bash -context-manager --save-report --verbose -``` -This combination saves a detailed JSON report while showing all included files during analysis, useful for comprehensive codebase reviews. - -### Combined analysis with multiple outputs -```bash -context-manager --method-level --save-report --context-export --verbose -``` -This command performs method-level analysis with verbose output while generating both a detailed report and an LLM context file, suitable for CI/CD pipelines and thorough codebase documentation. - -### GitIngest digest generation -```bash -context-manager --gitingest -``` -Generates a single digest.txt file containing the entire codebase in a prompt-friendly format for LLM consumption. - -### Two-step digest generation -```bash -context-manager --save-report -context-manager --gitingest-from-report token-analysis-report.json -``` -First analyzes the codebase and saves a report, then quickly generates a digest from the existing report without re-scanning. - -**Section sources** -- [README.md](file://README.md#L0-L891) - -## GitIngest Format Export -The context-manager now supports generating GitIngest-style digest files - a single, prompt-friendly text file perfect for LLM consumption. - -### What is GitIngest Format? -GitIngest format consolidates your entire codebase into a single text file with: -- Project summary and statistics -- Visual directory tree structure -- Complete file contents with clear separators -- Token count estimates - -This format is inspired by [GitIngest](https://github.com/coderamp-labs/gitingest), implemented purely in JavaScript with zero additional dependencies. - -### Usage -```bash -# Standard workflow - analyze and generate digest in one step -context-manager --gitingest -context-manager -g - -# Combine with other exports -context-manager -g -s # digest.txt + token-analysis-report.json - -# Two-step workflow - generate digest from existing JSON (fast, no re-scan) -context-manager -s # Step 1: Create report -context-manager --gitingest-from-report # Step 2: Generate digest - -# Or from LLM context -context-manager --context-export # Step 1: Create context -context-manager --gitingest-from-context # Step 2: Generate digest -``` - -### Output Format -The generated `digest.txt` file includes: -- Project name and file count -- Directory structure visualization with tree format -- Estimated token count -- File contents separated by clear delimiters -- When method-level filtering is active, only included methods are shown - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## Exit Codes and Error Handling -The context-manager CLI implements robust error handling mechanisms: - -- **Success (exit code 0)**: Analysis completed successfully with all requested operations performed. -- **Invalid option (exit code 1)**: The command was called with unrecognized or malformed options. -- **File system error (exit code 1)**: Issues accessing files or directories during analysis. -- **Clipboard error**: When clipboard operations fail, the tool falls back to saving the context to llm-context.json with a warning message. - -The tool gracefully handles missing configuration files and provides informative error messages. When tiktoken is not available for exact token counting, it falls back to smart estimation with a warning. - -**Section sources** -- [context-manager.js](file://context-manager.js#L750-L772) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Performance Considerations -When analyzing large codebases, consider the following performance optimizations: - -- Use .contextinclude to restrict analysis to essential files only -- Enable method-level analysis to focus on specific functionality -- Avoid verbose mode for large repositories to reduce output processing -- Use the compact context format for faster processing and smaller output -- Utilize JSON-based digest generation (--gitingest-from-report or --gitingest-from-context) for instant digest creation without re-scanning - -The tool is optimized for performance with efficient directory scanning and token counting algorithms. For very large codebases, the initial scan may take several seconds, but subsequent analyses benefit from the filtering rules that reduce the number of files processed. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L225-L790) - -## Shell Script Integration -The context-manager CLI can be integrated into shell scripts for automated workflows: - -```bash -# Check if codebase exceeds token budget -TOKENS=$(context-manager --context-export --no-verbose | jq '.project.totalTokens') -if [ $TOKENS -gt 100000 ]; then - echo "Codebase too large for LLM context!" - exit 1 -fi -``` - -```bash -# Daily analysis with timestamped reports -context-manager --save-report > reports/analysis-$(date +%Y%m%d).json -``` - -The tool's predictable output format and exit codes make it suitable for use in CI/CD pipelines, pre-commit hooks, and automated documentation generation workflows. - -**Section sources** -- [README.md](file://README.md#L0-L891) - -## Troubleshooting Guide -### Command not found -Ensure the package is installed globally: -```bash -npm install -g @hakkisagdic/context-manager -``` - -### Invalid options -Verify the option names and syntax. Use --help to see valid options. - -### Permission errors -On some systems, clipboard operations may require additional permissions. The tool automatically falls back to file output when clipboard access is denied. - -### Missing expected files -Check if files are excluded by .gitignore or context rules. Use verbose mode to see which files are being processed. - -### Token count discrepancies -Ensure tiktoken is installed for exact token counting. Without tiktoken, the tool uses estimation based on file type. - -### GitIngest digest issues -- Ensure the required JSON files exist when using --gitingest-from-report or --gitingest-from-context -- Check file permissions for reading and writing digest.txt -- Verify the JSON format is valid when generating from existing files - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [test/test.js](file://test/test.js#L0-L61) \ No newline at end of file diff --git a/docs/content-en/Configuration/Configuration.md b/docs/content-en/Configuration/Configuration.md deleted file mode 100644 index 96ed2b9..0000000 --- a/docs/content-en/Configuration/Configuration.md +++ /dev/null @@ -1,179 +0,0 @@ -# Configuration - - -**Referenced Files in This Document** -- [README.md](file://README.md) - *Updated with method filtering examples* -- [context-manager.js](file://context-manager.js) - *Main orchestrator with method-level analysis support* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Added in commit 6f5fea3204f18ec9d0802a00b400af1bb823e411* -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js) - *Modified to support method filter initialization* - - -## Update Summary -**Changes Made** -- Updated Method Filtering System section with implementation details from new files -- Added Pattern Syntax Guide updates based on actual code implementation -- Enhanced Configuration Examples with accurate method filtering scenarios -- Fixed outdated information about method filtering logic -- Added new section sources reflecting actual code files analyzed - -## Table of Contents -1. [File Filtering System](#file-filtering-system) -2. [Method Filtering System](#method-filtering-system) -3. [Pattern Syntax Guide](#pattern-syntax-guide) -4. [Configuration Examples](#configuration-examples) -5. [Common Configuration Issues](#common-configuration-issues) -6. [Best Practices](#best-practices) - -## File Filtering System - -The context-manager tool implements a dual-mode file filtering system that allows precise control over which files are included in token analysis. This system operates through two complementary configuration files: `.contextignore` for EXCLUDE mode and `.contextinclude` for INCLUDE mode. - -The filtering system follows a strict priority hierarchy where `.contextinclude` takes precedence over `.contextignore`. When both files exist, the tool operates in INCLUDE mode, completely ignoring the `.contextignore` file. This priority ensures that users can create focused analysis sets with precise file selection while maintaining the ability to fall back to exclusion-based filtering. - -In EXCLUDE mode (when only `.contextignore` exists), the tool includes all files except those matching patterns in the `.contextignore` file. This follows traditional gitignore-style exclusion logic and is the default mode when no `.contextinclude` file is present. The `.contextignore` file is pre-configured to exclude documentation files (`.md`, `.txt`), configuration files (`.json`, `.yml`), infrastructure and deployment files, testing directories, build artifacts, and specific code paths like `utility-mcp/src/workflows/**` and `utility-mcp/src/testing/**`. - -In INCLUDE mode (when `.contextinclude` exists), the tool includes only files matching patterns in the `.contextinclude` file, regardless of any rules in `.contextignore`. This mode provides more precise control for specific file selection and is ideal for creating focused analysis sets. The default `.contextinclude` configuration includes core JavaScript files from `utility-mcp/src/**/*.js` while using negation patterns to exclude specific subdirectories like workflows and testing utilities. - -The complete configuration file priority order is: 1) `.gitignore` (always respected), 2) `.contextinclude` (highest priority), 3) `.contextignore` (fallback when no include file exists). This layered approach ensures that standard git exclusions are always applied while providing flexible, project-specific filtering options. - -**Section sources** -- [README.md](file://README.md#L121-L150) -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L128-L151) - -## Method Filtering System - -The context-manager tool provides sophisticated method-level filtering capabilities through `.methodinclude` and `.methodignore` configuration files. These files work in conjunction with the `--method-level` command-line option to enable granular control over which methods are analyzed and included in the output. - -Method filtering operates on a similar principle to file filtering but with additional pattern matching capabilities specific to code structure. When method-level analysis is enabled, the tool parses JavaScript files to identify methods using regular expression patterns that match function declarations, method assignments, and arrow functions. The identified methods are then filtered based on the rules defined in the method configuration files. - -The `.methodinclude` file specifies which methods should be included in the analysis. When this file exists, the tool operates in INCLUDE mode for methods, meaning only methods matching the specified patterns will be included. The `.methodignore` file specifies which methods should be excluded from analysis when operating in EXCLUDE mode (when no `.methodinclude` file exists). - -The method filtering system supports several pattern types: exact method names (e.g., `calculateTokens`), wildcard patterns using `*` (e.g., `*Handler` to match all methods ending with "Handler"), class-specific methods using the `Class.*` syntax (e.g., `TokenCalculator.*` to include all methods in the TokenCalculator class), and file-specific methods using the `file.method` syntax (e.g., `server.handleRequest` to target a specific method in a specific file). - -The filtering logic is implemented in the `MethodFilterParser` class, which loads the configuration files, parses the patterns into regular expressions, and evaluates each method against these patterns. For INCLUDE mode, a method is included if it matches any pattern in the `.methodinclude` file. For EXCLUDE mode, a method is included only if it does not match any pattern in the `.methodignore` file. The system also supports negation patterns prefixed with `!` to exclude specific methods from broader inclusion rules. - -**Section sources** -- [README.md](file://README.md#L544-L610) -- [context-manager.js](file://context-manager.js#L69-L96) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L29-L50) - -## Pattern Syntax Guide - -The context-manager tool supports a comprehensive pattern syntax for both file and method filtering, enabling flexible and precise configuration. The pattern system includes wildcards, negation, and specific targeting mechanisms that allow users to create sophisticated filtering rules. - -For file patterns, the tool supports the following syntax elements: `**` for recursive matching across directories, `*` for single-level wildcard matching, and `!` for negation. The `**` wildcard matches zero or more directories, allowing patterns like `**/*.md` to match markdown files in any directory. The `*` wildcard matches any sequence of characters within a single directory level, such as `*.js` to match all JavaScript files in the current directory. Directory patterns should end with a trailing slash (e.g., `docs/`) to specifically target directories. - -Method patterns support additional syntax for code-specific filtering. In addition to the standard wildcards and negation, method patterns support class-level filtering using the `Class.*` syntax, which includes all methods within a specific class. File-specific method targeting is achieved with the `file.method` syntax, allowing precise control over individual methods in specific files. Pattern matching is case-insensitive by default, and comments can be included in configuration files by starting lines with the `#` character. - -The pattern evaluation follows specific rules: patterns are processed in order, with later patterns potentially overriding earlier ones, especially when using negation. When a negation pattern (prefixed with `!`) appears after a broader inclusion pattern, it excludes files or methods that would otherwise be included. For example, the pattern sequence `src/**/*.js` followed by `!src/**/*.test.js` includes all JavaScript files in the src directory except those with a `.test.js` extension. - -It's important to note that inline comments within pattern lines are not supported; comments must be on separate lines. Pattern syntax should be carefully validated, as incorrect patterns may lead to unexpected file inclusions or exclusions. The tool provides verbose output that shows which mode is active and can help diagnose pattern matching issues. - -**Section sources** -- [README.md](file://README.md#L544-L610) -- [README.md](file://README.md#L418) -- [context-manager.js](file://context-manager.js#L153-L173) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L25-L35) - -## Configuration Examples - -The context-manager tool provides practical configuration examples that demonstrate how to focus on core application logic or exclude test files effectively. These examples illustrate both EXCLUDE and INCLUDE mode configurations for different use cases. - -For EXCLUDE mode, users can modify the `.contextignore` file to expand or restrict the analysis scope. To include documentation files that are normally excluded, users can comment out or remove the `**/*.md` line from the `.contextignore` file. To exclude specific large files or directories, additional patterns can be added, such as `your-large-file.js` or `specific-directory/**`. The default `.contextignore` configuration focuses on core application logic by excluding documentation, configuration files, infrastructure code, workflows, and testing utilities. - -For INCLUDE mode, users create a `.contextinclude` file to specify exactly which files should be analyzed. A common pattern is to include all JavaScript files in a source directory while excluding specific subdirectories using negation. For example: -``` -# Include all JS files in src -src/**/*.js -# Exclude legacy code -!src/legacy/** -# Exclude test files -!src/**/*.test.js -``` -This configuration includes all JavaScript files in the src directory except those in the legacy subdirectory or with a `.test.js` extension. Another example focuses on core business logic by including specific entry points and source files: -``` -# Include main entry point -utility-mcp/index.js -# Include all src JavaScript files except workflows and testing -utility-mcp/src/**/*.js -!utility-mcp/src/workflows/** -!utility-mcp/src/testing/** -``` - -For method-level filtering, the `.methodinclude` file can be configured to focus on core business logic methods. Examples include: -``` -# Core business logic methods -calculateTokens -generateLLMContext -analyzeFile -handleRequest -validateInput -processData - -# Pattern matching for method categories -*Handler # All methods ending with 'Handler' -*Validator # All methods ending with 'Validator' -*Manager # All methods ending with 'Manager' -TokenCalculator.* # All methods in TokenCalculator class -``` - -Conversely, the `.methodignore` file can exclude utility and debug methods: -``` -# Exclude utility and debug methods -console -*test* -*debug* -*helper* -print* -main - -# File-specific exclusions -server.printStatus -utils.debugLog -``` - -**Section sources** -- [README.md](file://README.md#L294-L356) -- [README.md](file://README.md#L544-L610) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L37-L45) - -## Common Configuration Issues - -Users of the context-manager tool may encounter several common configuration issues related to pattern syntax, file inclusion/exclusion behavior, and interaction between different filter files. Understanding these issues and their solutions is essential for effective configuration. - -One frequent issue involves pattern syntax errors, particularly with wildcard usage. Users sometimes confuse `*` (single-level wildcard) with `**` (recursive wildcard), leading to unexpected results. For example, using `docs/*.md` will only match markdown files in the immediate docs directory, while `docs/**/*.md` matches markdown files in docs and all its subdirectories. Another common syntax issue is the placement of negation patterns; negation patterns must come after the patterns they modify to be effective. - -Unexpected file inclusions or exclusions often occur due to the priority hierarchy between configuration files. Since `.contextinclude` takes precedence over `.contextignore`, users may be confused when removing patterns from `.contextignore` doesn't change the analysis results. In such cases, the `.contextinclude` file is likely active and controlling the filtering behavior. Users should check for the presence of `.contextinclude` and either modify it or remove it to revert to EXCLUDE mode. - -Interaction between different filter files can also cause confusion. The tool respects `.gitignore` rules in addition to its own configuration files, meaning files excluded by `.gitignore` will not be analyzed regardless of context rules. This layered exclusion can make it difficult to understand why certain files are missing from the analysis. Using verbose mode can help diagnose these issues by showing which mode is active and providing insight into the filtering process. - -Other common issues include using directory patterns without proper syntax (patterns should use `docs/**` rather than `docs/`), having inline comments in pattern files (comments must be on separate lines starting with `#`), and not accounting for file extensions in method patterns. Users may also encounter issues when patterns contain special regex characters that need to be escaped, though the tool automatically handles most special characters in pattern conversion. - -**Section sources** -- [README.md](file://README.md#L418) -- [README.md](file://README.md#L378-L408) -- [context-manager.js](file://context-manager.js#L175-L211) - -## Best Practices - -To create effective filter configurations for different use cases, users should follow several best practices that leverage the full capabilities of the context-manager tool's filtering system. - -For general development workflows, use INCLUDE mode with `.contextinclude` for maximum precision. Start with broad inclusion patterns and use negation to exclude specific files or directories. For example, include all JavaScript files in the source directory with `src/**/*.js` and then exclude test files with `!src/**/*.test.js` and legacy code with `!src/legacy/**`. This approach ensures comprehensive coverage while maintaining control over what is excluded. - -When focusing on core application logic, create a `.contextinclude` file that specifically targets entry points and core modules. Include main application files explicitly and use pattern matching to capture related components. For method-level analysis, combine exact method names for critical business logic with pattern matching for method categories (e.g., `*Handler`, `*Validator`) to ensure comprehensive coverage of essential functionality. - -For testing and debugging scenarios, use method-level filtering to isolate specific components. Create a `.methodinclude` file that focuses on the methods being debugged, using both exact names and pattern matching to capture related functionality. Conversely, use `.methodignore` to exclude noise from utility methods, logging, and debugging functions that might clutter the analysis. - -Always validate configurations using verbose mode, which shows which filtering mode is active and provides detailed information about included and excluded files. This transparency helps identify configuration issues and ensures the analysis scope matches expectations. When troubleshooting, temporarily simplify configurations to isolate issues, starting with basic patterns and gradually adding complexity. - -Organize configuration files with clear comments explaining the purpose of each pattern. Group related patterns together and use comments to document the rationale behind inclusions and exclusions. This documentation helps maintain configurations over time and makes them easier to understand for other team members. - -Finally, consider the performance implications of different filtering approaches. While INCLUDE mode provides precise control, it requires careful maintenance as the codebase evolves. EXCLUDE mode may be more maintainable for stable project structures but risks including unwanted files as new directories are added. Regularly review and update filter configurations to ensure they continue to meet the project's analysis needs. - -**Section sources** -- [README.md](file://README.md#L30-L103) -- [README.md](file://README.md#L253-L293) -- [context-manager.js](file://context-manager.js#L408-L447) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) \ No newline at end of file diff --git a/docs/content-en/Configuration/File Filtering.md b/docs/content-en/Configuration/File Filtering.md deleted file mode 100644 index 19f45ae..0000000 --- a/docs/content-en/Configuration/File Filtering.md +++ /dev/null @@ -1,268 +0,0 @@ -# File Filtering - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) -- [README.md](file://README.md) - - -## Table of Contents -1. [Introduction](#introduction) -2. [Dual-Mode Filtering System](#dual-mode-filtering-system) -3. [Pattern Syntax and Examples](#pattern-syntax-and-examples) -4. [Precedence Rules and Configuration Priority](#precedence-rules-and-configuration-priority) -5. [Implementation Details](#implementation-details) -6. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) -7. [Best Practices](#best-practices) - -## Introduction - -The context-manager tool implements a sophisticated file filtering mechanism designed to optimize code analysis for LLM (Large Language Model) context generation. This system enables precise control over which files are included or excluded from analysis through a dual-mode approach using `.contextignore` and `.contextinclude` configuration files. The filtering system respects existing `.gitignore` rules while providing additional layers of control for focused analysis of specific code components. This documentation details the implementation, usage, and best practices for configuring the file filtering system to achieve optimal results in code analysis and token calculation. - -**Section sources** -- [README.md](file://README.md#L544-L610) -- [context-manager.js](file://context-manager.js#L124-L270) - -## Dual-Mode Filtering System - -The context-manager tool employs a dual-mode filtering system that operates through two complementary configuration files: `.contextignore` for EXCLUDE mode and `.contextinclude` for INCLUDE mode. These modes provide flexible approaches to file selection based on project requirements. - -### EXCLUDE Mode (.contextignore) - -EXCLUDE mode functions as a traditional ignore system, where all files are included by default except those matching patterns specified in the `.contextignore` file. This mode is ideal for projects where most files should be analyzed, but specific types or directories need to be excluded. The configuration follows gitignore-style syntax, allowing users to specify patterns that match files to be filtered out from analysis. - -### INCLUDE Mode (.contextinclude) - -INCLUDE mode operates on the principle of inclusion by specification, where only files matching patterns in the `.contextinclude` file are processed. This mode provides precise control over analysis scope, ensuring that only explicitly defined files are included. It is particularly useful for focusing analysis on core application components while excluding peripheral files like documentation, tests, or configuration files. - -The system automatically determines which mode to use based on the presence of configuration files. When both `.contextinclude` and `.contextignore` exist, INCLUDE mode takes precedence, ensuring that the more restrictive inclusion rules are applied. - -```mermaid -graph TD -A[Start Analysis] --> B{.contextinclude exists?} -B --> |Yes| C[Activate INCLUDE Mode] -B --> |No| D{.contextignore exists?} -D --> |Yes| E[Activate EXCLUDE Mode] -D --> |No| F[Include All Files
Respect .gitignore Only] -C --> G[Process Only Files Matching
.contextinclude Patterns] -E --> H[Process All Files Except Those Matching
.contextignore Patterns] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L134-L149) -- [README.md](file://README.md#L544-L610) - -**Section sources** -- [context-manager.js](file://context-manager.js#L134-L149) -- [README.md](file://README.md#L544-L610) - -## Pattern Syntax and Examples - -The filtering system supports a comprehensive pattern syntax that enables flexible and precise file selection. Patterns are processed using glob-style matching with additional features for negation and directory traversal. - -### Supported Pattern Syntax - -The system recognizes several key pattern elements: - -- `**` - Matches any number of directories and subdirectories (recursive) -- `*` - Matches any sequence of characters within a single directory level -- `?` - Matches any single character -- `!` - Negation operator that excludes files matching the subsequent pattern -- `/` - Directory separator that anchors patterns to specific directory levels - -Patterns can be specified as relative paths from the project root or as file extensions to match across the entire codebase. - -### Practical Configuration Examples - -The README provides concrete examples of effective configuration patterns: - -For INCLUDE mode focusing on core JavaScript files while excluding test and workflow components: -```bash -# Include only core JavaScript files -utility-mcp/src/**/*.js -!utility-mcp/src/testing/** -!utility-mcp/src/workflows/** -``` - -For EXCLUDE mode to filter out documentation, configuration, and test files: -```bash -# Exclude documentation and config -**/*.md -**/*.json -node_modules/** -test/ -**/*.test.js -**/*.spec.js -``` - -These examples demonstrate how to create focused analysis scopes by combining inclusion patterns with negation rules to refine the selection. - -```mermaid -flowchart TD -Start([Pattern Processing]) --> Parse["Parse Pattern String"] -Parse --> CheckNegation{"Starts with '!'?"} -CheckNegation --> |Yes| SetNegation["Set isNegation = true"] -CheckNegation --> |No| Continue["Keep isNegation = false"] -SetNegation --> RemoveNegation["Remove '!' prefix"] -Continue --> RemoveTrailing["Remove trailing '/'"] -RemoveNegation --> RemoveTrailing -RemoveTrailing --> Escape["Escape Special Regex Characters"] -Escape --> ReplaceWildcards["Replace Wildcards:
**→.*, *→[^/]*, ?→[^/]"] -ReplaceWildcards --> Anchor["Anchor Pattern:
^ if starts with /,
(^|/) otherwise"] -Anchor --> DirectoryCheck{"Ends with '/'?"} -DirectoryCheck --> |Yes| AddDirectory["Add (/.*?)? suffix"] -DirectoryCheck --> |No| AddEnd["Add $ suffix"] -AddDirectory --> CreateRegex["Create RegExp Object"] -AddEnd --> CreateRegex -CreateRegex --> Output["Return {regex, isNegation,
original, isDirectory}"] -Output --> End([Pattern Ready for Matching]) -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L159-L179) -- [README.md](file://README.md#L544-L610) - -**Section sources** -- [context-manager.js](file://context-manager.js#L159-L179) -- [README.md](file://README.md#L544-L610) - -## Precedence Rules and Configuration Priority - -The file filtering system implements a clear hierarchy of precedence to resolve potential conflicts between different configuration sources. This ensures predictable behavior when multiple filtering rules are defined. - -### Priority Order - -The system follows a strict priority order when evaluating file inclusion: - -1. **`.gitignore`** - Standard git exclusions are always respected and form the baseline for file filtering -2. **`.contextinclude`** - INCLUDE mode rules take highest priority for file selection -3. **`.contextignore`** - EXCLUDE mode rules are applied when no INCLUDE mode configuration exists - -This hierarchy ensures that git-ignored files are never included in analysis, while providing the flexibility to either include only specific files (via `.contextinclude`) or exclude specific files (via `.contextignore`). - -### Implementation of Precedence Logic - -The precedence rules are implemented in the `loadPatterns` method of the `GitIgnoreParser` class. When both `.contextinclude` and `.contextignore` files exist, the system prioritizes the INCLUDE mode configuration. The `hasIncludeFile` flag is set to true when a `.contextinclude` file is detected, which subsequently influences the filtering behavior in the `isIgnored` method. - -The implementation ensures that INCLUDE mode rules completely override EXCLUDE mode rules, preventing any ambiguity in file selection. This design choice emphasizes precision over breadth, allowing users to create tightly focused analysis scopes when needed. - -```mermaid -graph TD -A[File Path] --> B[Check .gitignore] -B --> |Matched| C[Exclude File] -B --> |Not Matched| D{hasIncludeFile?} -D --> |True| E[Check .contextinclude] -D --> |False| F[Check .contextignore] -E --> |Matched & Not Negated| G[Include File] -E --> |Not Matched or Negated| H[Exclude File] -F --> |Matched & Not Negated| H[Exclude File] -F --> |Not Matched or Negated| I[Include File] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L181-L206) -- [context-manager.js](file://context-manager.js#L134-L149) - -**Section sources** -- [context-manager.js](file://context-manager.js#L134-L149) -- [context-manager.js](file://context-manager.js#L181-L206) - -## Implementation Details - -The file filtering mechanism is implemented through the `GitIgnoreParser` class, which handles pattern loading, parsing, and file exclusion logic. The system integrates with the main `TokenCalculator` class to provide seamless filtering during code analysis. - -### Pattern Loading and Initialization - -The filtering system initializes through the `initGitIgnore` method in the `TokenCalculator` class, which locates and loads the appropriate configuration files. The system searches for `.contextignore` and `.contextinclude` files in both the tool directory and project root, allowing for flexible configuration placement. - -When configuration files are found, their patterns are parsed into regular expressions for efficient matching. The `parsePatternFile` method processes each line of the configuration file, ignoring comments and empty lines, then converts each pattern into a regex object using the `convertToRegex` method. - -### File Exclusion Logic - -The core filtering logic resides in the `isIgnored` method, which determines whether a given file should be excluded from analysis. For INCLUDE mode, the method first checks if the file matches any pattern in the `.contextinclude` file. If no matching pattern is found (or if a negation pattern matches), the file is excluded. For EXCLUDE mode, files are excluded if they match any pattern in the `.contextignore` file. - -The system also handles directory traversal efficiently by checking if directories should be traversed based on INCLUDE mode patterns, preventing unnecessary file system exploration. - -```mermaid -classDiagram -class GitIgnoreParser { -+patterns : Array -+calculatorPatterns : Array -+hasIncludeFile : boolean -+_lastIgnoreReason : string -+constructor(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+parsePatternFile(filePath) -+convertToRegex(pattern) -+isIgnored(filePath, relativePath) -+testPatterns(patterns, relativePath, reason) -+testPatternsWithNegation(patterns, relativePath) -} -class TokenCalculator { -+projectRoot : string -+options : Object -+stats : Object -+gitIgnore : GitIgnoreParser -+methodAnalyzer : MethodAnalyzer -+methodFilter : MethodFilterParser -+methodStats : Object -+constructor(projectRoot, options) -+initGitIgnore() -+scanDirectory(dir) -+countIgnoredFiles(filePath) -} -TokenCalculator --> GitIgnoreParser : "uses for file filtering" -TokenCalculator --> MethodAnalyzer : "uses for method extraction" -TokenCalculator --> MethodFilterParser : "uses for method filtering" -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L124-L270) - -**Section sources** -- [context-manager.js](file://context-manager.js#L124-L270) - -## Common Issues and Troubleshooting - -Users may encounter several common issues when configuring the file filtering system. Understanding these issues and their solutions helps ensure effective configuration. - -### Incorrect Pattern Syntax - -One frequent issue is incorrect pattern syntax, particularly with wildcards and negation. Users should ensure that patterns use the correct glob syntax and that negation patterns start with an exclamation mark (`!`). Inline comments within pattern files can also cause issues, as only line comments (starting at the beginning of a line) are properly ignored. - -### Unexpected File Inclusions - -Unexpected file inclusions often occur due to precedence rule misunderstandings. When both `.contextinclude` and `.contextignore` files exist, only the INCLUDE mode rules are applied. Users expecting EXCLUDE mode behavior may be surprised to find files included or excluded contrary to their `.contextignore` rules. Checking the console output for the active mode can help diagnose this issue. - -### Performance Impacts - -Broad patterns, particularly recursive wildcards (`**`), can impact performance by requiring extensive file system traversal. Users should be specific with their patterns and avoid overly broad rules that force the system to examine large portions of the codebase unnecessarily. - -## Best Practices - -To create efficient and maintainable filter configurations, follow these best practices: - -### Use Specific Patterns - -Prefer specific patterns over broad wildcards when possible. Instead of using `**/*.js` to include all JavaScript files, specify the exact directories that contain relevant code, such as `src/**/*.js` or `lib/**/*.js`. This reduces processing time and focuses analysis on relevant components. - -### Leverage Negation Effectively - -Use negation patterns to refine broad inclusion rules. For example, include all JavaScript files in a source directory but exclude test files: -```bash -src/**/*.js -!src/**/*.test.js -!src/**/*.spec.js -``` - -### Document Configuration Intent - -Add comments to configuration files explaining the purpose of each pattern. This helps team members understand the filtering strategy and maintain consistency across the project. - -### Test Configurations - -Verify configurations by running the tool in verbose mode to see which files are included or excluded. This immediate feedback helps identify issues with pattern matching and ensures the intended files are processed. - -### Balance Inclusion and Exclusion - -Choose between INCLUDE and EXCLUDE modes based on project needs. Use INCLUDE mode for focused analysis of core components and EXCLUDE mode for comprehensive analysis with selective exclusions. \ No newline at end of file diff --git a/docs/content-en/Configuration/Method Filtering.md b/docs/content-en/Configuration/Method Filtering.md deleted file mode 100644 index e7423b0..0000000 --- a/docs/content-en/Configuration/Method Filtering.md +++ /dev/null @@ -1,236 +0,0 @@ -# Method Filtering - - -**Referenced Files in This Document** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Updated in recent commit* -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js) - *Updated in recent commit* -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Updated in recent commit* -- [README.md](file://README.md) - *Updated in recent commit* - - -## Update Summary -**Changes Made** -- Updated all sections to reflect the actual implementation of the method filtering system -- Added accurate source references for all sections based on code analysis -- Corrected the configuration file loading mechanism to show proper initialization through ConfigUtils -- Updated the filtering logic section with accurate implementation details from the code -- Enhanced the integration section with precise details about TokenCalculator's method analysis -- Fixed outdated pattern syntax information to match actual implementation -- Updated practical examples to align with current README content - -## Table of Contents -1. [Introduction](#introduction) -2. [Configuration Files](#configuration-files) -3. [Pattern Syntax](#pattern-syntax) -4. [Filtering Logic](#filtering-logic) -5. [Integration with TokenCalculator](#integration-with-tokencalculator) -6. [Practical Examples](#practical-examples) -7. [Configuration Pitfalls](#configuration-pitfalls) -8. [Best Practices](#best-practices) - -## Introduction - -The context-manager tool provides a sophisticated method-level filtering system that enables granular control over which methods are included in LLM context generation. This system operates through two configuration files: `.methodinclude` and `.methodignore`, which work in conjunction with the `MethodFilterParser` class to determine which methods should be analyzed and included in the final context output. The filtering system is designed to help developers optimize token usage by focusing on core business logic while excluding utility, test, and debugging methods that add noise to LLM context. - -**Section sources** -- [README.md](file://README.md#L544-L610) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - -## Configuration Files - -The method filtering system relies on two optional configuration files that can be placed in the project root or tool directory: - -- **`.methodinclude`**: When present, this file enables INCLUDE mode, where only methods matching the specified patterns are included in analysis -- **`.methodignore`**: When `.methodinclude` is absent, this file enables EXCLUDE mode, where methods matching the specified patterns are excluded from analysis - -The system follows a clear priority hierarchy: if `.methodinclude` exists, it takes precedence over `.methodignore`, ensuring that developers have precise control over method selection. This dual-mode approach provides flexibility for different use cases, allowing developers to either whitelist specific methods of interest or blacklist methods that should be excluded from LLM context. - -The `MethodFilterParser` is initialized through the `ConfigUtils.initMethodFilter` method, which automatically detects configuration files in standard locations (package root and project root). This centralized configuration management ensures consistent behavior across different project setups. - -```mermaid -graph TD -A[Method Filtering System] --> B{.methodinclude exists?} -B --> |Yes| C[INCLUDE Mode] -B --> |No| D{.methodignore exists?} -D --> |Yes| E[EXCLUDE Mode] -D --> |No| F[Include All Methods] -C --> G[Only include matching methods] -E --> H[Exclude matching methods] -F --> I[Include all methods] -``` - -**Diagram sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L28-L41) - -**Section sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L28-L41) - -## Pattern Syntax - -The method filtering system supports several pattern types that provide flexible matching capabilities: - -| Pattern Type | Syntax | Description | Example | -|--------------|--------|-------------|---------| -| Exact Match | `methodName` | Matches methods with the exact name | `calculateTokens` matches only the method named "calculateTokens" | -| Wildcard | `*pattern*` | Matches methods containing the pattern | `*Handler` matches "requestHandler", "responseHandler" | -| Class Methods | `Class.*` | Matches all methods within a specific class | `TokenCalculator.*` matches all methods in the TokenCalculator class | -| File Methods | `filename.methodName` | Matches specific methods in specific files | `server.handleRequest` matches only the handleRequest method in server.js | - -The pattern matching is case-insensitive and supports the use of the `*` wildcard character to match any sequence of characters. This allows for powerful filtering rules that can target specific categories of methods based on naming conventions, which is particularly useful for excluding test, debug, or utility methods that follow predictable naming patterns. - -**Section sources** -- [README.md](file://README.md#L588-L610) - -## Filtering Logic - -The core filtering logic is implemented in the `MethodFilterParser` class, which processes the configuration files and determines method inclusion based on the active mode. The class follows a two-step process: - -1. **Configuration Loading**: The constructor checks for the existence of `.methodinclude` and `.methodignore` files, loading their patterns into separate arrays. The presence of `.methodinclude` sets the parser to INCLUDE mode. - -2. **Pattern Matching**: For each method encountered during analysis, the `shouldIncludeMethod` function evaluates whether the method should be included based on the active mode: - - In INCLUDE mode: A method is included if it matches any pattern in `.methodinclude` - - In EXCLUDE mode: A method is included if it does not match any pattern in `.methodignore` - -The pattern matching is performed using regular expressions that are dynamically generated from the wildcard patterns, with `*` characters converted to `.*` regex patterns. The matching is performed against both the bare method name and the fully qualified `filename.methodName` format, allowing for both general and file-specific filtering rules. - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : Boolean -+constructor(methodIncludePath, methodIgnorePath) -+parseMethodFile(filePath) : Array -+shouldIncludeMethod(methodName, fileName) : Boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+analyzeFileMethods(content, filePath) : Array -} -TokenCalculator --> MethodFilterParser : "uses" -``` - -**Diagram sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) - -**Section sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## Integration with TokenCalculator - -The method filtering system is tightly integrated with the `TokenCalculator` class, which orchestrates the overall analysis process. When method-level analysis is enabled via the `--method-level` flag, the `TokenCalculator` initializes a `MethodFilterParser` instance during construction by calling `initMethodFilter()`. - -The filtering occurs during the `analyzeFileMethods` method execution, where each extracted method is passed through the `shouldIncludeMethod` check before being included in the analysis results. This integration ensures that only relevant methods contribute to the token count and appear in the final LLM context output, significantly reducing the overall token footprint while preserving critical business logic. - -The system also maintains detailed statistics about method filtering, tracking the total number of methods found versus included, which helps developers understand the effectiveness of their filtering rules and optimize them for better context quality. - -```mermaid -sequenceDiagram -participant TC as TokenCalculator -participant MF as MethodFilterParser -participant MA as MethodAnalyzer -TC->>TC : run() -TC->>TC : scanDirectory() -TC->>TC : analyzeFile(filePath) -TC->>MA : extractMethods(content, filePath) -MA-->>TC : methods[] -loop For each method -TC->>MF : shouldIncludeMethod(name, fileName) -MF-->>TC : Boolean -alt Include method -TC->>MA : extractMethodContent() -MA-->>TC : methodContent -TC->>TC : calculateTokens() -TC->>TC : update methodStats -end -end -TC->>TC : generateLLMContext() -``` - -**Diagram sources** -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L231-L800) - -**Section sources** -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L231-L800) - -## Practical Examples - -The README provides several practical examples demonstrating how to use method filtering for different scenarios: - -**Including Core Business Logic:** -```bash -# .methodinclude -calculateTokens -generateLLMContext -analyzeFile -handleRequest -validateInput -processData -*Handler -*Validator -*Manager -TokenCalculator.* -``` - -This configuration focuses on core application logic by including specific business methods and all methods ending with common suffixes like "Handler", "Validator", and "Manager", which typically indicate important business components. - -**Excluding Utility Methods:** -```bash -# .methodignore -console -*test* -*debug* -*helper* -print* -main -server.printStatus -utils.debugLog -``` - -This configuration removes noise from the LLM context by excluding common utility, test, and debugging methods that don't contribute meaningful business logic. The file-specific exclusions like `server.printStatus` allow for precise control over individual methods. - -These examples demonstrate how developers can create focused contexts that highlight the most important parts of their codebase while minimizing token usage, making LLM interactions more efficient and effective. - -**Section sources** -- [README.md](file://README.md#L577-L587) - -## Configuration Pitfalls - -When configuring method filtering, developers should be aware of several common pitfalls: - -**Pattern Precedence**: The system follows a strict priority where `.methodinclude` always takes precedence over `.methodignore`. This means that if both files exist, only the include rules will be applied, which can lead to unexpected results if developers assume both sets of rules will be combined. - -**Case Sensitivity**: While the pattern matching is case-insensitive, developers should ensure their patterns account for common naming variations. For example, using `*test*` will match methods like "testMethod", "TestMethod", and "isTesting". - -**Interaction with File-Level Filtering**: Method filtering operates on files that have already passed file-level filtering. If a file is excluded by `.contextignore` or `.contextinclude` rules, its methods will not be analyzed regardless of method-level rules. This hierarchical filtering means that method rules only apply to files that are already included in the analysis scope. - -**Overly Broad Patterns**: Using patterns like `*` or `*.*` can lead to unintended matches. Developers should be specific with their patterns to avoid including methods that don't align with their intended filtering goals. - -**Section sources** -- [README.md](file://README.md#L544-L576) - -## Best Practices - -To optimize method filtering for LLM context generation, consider the following best practices: - -**Focus on Business Logic**: Prioritize including methods that implement core business rules, data processing, and critical application workflows. These methods typically provide the most valuable context for LLMs assisting with development tasks. - -**Exclude Noise Methods**: Systematically exclude utility, test, logging, and debugging methods that add token overhead without contributing meaningful business context. Common patterns like `*test*`, `*debug*`, and `console` are good candidates for exclusion. - -**Use Include Mode for Critical Paths**: When working on specific features or conducting deep analysis, use `.methodinclude` to create a whitelist of only the most relevant methods. This creates a highly focused context that maximizes the signal-to-noise ratio. - -**Leverage Naming Conventions**: Take advantage of consistent naming patterns in your codebase. If your team uses suffixes like "Service", "Manager", or "Handler" for business logic classes, use patterns like `*Service.*` to include all methods in these classes. - -**Monitor Token Reduction**: Regularly check the method statistics in the analysis output to understand how effectively your filtering rules are reducing token count. The difference between "Total methods found" and "Methods included" provides insight into filtering efficiency. - -**Iterate and Refine**: Start with broad filtering rules and gradually refine them based on the quality of LLM responses. If the LLM is missing important context, adjust your rules to include additional method categories. - -By following these practices, developers can create optimized LLM contexts that balance comprehensiveness with efficiency, ensuring that AI assistants have access to the most relevant code while operating within token limitations. - -**Section sources** -- [README.md](file://README.md#L544-L610) \ No newline at end of file diff --git a/docs/content-en/Contributing Guide.md b/docs/content-en/Contributing Guide.md deleted file mode 100644 index 20fb07f..0000000 --- a/docs/content-en/Contributing Guide.md +++ /dev/null @@ -1,267 +0,0 @@ -# Contributing Guide - - -**Referenced Files in This Document** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) -- [test/test.js](file://test/test.js) -- [test/test-suite.js](file://test/test-suite.js) -- [package.json](file://package.json) - - -## Table of Contents -1. [Introduction](#introduction) -2. [Development Workflow](#development-workflow) -3. [Code Structure and Architecture](#code-structure-and-architecture) -4. [Testing Strategy](#testing-strategy) -5. [Contribution Guidelines](#contribution-guidelines) -6. [Coding Standards](#coding-standards) -7. [Extending the Tool](#extending-the-tool) -8. [Conclusion](#conclusion) - -## Introduction -The context-manager project is an LLM context optimization tool with method-level filtering and token analysis capabilities. This guide provides comprehensive information for contributors to understand the development workflow, code structure, testing strategy, and contribution guidelines. The tool is designed to help developers analyze codebases and generate optimized context for AI assistants by calculating exact token counts using tiktoken (GPT-4 compatible). - -**Section sources** -- [README.md](file://README.md#L0-L891) - -## Development Workflow - -### Setting Up the Local Environment -To set up the local development environment for context-manager, follow these steps: - -1. Clone the repository from GitHub -2. Install dependencies using `npm install` -3. Install tiktoken for exact token counting: `npm install tiktoken` - -The tool can be used both as a global CLI tool and programmatically. The package is configured to work with Node.js version 14.0.0 or higher. - -### Running Tests -The project includes a comprehensive testing suite that can be executed using npm scripts: - -```bash -npm test # Run basic tests -npm run test:all # Run comprehensive test suite -``` - -The test suite validates core functionality including file-level analysis, method-level analysis, context export to file and clipboard, detailed report generation, and various CLI options. - -### Submitting Pull Requests -When submitting pull requests, ensure that: -- All tests pass successfully -- Code follows the established coding standards -- New features are accompanied by appropriate tests -- Documentation is updated to reflect changes -- The prepublishOnly script runs successfully, which executes tests before publishing - -**Section sources** -- [package.json](file://package.json#L0-L55) -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Code Structure and Architecture - -### Modular, Class-Based Design -The context-manager project follows a modular, class-based design pattern with clear separation of concerns. The architecture consists of several core components that work together to provide the tool's functionality. - -```mermaid -classDiagram -class TokenCalculator { -+projectRoot string -+options object -+stats object -+gitIgnore GitIgnoreParser -+methodAnalyzer MethodAnalyzer -+methodFilter MethodFilterParser -+run() void -+scanDirectory(dir) string[] -+analyzeFile(filePath) object -+generateLLMContext(analysisResults) object -} -class GitIgnoreParser { -+patterns string[] -+calculatorPatterns string[] -+hasIncludeFile boolean -+isIgnored(filePath, relativePath) boolean -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) void -} -class MethodAnalyzer { -+extractMethods(content, filePath) object[] -+getLineNumber(content, index) number -+isKeyword(name) boolean -+extractMethodContent(content, methodName) string -} -class MethodFilterParser { -+includePatterns object[] -+ignorePatterns object[] -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -} -TokenCalculator --> GitIgnoreParser : "uses" -TokenCalculator --> MethodAnalyzer : "uses" -TokenCalculator --> MethodFilterParser : "uses" -MethodAnalyzer --> MethodFilterParser : "provides methods for filtering" -``` - -**Diagram sources ** -- [context-manager.js](file://context-manager.js#L231-L800) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L14-L73) -- [context-manager.js](file://context-manager.js#L75-L115) - -### Core Components -The main components of the system are: - -- **TokenCalculator**: The primary orchestrator that manages the analysis process, coordinates file scanning, token counting, and report generation -- **GitIgnoreParser**: Handles pattern matching for .gitignore, .contextignore, and .contextinclude files to determine which files to include or exclude from analysis -- **MethodAnalyzer**: Extracts methods from JavaScript/TypeScript files using regex patterns and calculates token counts for individual methods -- **MethodFilterParser**: Filters methods based on rules defined in .methodinclude and .methodignore configuration files - -These components are exposed through the index.js file, which serves as the module entry point and exports all core classes for programmatic usage. - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L864) -- [index.js](file://index.js#L0-L7) - -## Testing Strategy - -### Test Directory Structure -The test directory contains two primary test files: - -- **test.js**: Basic functionality tests that verify the core components can be instantiated and basic operations work correctly -- **test-suite.js**: Comprehensive test suite that validates various aspects of the tool's functionality through integration tests - -### Test Coverage -The testing strategy focuses on several key areas: - -1. **Basic functionality**: Verifies that the core classes can be instantiated and basic operations work -2. **Package structure**: Ensures the module exports are correctly configured -3. **File-level analysis**: Tests the ability to analyze files and generate reports -4. **Method-level analysis**: Validates method extraction and analysis capabilities -5. **Context export**: Tests both file and clipboard export functionality -6. **Report generation**: Verifies detailed JSON reports are generated correctly -7. **CLI interface**: Validates command-line interface options and behavior -8. **Error handling**: Tests how the tool handles invalid inputs and edge cases -9. **Method extraction accuracy**: Ensures methods are correctly identified and extracted from code - -The test suite uses child process execution to test the CLI interface and verifies output contains expected strings to confirm functionality. - -```mermaid -flowchart TD -Start([Test Execution]) --> BasicFunctionality["Test Basic Functionality"] -BasicFunctionality --> PackageStructure["Test Package Structure"] -PackageStructure --> FileLevelAnalysis["Test File-Level Analysis"] -FileLevelAnalysis --> MethodLevelAnalysis["Test Method-Level Analysis"] -MethodLevelAnalysis --> ContextExport["Test Context Export"] -ContextExport --> ReportGeneration["Test Report Generation"] -ReportGeneration --> CLIInterface["Test CLI Interface"] -CLIInterface --> ErrorHandling["Test Error Handling"] -ErrorHandling --> MethodAccuracy["Test Method Extraction Accuracy"] -MethodAccuracy --> Results["Generate Test Results Summary"] -Results --> End([Test Complete]) -``` - -**Diagram sources ** -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -**Section sources** -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Contribution Guidelines - -### Bug Reports -When reporting bugs, please include: -- A clear description of the issue -- Steps to reproduce the problem -- Expected behavior vs. actual behavior -- Environment information (Node.js version, operating system) -- Any relevant error messages or stack traces -- Screenshots if applicable - -### Feature Requests -For feature requests, provide: -- A detailed description of the desired functionality -- Use cases and scenarios where the feature would be beneficial -- Any relevant examples or references -- Potential implementation approaches if known -- Expected benefits to users - -### Code Contributions -When contributing code: -1. Fork the repository and create a feature branch -2. Ensure your code follows the established coding standards -3. Write appropriate tests for new functionality -4. Update documentation as needed -5. Submit a pull request with a clear description of changes -6. Reference any related issues in the pull request description - -The project maintains a high test coverage to ensure reliability and prevent regressions. All contributions should maintain or improve this coverage. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [package.json](file://package.json#L0-L55) - -## Coding Standards - -### Code Style -The project follows these coding standards: -- ES6 class syntax for core components -- Regex-based parsing (no AST dependencies) -- Graceful fallbacks (tiktoken optional, clipboard fallback to file) -- Minimal dependencies (only tiktoken as optional) -- No TypeScript, pure JavaScript for maximum portability -- Consistent naming conventions -- Comprehensive commenting for complex logic -- Error handling with appropriate fallbacks - -### Commit Message Conventions -The project follows conventional commit message formatting: -- Use imperative mood ("fix", "add", "remove", "update") -- Limit the first line to 72 characters -- Include a blank line between subject and body -- Use the body to explain what and why vs. how -- Reference issues and pull requests when applicable - -### Code Review Process -The code review process includes: -1. Automated testing via the prepublishOnly script -2. Manual review of code quality and adherence to standards -3. Verification of test coverage -4. Assessment of documentation updates -5. Testing of functionality in different environments -6. Security review for potential vulnerabilities - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L864) -- [package.json](file://package.json#L0-L55) - -## Extending the Tool - -### Adding New Features -To extend the tool with new features: -1. Identify the appropriate component for the new functionality -2. Follow the existing design patterns and coding standards -3. Implement the feature with comprehensive tests -4. Update documentation to reflect the new capabilities -5. Ensure backward compatibility when possible - -### Adding New Output Formats -To add new output formats: -1. Extend the generateLLMContext method in the TokenCalculator class -2. Create a new method for the specific format -3. Add appropriate CLI options to enable the new format -4. Implement tests for the new output format -5. Update documentation with examples of the new format - -The tool currently supports multiple output formats including detailed JSON reports, LLM context files, and clipboard integration. New formats should follow the same principles of providing structured, machine-readable output that is useful for AI assistants. - -**Section sources** -- [context-manager.js](file://context-manager.js#L231-L800) -- [bin/cli.js](file://bin/cli.js#L0-L66) - -## Conclusion -The context-manager project provides a robust foundation for analyzing codebases and generating optimized context for AI assistants. By following the guidelines outlined in this document, contributors can effectively participate in the development of the tool, ensuring high-quality contributions that align with the project's architecture and goals. The modular, class-based design makes it relatively straightforward to extend the tool with new features or output formats while maintaining code quality and test coverage. \ No newline at end of file diff --git a/docs/content-en/Core Features/Core Features.md b/docs/content-en/Core Features/Core Features.md deleted file mode 100644 index 162ba9b..0000000 --- a/docs/content-en/Core Features/Core Features.md +++ /dev/null @@ -1,119 +0,0 @@ -# Core Features - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - *Updated in recent commit* -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Updated in recent commit* -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js) - *Updated in recent commit* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in recent commit* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Added in recent commit* -- [README.md](file://README.md) -- [index.js](file://index.js) - - -## Update Summary -**Changes Made** -- Updated Method-Level Analysis section to include new GitIngest-style digest formatter and method filtering capabilities -- Added new section on GitIngest Digest Generation to cover the new formatter functionality -- Enhanced Token Counting section with updated context on GitIngest integration -- Added new sources for recently modified and added files -- Updated Feature Integration section to reflect new export options and formatter integration - -## Table of Contents -1. [File-Level Analysis](#file-level-analysis) -2. [Method-Level Analysis](#method-level-analysis) -3. [Token Counting](#token-counting) -4. [GitIngest Digest Generation](#gitingest-digest-generation) -5. [Feature Integration](#feature-integration) -6. [Common Issues and Performance](#common-issues-and-performance) - -## File-Level Analysis - -The context-manager tool implements a comprehensive file-level analysis system that combines multiple filtering mechanisms to determine which files should be included in the token calculation process. The tool begins by scanning the entire directory structure starting from the project root, recursively traversing directories while respecting exclusion rules. - -The file scanning process is implemented in the `scanDirectory` method of the `TokenCalculator` class, which examines each file and directory in the project. During this process, the tool applies a hierarchical filtering system that respects both `.gitignore` patterns and custom configuration files. Files are only included in the analysis if they pass all filtering criteria and are identified as text files through the `isTextFile` method, which checks file extensions and base names against a predefined list of text-based formats. - -The filtering system prioritizes configuration files in a specific order: `.gitignore` rules are always respected, followed by `.contextinclude` (which takes precedence in INCLUDE mode), and then `.contextignore` (used in EXCLUDE mode when no include file exists). This multi-layered approach ensures that developers can precisely control which files are analyzed, allowing for focused examination of core application logic while excluding documentation, configuration, and test files. - -**Section sources** -- [context-manager.js](file://context-manager.js#L376-L406) -- [context-manager.js](file://context-manager.js#L288-L315) -- [README.md](file://README.md#L294-L356) - -## Method-Level Analysis - -The context-manager tool provides sophisticated method-level analysis capabilities for JavaScript and TypeScript files, enabling granular examination of individual functions within code files. This feature is implemented through the `MethodAnalyzer` and `MethodFilterParser` classes, which work together to extract and filter methods based on configurable rules. - -The `MethodAnalyzer` class uses a series of regular expressions to identify various JavaScript function patterns, including traditional function declarations, object method syntax, arrow functions, and async functions. When method-level analysis is enabled via the `--method-level` flag, the tool extracts all methods from eligible code files and captures metadata such as method name and line number. The `extractMethodContent` method then isolates the complete method body for individual token counting. - -Method filtering is controlled by `.methodinclude` and `.methodignore` configuration files, which allow developers to include or exclude specific methods using pattern matching. The `MethodFilterParser` class processes these files, converting glob patterns to regular expressions for efficient matching. When an include file is present, only methods matching the specified patterns are included; otherwise, the tool excludes methods matching patterns in the ignore file. This system supports various pattern types including exact matches, wildcards, class-specific methods (using `Class.*` syntax), and file-specific methods (using `file.method` syntax). - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) -- [context-manager.js](file://context-manager.js#L357-L377) -- [README.md](file://README.md#L544-L610) -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js#L7-L92) - *Updated in recent commit* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - *Added in recent commit* - -## Token Counting - -The context-manager tool employs a dual approach to token counting, prioritizing accuracy while providing a reliable fallback mechanism. The primary method uses the `tiktoken` library to provide exact GPT-4 compatible token counts, which is essential for accurately estimating how much code can fit within an LLM's context window. When the `tiktoken` package is installed, the tool uses the `cl100k_base` encoding (used by GPT-4, ChatGPT-4, and text-embedding-ada-002) to encode the text content and count tokens precisely. - -The token counting process is implemented in the `calculateTokens` method of the `TokenCalculator` class, which attempts to use `tiktoken` first and falls back to estimation if the library is not available or if an error occurs. The estimation mechanism uses a character-based approach with different ratios for various file types, as different file formats have different average characters per token. For example, JavaScript and TypeScript files use a ratio of 3.2 characters per token, while Markdown files use 4.0, and JSON files use 2.5. This estimation provides approximately 95% accuracy compared to exact counting. - -The tool also tracks token statistics at multiple levels, including per-file, per-extension, and per-directory counts, providing detailed insights into the codebase composition. When method-level analysis is enabled, the tool additionally counts tokens for individual methods, allowing developers to identify particularly large or complex functions that might need refactoring. - -**Section sources** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L288-L315) -- [README.md](file://README.md#L356) - -## GitIngest Digest Generation - -The context-manager tool now includes a GitIngest-style digest formatter that generates comprehensive, prompt-friendly text files from code analysis results. This feature is implemented through the `GitIngestFormatter` class, which creates structured output suitable for LLM context consumption. - -The digest generation process begins with the `GitIngestFormatter` constructor, which accepts the project root, analysis statistics, and file analysis results. The formatter automatically detects method filtering configuration through the `detectMethodFilters` method, enabling method-level filtering when `.methodinclude` or `.methodignore` files exist in the project. - -The generated digest includes several components: a summary header with project information and token estimates, a directory tree structure showing the project layout, and file contents formatted with clear separators. When method-level filtering is active, the formatter extracts only the methods that match the filter criteria rather than including entire files, making the digest more focused and efficient. - -The formatter supports multiple generation methods: direct creation from live analysis, generation from existing `token-analysis-report.json` files, and creation from `llm-context.json` files. This flexibility allows users to generate digests quickly from previously saved analysis results without re-scanning the entire codebase. The `--gitingest-from-report` and `--gitingest-from-context` CLI flags enable these alternative generation methods. - -**Section sources** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - *Added in recent commit* -- [context-manager.js](file://context-manager.js#L524-L597) - *Updated in recent commit* -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L524-L597) - *Updated in recent commit* -- [test/test-gitingest.js](file://test/test-gitingest.js#L0-L172) - *Added in recent commit* -- [test/test-gitingest-json.js](file://test/test-gitingest-json.js#L0-L224) - *Added in recent commit* - -## Feature Integration - -The core features of the context-manager tool are orchestrated through the `TokenCalculator` class, which integrates file-level analysis, method-level analysis, token counting, and digest generation into a cohesive workflow. The `run` method serves as the main entry point, coordinating the entire analysis process from directory scanning to final reporting. - -The integration begins with initialization of the various components: the `GitIgnoreParser` for file filtering, the `MethodAnalyzer` and `MethodFilterParser` for method extraction (when enabled), and the token counting system. The tool then scans the directory structure, applying filtering rules to determine which files to analyze. For each included file, it reads the content and calculates tokens, optionally extracting and analyzing individual methods when the `methodLevel` option is enabled. - -The results are aggregated in comprehensive statistics that track files, tokens, bytes, and lines at various levels of granularity. The tool can generate different output formats depending on the use case: a compact format for LLM context optimization, a detailed method-level context when requested, or a comprehensive JSON report for analysis and monitoring. The `generateLLMContext` method creates structured output that can be exported to a file or copied to the clipboard, making it easy to share codebase context with AI assistants. - -Additionally, the tool now supports direct generation of GitIngest-style digests through the `saveGitIngestDigest` method, which creates an instance of `GitIngestFormatter` and saves the formatted digest to `digest.txt`. This integration allows users to generate comprehensive code summaries with a single command. - -**Section sources** -- [context-manager.js](file://context-manager.js#L213-L251) -- [context-manager.js](file://context-manager.js#L498-L539) -- [context-manager.js](file://context-manager.js#L774-L813) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L13-L642) - *Updated in recent commit* - -## Common Issues and Performance - -The context-manager tool addresses several common issues that arise in code analysis, particularly around pattern matching accuracy and token counting precision. One common issue is pattern matching failures, which can occur when configuration files contain syntax errors or when negation patterns (`!pattern`) are not properly understood. The tool provides verbose output to help diagnose these issues, showing which mode is active (INCLUDE or EXCLUDE) and how many rules were loaded from each configuration file. - -For large codebases, performance is optimized through several mechanisms. The tool avoids unnecessary file reads by first checking filtering rules before processing file content. It also uses efficient regular expressions for method extraction and pattern matching, compiling patterns once during initialization rather than repeatedly. The directory scanning process skips common exclusion directories like `node_modules`, `.git`, and `dist` by default, reducing the number of filesystem operations. - -Inaccurate token counts can occur when the `tiktoken` library is not installed, forcing the tool to rely on estimation. While the estimation is generally accurate (~95% compared to exact counts), it may vary depending on the specific characteristics of the code. Developers working with strict token limits should install `tiktoken` for precise counting. The tool also provides detailed reporting that breaks down token usage by file type and directory, helping identify unexpected large files or directories that might be skewing the overall count. - -When using the GitIngest digest generation feature, users should be aware that generating from existing JSON files (`token-analysis-report.json` or `llm-context.json`) is significantly faster than scanning the entire codebase, especially for large projects. However, this approach relies on the freshness of the JSON files, so users should ensure their analysis data is up-to-date before generating digests. - -**Section sources** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L376-L406) -- [README.md](file://README.md#L544-L610) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - *Added in recent commit* \ No newline at end of file diff --git a/docs/content-en/Core Features/File-Level Analysis.md b/docs/content-en/Core Features/File-Level Analysis.md deleted file mode 100644 index 5e2486e..0000000 --- a/docs/content-en/Core Features/File-Level Analysis.md +++ /dev/null @@ -1,97 +0,0 @@ -# File-Level Analysis - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - - -## Table of Contents -1. [File-Level Analysis](#file-level-analysis) -2. [Directory Scanning and Filtering](#directory-scanning-and-filtering) -3. [GitIgnore Processing](#gitignore-processing) -4. [Text File Detection](#text-file-detection) -5. [File Filtering and Token Counting Relationship](#file-filtering-and-token-counting-relationship) -6. [Statistics Tracking](#statistics-tracking) -7. [Common Issues and Optimization](#common-issues-and-optimization) - -## Directory Scanning and Filtering - -The TokenCalculator class implements recursive directory scanning while respecting multiple ignore rules. The scanDirectory method traverses the file system starting from a specified directory, applying filtering logic at each level to determine which files should be included in the analysis. - -The scanning process begins by reading all items in the current directory and processing them sequentially. For each item, the system first constructs both the full path and relative path from the project root. It then checks whether the file or directory should be ignored by calling the isIgnored method of the GitIgnoreParser instance. If the item is ignored, it increments the appropriate counter in the statistics and continues to the next item. - -For non-ignored items, the system determines whether the item is a file or directory. Directory traversal is limited to specific directories, excluding common development directories such as node_modules, .git, coverage, dist, and build. This prevents the analysis from processing unnecessary files and improves performance. When a directory is not excluded, the scanDirectory method calls itself recursively to process the contents of that directory. - -Text files that pass the ignore checks are added to the results array, which is returned after all items in the directory have been processed. This recursive approach ensures comprehensive coverage of the file system while maintaining efficient filtering at each level of the directory hierarchy. - -**Section sources** -- [context-manager.js](file://context-manager.js#L385-L412) - -## GitIgnore Processing - -The GitIgnoreParser class handles the processing of ignore and include patterns from multiple sources, implementing a priority-based system for rule evaluation. The class processes three types of configuration files: .gitignore, .contextignore, and .contextinclude, with .contextinclude having the highest priority. - -During initialization, the GitIgnoreParser loads patterns from the specified configuration files. When both .contextinclude and .contextignore exist, the include file takes precedence, implementing an "include-only" mode where only files matching the include patterns are processed. This priority system allows users to switch between exclusion-based filtering (where most files are included by default) and inclusion-based filtering (where only explicitly specified files are included). - -The pattern processing involves converting glob-style patterns into regular expressions for efficient matching. The convertToRegex method handles various pattern features including directory markers (/), negation (!), wildcards (*), and recursive wildcards (**). Directory patterns are treated specially, matching both the directory itself and all files within it. Negation patterns allow specific exceptions to broader ignore rules, providing fine-grained control over the filtering process. - -The isIgnored method implements the core filtering logic, first checking .gitignore rules, then applying calculator-specific rules based on whether include or exclude mode is active. In include mode, a file is considered ignored if it doesn't match any include pattern (after accounting for negations), while in exclude mode, a file is ignored if it matches any exclude pattern. This two-tiered approach ensures compatibility with existing .gitignore conventions while providing enhanced filtering capabilities. - -**Section sources** -- [context-manager.js](file://context-manager.js#L124-L229) - -## Text File Detection - -The isTextFile method determines whether a file should be analyzed based on its extension and basename. This filtering mechanism ensures that only text-based files are processed for token counting, avoiding binary files and other non-text content that would not be suitable for LLM context generation. - -The method uses two criteria to identify text files: file extension and basename patterns. For extensions, it maintains a comprehensive set of common text-based file types including source code files (.js, .ts, .py, .java, etc.), markup languages (.html, .xml, .svg), configuration formats (.json, .yml, .toml), and documentation formats (.md, .txt). Files with these extensions are automatically considered text files regardless of their name. - -In addition to extension-based detection, the method checks for specific basename patterns that commonly appear in development projects. These include files like Dockerfile, Makefile, LICENSE, README, and CHANGELOG, which may not have standard extensions but contain important textual content. The method performs a case-insensitive search for these patterns within the filename, allowing for variations like readme.md, LICENSE.txt, or CHANGELOG. - -This dual-criteria approach provides flexible file detection that accommodates both conventional naming patterns and common exceptions in development workflows. By combining extension and basename analysis, the system can accurately identify text files across various project structures and naming conventions. - -**Section sources** -- [context-manager.js](file://context-manager.js#L306-L321) - -## File Filtering and Token Counting Relationship - -File filtering directly impacts token counting by determining which files are included in the analysis process. The filtering pipeline operates as a series of gates that files must pass through before their tokens are counted. Only files that survive all filtering stages are processed for token calculation, ensuring that the final token count reflects only the desired subset of the codebase. - -The filtering process occurs in a specific order: first .gitignore rules are applied, then calculator-specific rules (.contextinclude or .contextignore), and finally the text file check. This sequence ensures that obviously irrelevant files (like those in node_modules) are excluded early, improving performance by avoiding unnecessary processing. Files that pass all filters are then analyzed to determine their token count using either the tiktoken library for exact counting or an estimation algorithm when tiktoken is not available. - -The relationship between filtering and token counting is reflected in the tool's output, which provides detailed statistics about both included and excluded files. This transparency allows users to understand exactly how filtering decisions affect the final token count and adjust their configuration files accordingly. The system also distinguishes between files ignored due to .gitignore rules versus those filtered by context rules, providing insight into which configuration files are most influential in shaping the analysis scope. - -**Section sources** -- [context-manager.js](file://context-manager.js#L385-L412) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L306-L321) - -## Statistics Tracking - -The TokenCalculator class maintains comprehensive statistics about the analysis process, tracking both included and excluded files across multiple dimensions. The statistics are stored in the stats object, which is initialized with counters for total files, tokens, bytes, lines, and various categorizations. - -As files are processed, the updateStats method increments the appropriate counters and updates extension-specific and directory-specific statistics. Each file contributes to the overall totals and also populates the byExtension and byDirectory breakdowns, allowing for detailed analysis of the codebase composition. The largestFiles array maintains a record of the most significant files by token count, enabling identification of potential optimization targets. - -The system tracks ignored files separately, distinguishing between those excluded by .gitignore rules and those filtered by context rules. This separation provides valuable feedback about the effectiveness of different filtering strategies and helps users understand the impact of their configuration choices. The countIgnoredFiles method recursively counts files within ignored directories, ensuring accurate statistics even when entire directory trees are excluded. - -These statistics are used to generate the final analysis report, which includes summary metrics, extension breakdowns, and rankings of the largest files and directories. This comprehensive reporting enables users to make informed decisions about their codebase structure and filtering configuration. - -**Section sources** -- [context-manager.js](file://context-manager.js#L455-L489) -- [context-manager.js](file://context-manager.js#L715-L743) -- [context-manager.js](file://context-manager.js#L673-L696) - -## Common Issues and Optimization - -Several common issues can arise when configuring file-level analysis, primarily related to misconfigured ignore patterns or performance bottlenecks with large directories. One frequent issue is the incorrect ordering of include/exclude rules, where negation patterns are placed after more general patterns, causing them to be ineffective. Users should ensure that negation patterns (those starting with !) are positioned appropriately within their configuration files to achieve the desired filtering behavior. - -Another common issue is the use of overly broad patterns that either exclude necessary files or include too many irrelevant files. For example, using **/*.js might include test files or generated code that should be excluded from LLM context. Conversely, overly specific patterns might miss important files. Users should carefully review their patterns and use the tool's verbose output to verify that the expected files are being included or excluded. - -Performance bottlenecks can occur when analyzing very large directories or when the filtering configuration requires extensive pattern matching. To optimize performance, users should employ precise include rules to limit the scope of analysis to only essential files. Using .contextinclude with specific patterns rather than relying solely on .contextignore with broad exclusions can significantly improve performance by reducing the number of files that need to be processed. - -Additional optimization strategies include avoiding recursive wildcards (**/ ) when possible, as they require more extensive file system traversal, and ensuring that the most commonly matched patterns are listed first in configuration files to minimize the number of pattern comparisons needed. Regularly reviewing and refining the filtering configuration based on the tool's statistics can help maintain optimal performance and accuracy. - -**Section sources** -- [context-manager.js](file://context-manager.js#L385-L412) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L306-L321) \ No newline at end of file diff --git a/docs/content-en/Core Features/Method-Level Analysis.md b/docs/content-en/Core Features/Method-Level Analysis.md deleted file mode 100644 index bab67c6..0000000 --- a/docs/content-en/Core Features/Method-Level Analysis.md +++ /dev/null @@ -1,294 +0,0 @@ -# Method-Level Analysis - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - *Updated in recent commit* -- [README.md](file://README.md) - *Updated in recent commit* -- [CLAUDE.md](file://CLAUDE.md) - *Updated in recent commit* -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js) - *Updated in recent commit* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in recent commit* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Updated in recent commit* - - -## Update Summary -**Changes Made** -- Updated Method Filtering Mechanism section to reflect GitIngest-style formatter integration -- Added new content about auto-detection of method filtering configuration -- Enhanced diagram to show GitIngestFormatter integration -- Updated section sources to reflect actual file changes -- Added new diagram sources for the updated architecture visualization - -## Table of Contents -1. [Introduction](#introduction) -2. [Method Extraction Process](#method-extraction-process) -3. [Method Analysis Integration](#method-analysis-integration) -4. [Method Filtering Mechanism](#method-filtering-mechanism) -5. [Method Statistics and Reporting](#method-statistics-and-reporting) -6. [LLM Context Generation](#llm-context-generation) -7. [Common Issues and Best Practices](#common-issues-and-best-practices) - -## Introduction - -The context-manager tool provides method-level analysis capabilities that enable granular examination of JavaScript and TypeScript codebases. This feature allows developers to extract, analyze, and filter individual methods from source files, creating optimized representations for LLM context generation. The method-level analysis is controlled through the `methodLevel` option and integrates with the TokenCalculator to process method content and generate detailed statistics. - -**Section sources** -- [context-manager.js](file://context-manager.js#L234-L238) -- [bin/cli.js](file://bin/cli.js#L17-L18) - -## Method Extraction Process - -The MethodAnalyzer class is responsible for extracting JavaScript/TypeScript methods from source code using regex patterns. It identifies methods through multiple patterns that match different function declaration styles: - -```mermaid -flowchart TD -Start([Start Method Extraction]) --> Pattern1["Pattern 1: Named functions
(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\("] -Pattern1 --> Pattern2["Pattern 2: Object methods
(\w+)\s*:\s*(?:async\s+)?function\s*\("] -Pattern2 --> Pattern3["Pattern 3: Arrow functions
(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>"] -Pattern3 --> Pattern4["Pattern 4: Getters/Setters
(?:get|set)\s+(\w+)\s*\("] -Pattern4 --> Pattern5["Pattern 5: Method shorthand
(?:async\s+)?(\w+)\s*\([^)]*\)\s*\{"] -Pattern5 --> Extract["Extract Method Name and Line Number"] -Extract --> KeywordCheck["Check if Name is Reserved Keyword"] -KeywordCheck --> |No| Store["Store Method in Map
(key: name:line)"] -KeywordCheck --> |Yes| Skip["Skip Reserved Keywords"] -Store --> NextPattern["Process Next Pattern"] -NextPattern --> End([Return Methods Array]) -``` - -The extraction process begins with the `extractMethods` function, which applies five regex patterns to identify different method declaration styles in JavaScript/TypeScript code. For each match, the analyzer captures the method name and calculates its line number by counting newlines from the beginning of the file to the match index. The analyzer filters out reserved JavaScript keywords to prevent false positives. - -To retrieve the complete content of a method, the `extractMethodContent` function uses dynamically constructed regex patterns that match the full method body, including nested braces. This allows the tool to extract not just the method signature but the entire implementation for token calculation. - -**Diagram sources** -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js#L7-L92) -- [context-manager.js](file://context-manager.js#L61-L72) - -**Section sources** -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js#L7-L92) - -## Method Analysis Integration - -The analyzeFileMethods function integrates method extraction with the TokenCalculator to process method content and calculate tokens. This integration occurs when the `methodLevel` option is enabled in the TokenCalculator constructor. - -```mermaid -sequenceDiagram -participant TokenCalculator -participant MethodAnalyzer -participant TokenCalculator as TokenCalculator -participant MethodFilterParser -TokenCalculator->>TokenCalculator : analyzeFile(filePath) -TokenCalculator->>TokenCalculator : Read file content -alt methodLevel enabled -TokenCalculator->>TokenCalculator : analyzeFileMethods(content, filePath) -TokenCalculator->>MethodAnalyzer : extractMethods(content, filePath) -MethodAnalyzer-->>TokenCalculator : Return methods array -TokenCalculator->>TokenCalculator : Initialize filteredMethods -TokenCalculator->>TokenCalculator : Increment methodStats.totalMethods -loop For each method -TokenCalculator->>MethodFilterParser : shouldIncludeMethod(method.name, fileName) -alt Method passes filter -TokenCalculator->>MethodAnalyzer : extractMethodContent(content, method.name) -MethodAnalyzer-->>TokenCalculator : Return method content -TokenCalculator->>TokenCalculator : calculateTokens(methodContent, filePath) -TokenCalculator->>TokenCalculator : Create methodInfo object -TokenCalculator->>TokenCalculator : Add to filteredMethods -TokenCalculator->>TokenCalculator : Increment methodStats.includedMethods -TokenCalculator->>TokenCalculator : Store methodTokens -end -end -TokenCalculator-->>TokenCalculator : Return filteredMethods -end -TokenCalculator-->>TokenCalculator : Return fileInfo with methods -``` - -The integration process begins in the `analyzeFile` method of TokenCalculator, which checks if method-level analysis is enabled. If so, it calls `analyzeFileMethods` to process the file content. This function first extracts all methods using the MethodAnalyzer, then iterates through each method to determine if it should be included based on filtering rules. - -For each included method, the system extracts the method content and calculates tokens using the same mechanism as for entire files. The token calculation uses the tiktoken library for exact GPT-4 compatible counts when available, falling back to estimation based on character counts per file type when tiktoken is not installed. - -**Diagram sources** -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) -- [context-manager.js](file://context-manager.js#L234-L238) - -**Section sources** -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) - -## Method Filtering Mechanism - -The method filtering mechanism uses the MethodFilterParser class to determine which methods should be included in the analysis based on rules defined in `.methodinclude` and `.methodignore` files. This filtering system provides fine-grained control over method selection. - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : boolean --methodIncludePath : string --methodIgnorePath : string -+constructor(methodIncludePath, methodIgnorePath) -+parseMethodFile(filePath) Array -+shouldIncludeMethod(methodName, fileName) boolean -} -class MethodAnalyzer { -+extractMethods(content, filePath) Array -+extractMethodContent(content, methodName) string -+getLineNumber(content, index) number -+isKeyword(name) boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+methodStats : Object -+analyzeFileMethods(content, filePath) Array -+generateMethodContext(analysisResults) Object -} -class GitIngestFormatter { -+methodFilterEnabled : boolean -+methodAnalyzer : MethodAnalyzer -+methodFilter : MethodFilterParser -+constructor(projectRoot, stats, analysisResults) -+detectMethodFilters() boolean -+initMethodFilter() MethodFilterParser -+generateFilteredFileContent(content, filePath) string -} -TokenCalculator --> MethodFilterParser : "uses for filtering" -TokenCalculator --> MethodAnalyzer : "uses for extraction" -MethodFilterParser --> ".methodinclude file" : "reads" -MethodFilterParser --> ".methodignore file" : "reads" -GitIngestFormatter --> MethodAnalyzer : "uses for method extraction" -GitIngestFormatter --> MethodFilterParser : "uses for filtering" -GitIngestFormatter --> "detects configuration" : "auto-detects .methodinclude/.methodignore" -``` - -The MethodFilterParser reads patterns from `.methodinclude` and `.methodignore` files, converting each line into a case-insensitive regex pattern. The filtering behavior depends on whether an include file exists: - -- When `.methodinclude` exists: Only methods matching the include patterns are included (INCLUDE mode) -- When only `.methodignore` exists: Methods matching ignore patterns are excluded (EXCLUDE mode) - -The `shouldIncludeMethod` function evaluates both the method name and the fully qualified name (filename.method) against the patterns. This allows for both general pattern matching (e.g., `*Handler` to match all methods ending with "Handler") and specific method targeting (e.g., `server.handleRequest`). - -The system searches for these configuration files in two locations: the script directory and the project root, with the project root taking precedence. This allows for both global and project-specific configuration. - -The GitIngestFormatter class now automatically detects method filtering configuration through the `detectMethodFilters` method in ConfigUtils, which checks for the presence of `.methodinclude` or `.methodignore` files. When method filtering is enabled, the formatter uses the MethodAnalyzer and MethodFilterParser to generate filtered file content that includes only the methods that pass the filter criteria. - -**Diagram sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js#L7-L92) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L2-L268) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L48-L52) - -**Section sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [README.md](file://README.md#L481-L500) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L2-L268) - -## Method Statistics and Reporting - -The method analysis feature aggregates statistics in the methodStats object, which tracks key metrics about the methods processed during analysis. These statistics are included in the final report to provide insights into the codebase structure. - -```mermaid -erDiagram -METHOD_STATS { -integer totalMethods -integer includedMethods -object methodTokens -} -METHOD_TOKENS { -string methodKey -integer tokenCount -} -ANALYSIS_RESULTS { -string relativePath -array methods -} -METHOD_STATS ||--o{ METHOD_TOKENS : "contains" -ANALYSIS_RESULTS ||--o{ METHOD_STATS : "references" -``` - -The methodStats object contains three properties: -- `totalMethods`: The total number of methods found across all analyzed files -- `includedMethods`: The number of methods that passed the filtering criteria -- `methodTokens`: An object mapping method identifiers (filename.methodname) to their token counts - -These statistics are updated during the method analysis process. The `totalMethods` counter is incremented with the number of methods extracted from each file, while `includedMethods` is incremented for each method that passes the filter. The `methodTokens` object stores the token count for each included method, enabling detailed analysis of method complexity. - -The statistics are incorporated into the final LLM context when method-level analysis is enabled, providing a summary of the method analysis results alongside the detailed method information. - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L239-L239) -- [context-manager.js](file://context-manager.js#L491-L519) - -**Section sources** -- [context-manager.js](file://context-manager.js#L239-L239) -- [context-manager.js](file://context-manager.js#L491-L519) - -## LLM Context Generation - -The method-level analysis directly supports LLM context generation by creating compact representations of methods that can be efficiently consumed by language models. When method-level analysis is enabled, the generateLLMContext function produces a different output structure. - -```mermaid -flowchart TD -Start([generateLLMContext]) --> CheckMethodLevel{"methodLevel enabled?"} -CheckMethodLevel --> |Yes| GenerateMethodContext["generateMethodContext(analysisResults)"] -GenerateMethodContext --> CreateMethodsObject["Create methods object with:
- relativePath
- method name
- line number
- token count"] -CreateMethodsObject --> AddMethodStats["Add methodStats to context"] -AddMethodStats --> ReturnContext["Return context with methods and methodStats"] -CheckMethodLevel --> |No| GenerateCompactPaths["generateCompactPaths(analysisResults)"] -GenerateCompactPaths --> ReturnPaths["Return context with paths"] -ReturnContext --> End([Return context]) -ReturnPaths --> End -``` - -When method-level analysis is enabled, the generated context includes a `methods` property that organizes methods by their relative file path. Each method is represented with its name, line number, and token count, providing essential information without including the full method content. This creates a compact representation that preserves the structure and relative complexity of the codebase. - -The context also includes `methodStats` with aggregate information about the total methods found, included methods, and total method tokens. This summary helps users understand the scope of the analysis and the proportion of methods that were included in the final context. - -The compact representation significantly reduces the token count of the context while preserving important structural information, making it ideal for LLM consumption where context window size is limited. - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L491-L519) -- [context-manager.js](file://context-manager.js#L614-L643) - -**Section sources** -- [context-manager.js](file://context-manager.js#L491-L519) - -## Common Issues and Best Practices - -### Common Issues - -**Inaccurate Method Extraction**: The regex-based extraction may fail with complex syntax such as: -- Methods with template literals in parameters -- Methods with complex destructuring patterns -- Minified or obfuscated code -- Unconventional formatting that breaks pattern matching - -**Pattern Matching Issues**: Users may encounter problems with filter patterns due to: -- Case sensitivity (patterns are case-insensitive but exact matching may be needed) -- Special characters in method names -- Conflicting include/exclude rules -- Incorrect file paths in fully qualified method names - -### Best Practices for Method Filter Patterns - -**Effective Include Patterns**: -- Use specific method names for critical business logic: `calculateTokens`, `handleRequest` -- Use wildcards for method categories: `*Handler`, `*Validator`, `*Manager` -- Use class-based patterns: `TokenCalculator.*` to include all methods in a class -- Combine multiple patterns in `.methodinclude` to capture related functionality - -**Effective Ignore Patterns**: -- Exclude test methods: `*test*`, `*spec*` -- Exclude debug methods: `*debug*`, `console`, `logger` -- Exclude utility methods: `*helper*`, `*util*` -- Exclude lifecycle methods if not needed: `componentDidMount`, `ngOnInit` - -**Configuration Management**: -- Place `.methodinclude` and `.methodignore` in the project root for project-specific rules -- Use comments (lines starting with #) to document pattern purposes -- Test patterns with a small codebase before applying to large projects -- Use the verbose mode to verify which methods are being included/excluded - -The method-level analysis feature provides powerful capabilities for optimizing LLM context generation, but requires careful configuration to ensure accurate and useful results. By following these best practices, users can create effective filter patterns that capture the most important methods while excluding noise and boilerplate code. - -**Section sources** -- [README.md](file://README.md#L481-L500) -- [CLAUDE.md](file://CLAUDE.md#L101-L127) \ No newline at end of file diff --git a/docs/content-en/Core Features/Token Counting.md b/docs/content-en/Core Features/Token Counting.md deleted file mode 100644 index 0e5fb5d..0000000 --- a/docs/content-en/Core Features/Token Counting.md +++ /dev/null @@ -1,278 +0,0 @@ -# Token Counting - - -**Referenced Files in This Document** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js) - *Updated in recent commit* -- [context-manager.js](file://context-manager.js) - *Modified in recent commit* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in recent commit* -- [package.json](file://package.json#L35-L38) -- [README.md](file://README.md#L294-L356) - - -## Update Summary -**Changes Made** -- Updated token counting implementation to use new TokenUtils class -- Added documentation for exact token counting with tiktoken library -- Enhanced estimated token counting section with updated ratios and implementation -- Added integration details with GitIngest formatter -- Updated performance implications section with new findings -- Added troubleshooting guidance for tiktoken installation issues - -## Table of Contents -1. [Introduction](#introduction) -2. [Token Calculation Methods](#token-calculation-methods) -3. [Exact Token Counting with tiktoken](#exact-token-counting-with-tiktoken) -4. [Estimated Token Counting Implementation](#estimated-token-counting-implementation) -5. [File Type Specific Examples](#file-type-specific-examples) -6. [Integration with File and Project Statistics](#integration-with-file-and-project-statistics) -7. [LLM Context Generation](#llm-context-generation) -8. [Performance Implications](#performance-implications) -9. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) -10. [Installation and Configuration](#installation-and-configuration) - -## Introduction - -The context-manager tool provides sophisticated token counting functionality to support LLM context management and code analysis. The system implements a dual approach to token counting, combining exact GPT-4 compatible calculations with intelligent estimation methods. This documentation details the implementation, usage, and integration of the token counting system within the context-manager tool. - -**Section sources** -- [context-manager.js](file://context-manager.js#L7-L8) -- [README.md](file://README.md#L294-L356) - -## Token Calculation Methods - -The token counting system in context-manager implements two complementary methods for determining token counts: exact counting using the tiktoken library and estimated counting using character-per-token ratios. The system automatically selects the appropriate method based on library availability and performance requirements. - -The primary entry point for token calculation is the `calculateTokens` method in the `TokenCalculator` class, which delegates to the `TokenUtils.calculate` method. This utility class serves as a dispatcher between the exact and estimated counting methods. When tiktoken is available, the system uses exact counting; otherwise, it falls back to estimation. - -```mermaid -flowchart TD -Start([calculateTokens]) --> CheckTiktoken{"tiktoken available?"} -CheckTiktoken --> |Yes| ExactCounting["Use tiktoken.encode()"] -CheckTiktoken --> |No| EstimateCounting["Use estimateTokens()"] -ExactCounting --> ReturnExact["Return exact token count"] -EstimateCounting --> ReturnEstimate["Return estimated token count"] -ReturnExact --> End([Method complete]) -ReturnEstimate --> End -``` - -**Diagram sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L20-L32) - -**Section sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L20-L32) -- [context-manager.js](file://context-manager.js#L280-L292) - -## Exact Token Counting with tiktoken - -The context-manager tool uses the tiktoken library to provide exact GPT-4 compatible token counts when available. The implementation follows a graceful degradation pattern, attempting to load tiktoken at initialization and falling back to estimation if the library is not present. - -The exact token counting process uses the cl100k_base encoding, which is the tokenizer used by GPT-4, GPT-3.5-Turbo, and other models. This ensures that token counts are accurate representations of how these models would process the text. - -```mermaid -sequenceDiagram -participant Calculator as TokenCalculator -participant Tiktoken as tiktoken Library -participant Encoding as cl100k_base Encoding -Calculator->>Calculator : calculateTokens(content, filePath) -Calculator->>Tiktoken : Check if tiktoken is available -alt tiktoken available -Calculator->>Encoding : get_encoding('cl100k_base') -Encoding-->>Calculator : Return encoding instance -Calculator->>Encoding : encode(content) -Encoding-->>Calculator : Return token array -Calculator->>Encoding : free() memory -Calculator->>Calculator : Return token count -else tiktoken not available -Calculator->>Calculator : Call estimateTokens() -end -``` - -**Diagram sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L20-L32) -- [package.json](file://package.json#L35-L38) - -**Section sources** -- [lib/utils/token-utils.js](file:///Users/hakki.sagdiс/Documents/GitHub/context-manager/lib/utils/token-utils.js#L20-L32) -- [package.json](file://package.json#L35-L38) - -## Estimated Token Counting Implementation - -When the tiktoken library is unavailable, the context-manager tool falls back to an estimation method that uses extension-specific character-per-token ratios. This approach provides reasonably accurate estimates (~95% accuracy) while maintaining performance and reducing dependencies. - -The estimation algorithm follows these steps: -1. Determine the file extension from the filePath parameter -2. Look up the appropriate characters-per-token ratio based on the extension -3. Clean the text by normalizing whitespace -4. Calculate the estimated token count using the character ratio - -```mermaid -flowchart TD -Start([estimateTokens]) --> ExtractExt["Extract file extension"] -ExtractExt --> LookupRatio["Look up charsPerToken ratio"] -LookupRatio --> CleanText["Clean text: replace\\s+ with single space"] -CleanText --> Calculate["Calculate: Math.ceil(cleanText.length / charsPerToken)"] -Calculate --> Return["Return estimated token count"] -``` - -The implementation includes specific character-per-token ratios for common file types: -- JavaScript/TypeScript: 3.2 characters per token -- JSON: 2.5 characters per token -- Markdown/Text: 4.0 characters per token -- YAML: 3.5 characters per token -- HTML/XML: 2.8 characters per token - -**Diagram sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L45-L65) - -**Section sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L45-L65) - -## File Type Specific Examples - -The token counting system handles different file types appropriately through the extension-specific character-per-token ratios in the estimation method. When exact counting is available via tiktoken, the system provides accurate counts regardless of file type. - -For JavaScript files (.js, .ts, .jsx, .tsx), the system uses a ratio of 3.2 characters per token, reflecting the typical density of code in these languages. Markdown and plain text files use a more generous 4.0 characters per token, accounting for the higher proportion of spaces and formatting in documentation. - -Configuration files like JSON, YAML, and XML have their own specific ratios that reflect their structural characteristics. JSON uses 2.5 characters per token due to its compact syntax with braces, brackets, and quotes, while XML and HTML use 2.8 characters per token to account for tag verbosity. - -The system determines if a file should be analyzed as a text file through the `isTextFile` method, which checks both file extensions and common text file names like "readme", "license", and "changelog". - -**Section sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L45-L65) -- [context-manager.js](file://context-manager.js#L306-L321) - -## Integration with File and Project Statistics - -Token counts are integrated throughout the file and project statistics system, providing comprehensive analysis of codebase size and complexity. The `analyzeFile` method calls `calculateTokens` for each file and incorporates the results into detailed statistics. - -The system maintains multiple levels of statistical aggregation: -- Per-file statistics including token count, size in bytes, and line count -- Extension-level statistics aggregating counts across all files of the same type -- Directory-level statistics showing token distribution by top-level directory -- Project-level summary statistics - -These statistics are updated in the `updateStats` method, which processes the file information and accumulates totals for the entire project. The statistics include both raw counts and derived metrics like average tokens per file. - -```mermaid -classDiagram -class TokenCalculator { -+stats : StatsObject -+analyzeFile(filePath) : FileInfo -+updateStats(fileInfo) : void -+calculateTokens(content, filePath) : number -+estimateTokens(content, filePath) : number -} -class FileInfo { -+path : string -+relativePath : string -+sizeBytes : number -+tokens : number -+lines : number -+extension : string -} -class StatsObject { -+totalFiles : number -+totalTokens : number -+totalBytes : number -+totalLines : number -+byExtension : Map[string, ExtStats] -+byDirectory : Map[string, DirStats] -+largestFiles : FileInfo[] -} -class ExtStats { -+count : number -+tokens : number -+bytes : number -+lines : number -} -class DirStats { -+count : number -+tokens : number -+bytes : number -+lines : number -} -TokenCalculator --> FileInfo : "produces" -TokenCalculator --> StatsObject : "updates" -StatsObject --> ExtStats : "contains" -StatsObject --> DirStats : "contains" -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L323-L351) -- [context-manager.js](file://context-manager.js#L455-L480) - -**Section sources** -- [context-manager.js](file://context-manager.js#L323-L351) -- [context-manager.js](file://context-manager.js#L455-L480) - -## LLM Context Generation - -Token counts directly influence LLM context generation through the `generateLLMContext` method, which creates optimized file lists for AI consumption. The context generation process uses token statistics to prioritize files and methods that are most relevant for LLM processing. - -When method-level analysis is enabled, the system generates detailed method context including token counts for individual methods. This allows for fine-grained control over which code elements are included in the LLM context. - -The context generation supports two formats: -- Compact format: Organized file paths without token counts (~2.3k characters) -- Detailed format: Full method-level information with token counts (~8.6k characters) - -The choice of format affects how token counts are presented in the output, with the compact format focusing on file organization and the detailed format providing comprehensive token information for each method. - -**Section sources** -- [context-manager.js](file://context-manager.js#L482-L503) - -## Performance Implications - -The token counting system balances accuracy and performance through its dual-method approach. Exact counting with tiktoken provides precise GPT-4 compatible results but incurs additional overhead from library loading and encoding operations. Estimated counting is faster and has no external dependencies but provides approximate results. - -The performance implications of each method are: -- **Exact counting**: Higher accuracy (100%), slower performance, requires tiktoken dependency -- **Estimated counting**: Lower accuracy (~95%), faster performance, no external dependencies - -The system is designed to prefer exact counting when available, as indicated by the startup message that shows "✅ Exact (using tiktoken)" when the library is loaded successfully. When tiktoken is not available, the system falls back to estimation with a "⚠️ Estimated" indicator. - -For large codebases, the performance difference becomes more significant, making estimated counting preferable when absolute precision is not required. The estimation method's O(n) complexity for text cleaning and simple division makes it highly efficient even for large files. - -**Section sources** -- [context-manager.js](file://context-manager.js#L659-L659) -- [README.md](file://README.md#L294-L356) - -## Common Issues and Troubleshooting - -Common issues with token counting in the context-manager tool typically relate to inaccurate estimates for non-standard file types or problems with tiktoken installation. The most frequent issues include: - -1. **Inaccurate estimates for non-standard file types**: When a file has an uncommon extension not included in the predefined mapping, the system uses a default ratio of 3.5 characters per token. This may lead to inaccurate estimates for specialized file formats. - -2. **tiktoken not installed**: If the tiktoken library is not properly installed, the system falls back to estimation mode. This can be identified by the "⚠️ Estimated" message during execution. - -3. **Permission issues**: On some systems, installing native dependencies like tiktoken may require elevated permissions or specific build tools. - -4. **Version compatibility**: The package.json specifies tiktoken version ^1.0.0, and version mismatches could cause loading failures. - -To troubleshoot token counting issues, users should first verify tiktoken installation and check the startup message to confirm whether exact or estimated counting is being used. - -**Section sources** -- [package.json](file://package.json#L35-L38) -- [README.md](file://README.md#L294-L356) - -## Installation and Configuration - -To ensure exact token counting, the tiktoken library must be properly installed. The context-manager tool lists tiktoken as both a dependency and optionalDependency in package.json, allowing the tool to function without it while encouraging installation for exact counting. - -Installation is performed via npm: -```bash -npm install tiktoken -``` - -The implementation uses a try-catch block to load tiktoken, allowing graceful degradation when the library is not available: - -```javascript -let tiktoken = null; -try { tiktoken = require('tiktoken'); } catch {} -``` - -This pattern ensures that the tool remains functional even if tiktoken installation fails or is not performed, while still providing the option for exact counting when desired. The startup sequence displays the token calculation method being used, helping users verify their installation status. - -**Section sources** -- [lib/utils/token-utils.js](file://lib/utils/token-utils.js#L7-L9) -- [package.json](file://package.json#L35-L38) -- [README.md](file://README.md#L294-L356) \ No newline at end of file diff --git a/docs/content-en/GitIngest Format Specification.md b/docs/content-en/GitIngest Format Specification.md deleted file mode 100644 index a53f41c..0000000 --- a/docs/content-en/GitIngest Format Specification.md +++ /dev/null @@ -1,348 +0,0 @@ -# GitIngest Format Specification - - -**Referenced Files in This Document** -- [GitIngestFormatter](file://lib/formatters/gitingest-formatter.js) -- [context-manager.js](file://context-manager.js) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md) -- [README.md](file://README.md) -- [test-gitingest.js](file://test/test-gitingest.js) -- [test-gitingest-json.js](file://test/test-gitingest-json.js) - - -## Table of Contents -1. [Introduction](#introduction) -2. [Purpose and Use Cases](#purpose-and-use-cases) -3. [Format Structure](#format-structure) -4. [Versioning System](#versioning-system) -5. [Implementation Details](#implementation-details) -6. [Method-Level Filtering](#method-level-filtering) -7. [Practical Examples](#practical-examples) -8. [LLM Consumption Guidelines](#llm-consumption-guidelines) -9. [Troubleshooting](#troubleshooting) -10. [Integration Workflows](#integration-workflows) - -## Introduction - -The GitIngest format specification defines a standardized text-based digest format for codebase representation optimized for Large Language Model (LLM) consumption. This format enables developers to consolidate entire project contexts into a single, structured text file that can be efficiently processed by AI assistants like ChatGPT, Claude, or other LLMs. - -The implementation in the context-manager tool provides a JavaScript-based solution that generates GitIngest-style digests from codebases, incorporating project metadata, directory structure visualization, and complete file contents in a prompt-friendly format. - -**Section sources** -- [README.md](file://README.md#L150-L170) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L10) - -## Purpose and Use Cases - -The GitIngest format serves as a bridge between complex codebases and LLM context windows, addressing the fundamental limitation of finite context sizes in language models. By consolidating essential project information into a single, well-structured text file, it enables comprehensive code understanding and analysis. - -Key purposes include: -- **LLM Context Provision**: Deliver complete project context within token limits -- **Codebase Snapshotting**: Create archival representations of project states -- **Collaboration Facilitation**: Share complete project context with team members or AI assistants -- **Analysis Enablement**: Support deep code analysis, refactoring suggestions, and documentation generation - -Primary use cases: -- **AI-Assisted Development**: Provide full context for code generation, debugging, and optimization -- **Code Reviews**: Share complete project snapshots for thorough review -- **Onboarding**: Accelerate new developer integration with comprehensive project overviews -- **Documentation Generation**: Serve as input for automated documentation systems -- **Architecture Analysis**: Enable holistic assessment of code structure and patterns - -**Section sources** -- [README.md](file://README.md#L150-L200) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L10) - -## Format Structure - -The GitIngest format follows a hierarchical structure designed for maximum readability and efficient parsing by both humans and LLMs. The format consists of three main sections: summary header, directory tree, and file contents. - -### Summary Header -The header provides essential project metadata: -- Directory name -- Number of files analyzed -- Method filtering status (when applicable) -- Estimated token count - -### Directory Tree -A visual representation of the project structure using ASCII characters, showing the hierarchical organization of files and directories. The tree follows standard directory listing conventions with appropriate connectors. - -### File Contents -The core of the digest, containing complete file contents separated by clear delimiters. Files are sorted by token count (largest first) to prioritize important files within LLM context windows. - -```mermaid -flowchart TD -A[GitIngest Digest] --> B[Summary Header] -A --> C[Directory Tree] -A --> D[File Contents] -B --> B1["Directory: project-name"] -B --> B2["Files analyzed: count"] -B --> B3["Method filtering: mode"] -B --> B4["Estimated tokens: count"] -C --> C1["Directory structure:"] -C --> C2["└── project/"] -C --> C3[" ├── src/"] -C --> C4[" └── README.md"] -D --> D1["================================================"] -D --> D2["FILE: relative-path"] -D --> D3["================================================"] -D --> D4["file content"] -``` - -**Diagram sources** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L35-L50) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L15-L30) - -## Versioning System - -The context-manager implementation follows a version tracking system that aligns with the reference GitIngest format while maintaining its own versioning for compatibility and feature tracking. - -### Current Implementation -- **GitIngest Version Reference**: v0.3.1 (2025-07-31) -- **Implementation Date**: October 13, 2025 -- **Source Repository**: https://github.com/coderamp-labs/gitingest - -### Version History -| Date | GitIngest Version | Notes | -|------|-------------------|-------| -| 2025-10-13 | v0.3.1 | Initial implementation based on GitIngest format | - -The versioning system ensures compatibility with the evolving GitIngest specification while allowing for JavaScript-specific optimizations and feature additions. The implementation maintains a snapshot of the reference implementation in the documentation directory for audit purposes. - -**Section sources** -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L79) - -## Implementation Details - -The GitIngest format is implemented through the `GitIngestFormatter` class, which orchestrates the generation of the digest file from analyzed codebase data. The implementation is designed to be dependency-free and compatible with the core context-manager analysis pipeline. - -### Core Components -- **GitIngestFormatter Class**: Main formatter that generates the digest -- **Token Count Formatting**: Converts raw token counts to human-readable formats (k/M) -- **Tree Structure Generator**: Creates visual directory representations -- **File Content Processor**: Handles file reading and content inclusion - -### Processing Pipeline -1. **Initialization**: Accepts project root, statistics, and analysis results -2. **Method Filter Detection**: Automatically detects method-level filtering configuration -3. **Digest Generation**: Combines summary, tree, and file contents -4. **Output**: Saves the complete digest to a text file - -```mermaid -classDiagram -class GitIngestFormatter { -+string projectRoot -+object stats -+array analysisResults -+boolean methodFilterEnabled -+MethodAnalyzer methodAnalyzer -+MethodFilterParser methodFilter -+generateDigest() string -+generateSummary() string -+generateTree() string -+buildFileTree() object -+formatTreeNode(node, prefix, isLast) string -+generateFileContents() string -+generateFilteredFileContent(content, filePath) string -+extractMethodBlock(lines, startLine) string -+saveToFile(outputPath) number -} -class MethodAnalyzer { -+extractMethods(content, filePath) array -} -class MethodFilterParser { -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -} -GitIngestFormatter --> MethodAnalyzer : "uses" -GitIngestFormatter --> MethodFilterParser : "uses" -GitIngestFormatter --> TokenUtils : "uses format" -GitIngestFormatter --> FileUtils : "uses isCode" -``` - -**Diagram sources** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L4-L5) - -## Method-Level Filtering - -The GitIngest implementation supports optional method-level filtering, allowing for more granular control over the content included in the digest. This feature enables developers to focus on specific methods of interest while excluding boilerplate or utility functions. - -### Filter Configuration -- **.methodinclude**: INCLUDE mode - only specified methods are included -- **.methodignore**: EXCLUDE mode - specified methods are excluded - -### Filter Syntax -| Pattern | Description | -|---------|-------------| -| `methodName` | Exact method name match | -| `*pattern*` | Wildcard matching (contains pattern) | -| `Class.*` | All methods in a specific class | -| `file.method` | Specific method in a specific file | -| `!pattern` | Negation (exclude pattern) | - -When method filtering is active, the digest includes only the filtered methods within each file, accompanied by metadata indicating which methods were included. This selective inclusion significantly reduces token usage while maintaining focus on critical functionality. - -```mermaid -sequenceDiagram -participant Formatter as GitIngestFormatter -participant Analyzer as MethodAnalyzer -participant Filter as MethodFilterParser -participant File as File System -Formatter->>Formatter : detectMethodFilters() -alt Method filtering enabled -Formatter->>Analyzer : extractMethods(content) -Formatter->>Filter : shouldIncludeMethod() -Formatter->>Formatter : generateFilteredContent() -loop For each included method -Formatter->>Formatter : extractMethodBlock() -Formatter->>Formatter : Add method with metadata -end -else Full file content -Formatter->>File : readFileSync() -Formatter->>Formatter : Include full content -end -Formatter->>Formatter : Return complete digest -``` - -**Diagram sources** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L200-L225) -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L226-L257) - -## Practical Examples - -The GitIngest format can be generated through multiple workflows, providing flexibility for different use cases and performance requirements. - -### Direct Generation -Generate a digest directly from codebase analysis: -```bash -context-manager --gitingest -context-manager -g -``` - -### JSON-Based Generation -Generate digest from existing JSON reports (faster, no re-scan): -```bash -# From detailed analysis report -context-manager --gitingest-from-report token-analysis-report.json - -# From LLM context file -context-manager --gitingest-from-context llm-context.json - -# Using default filenames -context-manager --gitingest-from-report -context-manager --gitingest-from-context -``` - -### Combined Workflows -Combine digest generation with other outputs: -```bash -# Generate both digest and detailed report -context-manager -g -s - -# Two-step workflow for repeated digest generation -context-manager --save-report -context-manager --gitingest-from-report -``` - -The output `digest.txt` file contains the complete formatted digest, ready for LLM consumption or archival purposes. - -**Section sources** -- [README.md](file://README.md#L170-L200) -- [test-gitingest-json.js](file://test/test-gitingest-json.js#L1-L225) - -## LLM Consumption Guidelines - -To maximize the effectiveness of GitIngest format for LLM interactions, follow these best practices: - -### Optimal Usage Patterns -- **Context Provisioning**: Paste the entire digest at the beginning of your conversation with the LLM -- **Focused Queries**: After providing context, ask specific questions about architecture, implementation, or improvements -- **Incremental Analysis**: For very large codebases, consider generating multiple digests focused on specific subsystems - -### Recommended Query Types -- **Architecture Questions**: "Based on the directory structure, what appears to be the main architectural pattern?" -- **Code Understanding**: "Explain the purpose of the [file] based on its content and position in the project structure" -- **Improvement Suggestions**: "Identify potential improvements to the error handling pattern in this codebase" -- **Documentation Generation**: "Create API documentation based on the exported methods in these files" - -### Performance Considerations -- **Token Efficiency**: The digest format is optimized to provide maximum context within token limits -- **File Ordering**: Files are sorted by size (largest first) to prioritize important files in context windows -- **Method Filtering**: Use method-level filtering to further reduce token usage when focusing on specific functionality - -**Section sources** -- [README.md](file://README.md#L190-L200) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L79) - -## Troubleshooting - -Common issues and their solutions when working with the GitIngest format: - -### File Generation Issues -- **Digest not created**: Ensure the output directory is writable and you have sufficient permissions -- **Missing files**: Verify that files are not excluded by `.gitignore`, `.contextignore`, or other filter rules -- **Empty digest**: Check that the analysis found files matching the inclusion criteria - -### Method Filtering Problems -- **Filter not applied**: Ensure `.methodinclude` or `.methodignore` files exist in the project root -- **Unexpected methods included**: Review pattern syntax and consider using negation patterns -- **No methods shown**: Verify method extraction patterns match your code style (function declarations, arrow functions, etc.) - -### Content Quality Issues -- **Truncated methods**: The implementation limits method extraction to 100 lines for safety; very long methods are truncated -- **Encoding issues**: Ensure files are saved in UTF-8 encoding to prevent reading errors -- **Large digest size**: Use method-level filtering or adjust include/exclude patterns to reduce output size - -### JSON Source Problems -- **Invalid JSON format**: Ensure source JSON files follow the expected structure for reports or context files -- **Missing fields**: Verify that required fields (project, paths, files) are present in source JSON -- **Path resolution issues**: Ensure relative paths in JSON files are correct and files exist at specified locations - -**Section sources** -- [test-gitingest-json.js](file://test/test-gitingest-json.js#L150-L180) -- [context-manager.js](file://context-manager.js#L20-L50) - -## Integration Workflows - -The GitIngest format supports various integration workflows that enhance development productivity and AI-assisted coding. - -### Development Workflow Integration -```mermaid -flowchart LR -A[Code Changes] --> B[Run Analysis] -B --> C{Export Choice} -C --> D[Save Report] -C --> E[Generate Context] -C --> F[Create Digest] -C --> G[Copy to Clipboard] -D --> H[Archive for History] -E --> I[CI/CD Integration] -F --> J[LLM Analysis] -G --> K[Immediate AI Assistance] -``` - -### CI/CD Pipeline Integration -Integrate GitIngest generation into automated workflows: -```bash -# In CI/CD script -npm run analyze -- --save-report -npm run gitingest -- --gitingest-from-report - -# Upload digest as artifact -aws s3 cp digest.txt s3://project-artifacts/${GIT_COMMIT}/digest.txt -``` - -### Interactive Development Loop -1. Make code changes -2. Run `context-manager --gitingest` -3. Copy digest content -4. Paste into LLM interface with query -5. Implement suggestions -6. Repeat - -This tight feedback loop enables rapid iteration and continuous improvement with AI assistance. - -**Section sources** -- [README.md](file://README.md#L200-L220) -- [context-manager.js](file://context-manager.js#L100-L150) \ No newline at end of file diff --git a/docs/content-en/Installation.md b/docs/content-en/Installation.md deleted file mode 100644 index b7e2e0b..0000000 --- a/docs/content-en/Installation.md +++ /dev/null @@ -1,290 +0,0 @@ -# Installation - - -**Referenced Files in This Document** -- [README.md](file://README.md) -- [package.json](file://package.json) -- [bin/cli.js](file://bin/cli.js) -- [context-manager.js](file://context-manager.js) - - -## Table of Contents -1. [Prerequisites](#prerequisites) -2. [Installation Methods](#installation-methods) -3. [Token Counting Configuration](#token-counting-configuration) -4. [Configuration Files](#configuration-files) -5. [Verification and Usage](#verification-and-usage) -6. [Integration with Development Workflows](#integration-with-development-workflows) -7. [Troubleshooting](#troubleshooting) - -## Prerequisites - -Before installing the context-manager tool, ensure your system meets the following requirements: - -- **Node.js**: Version 14.0.0 or higher (specified in package.json under "engines") -- **npm**: Node Package Manager, typically installed with Node.js - -These prerequisites are essential for both global and local installations of the package. The tool is designed to work across different operating systems including macOS, Linux, and Windows, leveraging Node.js's cross-platform capabilities for consistent behavior. - -**Section sources** -- [package.json](file://package.json#L15-L17) - -## Installation Methods - -The context-manager tool can be installed using npm through two primary methods: globally or locally. Each method serves different use cases depending on your development workflow. - -### Global Installation - -Global installation makes the `context-manager` command available system-wide, allowing you to use it from any directory in your terminal: - -```bash -npm install -g @hakkisagdic/context-manager -``` - -This approach is recommended if you plan to use the tool across multiple projects or want to access it as a standalone CLI tool from anywhere in your system. After global installation, you can run `context-manager` commands directly without prefixing them with `npx`. - -### Local Installation - -Local installation adds the package as a dependency to your current project: - -```bash -npm install @hakkisagdic/context-manager -``` - -This method is ideal when you want to include context-manager as part of a specific project's toolchain or when working in a team environment where consistent tool versions are important. With local installation, you can execute the tool using `npx`: - -```bash -npx context-manager --help -``` - -Local installation ensures that all team members use the same version of the tool as defined in the project's package-lock.json, promoting consistency across development environments. - -**Section sources** -- [README.md](file://README.md#L235-L245) - -## Token Counting Configuration - -The context-manager tool provides two methods for token counting, with an optional dependency that enhances accuracy. - -### Exact Token Counting with tiktoken - -For precise token counting that matches GPT-4's tokenization, install the tiktoken package: - -```bash -npm install tiktoken -``` - -When tiktoken is available, the tool uses exact token counting by loading the cl100k_base encoding (used by GPT-4). This provides the most accurate token counts for LLM context management. - -### Fallback to Smart Estimation - -If tiktoken is not installed, the tool automatically falls back to a smart estimation algorithm with approximately 95% accuracy. The estimation uses character-to-token ratios specific to file types: - -- JavaScript/TypeScript: 3.2 characters per token -- JSON: 2.5 characters per token -- Markdown: 4.0 characters per token -- HTML/XML: 2.8 characters per token -- Other text files: 3.5 characters per token - -The tool first attempts to load tiktoken, and if unsuccessful, uses the estimation method. This is implemented in the `calculateTokens` method of the TokenCalculator class, which tries to require tiktoken and catches any errors to fall back to estimation. - -**Section sources** -- [README.md](file://README.md#L219-L223) -- [context-manager.js](file://context-manager.js#L287-L317) - -## Configuration Files - -The context-manager tool uses several configuration files to control file and method inclusion/exclusion, with a defined priority hierarchy. - -### File-Level Configuration - -#### .contextignore (EXCLUDE Mode) -This file contains patterns for files to exclude from analysis. It follows gitignore-style syntax: -```bash -**/*.md # All documentation -**/*.json # All configuration files -infrastructure/** # Infrastructure code -``` - -#### .contextinclude (INCLUDE Mode) -This file specifies patterns for files to include in analysis, taking priority over .contextignore: -```bash -utility-mcp/src/**/*.js -!utility-mcp/src/workflows/** -``` - -### Method-Level Configuration - -#### .methodinclude -Defines methods to include in method-level analysis: -```bash -calculateTokens -*Handler -TokenCalculator.* -``` - -#### .methodignore -Specifies methods to exclude from analysis: -```bash -*test* -*debug* -console -``` - -### Configuration Priority Hierarchy - -The tool follows a strict priority order when determining which files and methods to analyze: - -1. **`.gitignore`** - Always respected (project root) -2. **`.contextinclude`** - Highest priority for files (INCLUDE mode) -3. **`.contextignore`** - Used when no include file exists (EXCLUDE mode) -4. **`.methodinclude`** - Highest priority for methods (INCLUDE mode) -5. **`.methodignore`** - Used when no method include file exists (EXCLUDE mode) - -When both .contextinclude and .contextignore exist, the include file takes precedence and the ignore file is ignored. This allows for precise control over analysis scope. - -**Section sources** -- [README.md](file://README.md#L145-L184) -- [context-manager.js](file://context-manager.js#L108-L218) - -## Verification and Usage - -After installation, verify the tool is working correctly and explore its basic usage patterns. - -### Verification - -Test the installation by accessing the help menu: - -```bash -context-manager --help -``` - -This should display the CLI options and usage information, confirming the tool is properly installed and accessible. The help output includes available options like `--save-report`, `--context-export`, and `--method-level`, along with examples of common usage patterns. - -### Basic Usage Examples - -#### Interactive Analysis -Running the tool without arguments initiates interactive mode with export options: -```bash -context-manager -``` - -#### Direct Export Options -```bash -# Save detailed JSON report -context-manager --save-report - -# Generate LLM context file -context-manager --context-export - -# Copy context to clipboard -context-manager --context-clipboard -``` - -#### Method-Level Analysis -```bash -# Analyze specific methods only -context-manager --method-level --context-clipboard -``` - -The tool provides immediate feedback during execution, showing whether it's using exact token counting (with tiktoken) or estimation, the analysis mode (INCLUDE/EXCLUDE), and summary statistics upon completion. - -**Section sources** -- [README.md](file://README.md#L247-L255) -- [bin/cli.js](file://bin/cli.js#L35-L65) - -## Integration with Development Workflows - -The context-manager tool can be integrated into various development workflows to optimize LLM context usage and monitor codebase complexity. - -### Package.json Scripts -Add custom scripts to your project's package.json: -```json -"scripts": { - "analyze": "context-manager", - "analyze:methods": "context-manager --method-level", - "llm-context": "context-manager --context-clipboard" -} -``` - -Then use them with: -```bash -npm run analyze -npm run llm-context -``` - -### CI/CD Integration -Incorporate the tool into continuous integration pipelines to monitor codebase growth: -```bash -# In CI script -context-manager --save-report -TOKENS=$(jq '.summary.totalTokens' token-analysis-report.json) -if [ $TOKENS -gt 100000 ]; then - echo "Codebase exceeds LLM context limits" - exit 1 -fi -``` - -### Pre-commit Hooks -Use as a pre-commit hook to ensure code stays within token budgets before pushing changes. - -### LLM Context Preparation -The tool generates optimized file lists for LLM consumption in two formats: -- **Compact format** (~2.3k characters): Minimal JSON structure for frequent AI interactions -- **Detailed format** (~8.6k characters): Comprehensive context for initial project analysis - -These outputs can be automatically fed into AI-assisted development workflows, ensuring developers work with the most relevant code context. - -**Section sources** -- [README.md](file://README.md#L201-L217) -- [package.json](file://package.json#L7-L13) - -## Troubleshooting - -Address common issues that may arise during installation and usage of the context-manager tool. - -### Permission Errors (Global Installation) -When installing globally, you might encounter permission errors: -```bash -npm install -g @hakkisagdic/context-manager -# Error: EACCES: permission denied -``` - -**Solutions:** -- Use a Node.js version manager like nvm that installs Node.js in your home directory -- Change npm's default directory to avoid permission issues -- Use sudo (not recommended for security reasons): `sudo npm install -g @hakkisagdic/context-manager` - -### Missing Dependencies -If tiktoken fails to install, the tool automatically falls back to estimation mode. To resolve installation issues: -```bash -# Clear npm cache -npm cache clean --force - -# Reinstall with fresh dependencies -npm install tiktoken -``` - -### Configuration Issues -#### Include vs Exclude Mode Confusion -- **Problem**: Unexpected files included/excluded -- **Solution**: Check for .contextinclude file presence, as it takes priority over .contextignore - -#### Pattern Matching Problems -- Ensure patterns don't have inline comments -- Use `**` for recursive matching, `*` for single level -- Test patterns with verbose mode to see matching behavior - -### Platform-Specific Issues -On Linux systems without proper clipboard tools: -```bash -# Install required clipboard utilities -sudo apt-get install xclip xsel # Debian/Ubuntu -sudo yum install xclip # CentOS/RHEL -``` - -The tool automatically tries alternative clipboard commands if the primary one fails, providing fallback mechanisms for cross-platform compatibility. - -**Section sources** -- [README.md](file://README.md#L257-L284) -- [context-manager.js](file://context-manager.js#L565-L585) \ No newline at end of file diff --git a/docs/content-en/Output Formats.md b/docs/content-en/Output Formats.md deleted file mode 100644 index cf20e38..0000000 --- a/docs/content-en/Output Formats.md +++ /dev/null @@ -1,390 +0,0 @@ -# Output Formats - - -**Referenced Files in This Document** -- [README.md](file://README.md) - *Updated with GitIngest format details* -- [context-manager.js](file://context-manager.js) - *Added GitIngest generation functions* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *New GitIngest formatter implementation* - - -## Table of Contents -1. [Introduction](#introduction) -2. [Detailed JSON Report](#detailed-json-report) -3. [LLM Context Formats](#llm-context-formats) -4. [Clipboard Format](#clipboard-format) -5. [GitIngest Format](#gitingest-format) -6. [Use Cases and Performance](#use-cases-and-performance) -7. [Parsing Strategies](#parsing-strategies) - -## Introduction - -The context-manager tool provides three primary output formats for different use cases in AI-assisted development workflows. These formats serve distinct purposes in code analysis, LLM context optimization, and project documentation. The tool generates a detailed JSON report for comprehensive analysis, creates LLM context files in both compact and detailed formats, and supports clipboard integration for quick sharing. All export formats maintain consistent structure between file and clipboard outputs, ensuring reliability across different usage scenarios. - -**Section sources** -- [README.md](file://README.md#L1-L891) - -## Detailed JSON Report - -The detailed JSON report provides comprehensive analysis of the codebase with complete metadata, summary statistics, file-level details, and method-level data when applicable. This format is generated when using the `--save-report` flag or selecting the appropriate option in interactive mode. - -The report structure consists of three main sections: -- **metadata**: Contains generation timestamp, project root path, and configuration rules from .gitignore and calculator configuration files -- **summary**: Includes comprehensive statistics such as total files analyzed, token counts, file type distribution, and largest files/directories -- **files**: Contains detailed information for each analyzed file including path, token count, size, lines, and extension - -When method-level analysis is enabled with the `--method-level` flag, additional method-specific data is included in the file objects, providing granular insights into individual functions and their token usage. - -```mermaid -classDiagram -class DetailedJSONReport { -+metadata : object -+summary : object -+files : array -} -class Metadata { -+generatedAt : string -+projectRoot : string -+gitignoreRules : array -+calculatorRules : array -} -class Summary { -+totalFiles : number -+totalTokens : number -+byExtension : object -+largestFiles : array -+byDirectory : object -} -class File { -+path : string -+relativePath : string -+sizeBytes : number -+tokens : number -+lines : number -+extension : string -+methods? : array -} -DetailedJSONReport --> Metadata -DetailedJSONReport --> Summary -DetailedJSONReport --> File -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L784-L799) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L784-L799) - -## LLM Context Formats - -The context-manager tool offers two distinct LLM context formats optimized for different use cases: an ultra-compact format used by default and a detailed format activated with the `--detailed-context` flag. Both formats are designed to provide essential project context for AI assistants while minimizing token usage. - -### Compact Format (~2.3k characters) - -The default compact format provides a minimal yet structured representation of the codebase, containing approximately 2.3k characters in JSON format. This format includes: -- Project metadata (root directory, total files, total tokens) -- Organized file paths grouped by directory with common prefix compression -- Removal of file extensions to save space -- Directory grouping to minimize redundancy - -The compact format prioritizes efficiency and is ideal for frequent AI interactions where token economy is crucial. It maintains the complete JSON structure identical to the llm-context.json file. - -### Detailed Format (~8.6k characters) - -The detailed format, activated with `--detailed-context`, provides a more comprehensive context at approximately 8.6k characters. This format includes: -- Full file paths with extensions -- Importance scores based on token count and project structure -- Directory statistics and file categorization -- Method-level data when method analysis is enabled -- Additional metadata for project understanding - -The detailed format is suitable for initial project analysis, comprehensive documentation, and situations requiring deeper context understanding. - -```mermaid -classDiagram -class LLMContext { -+project : object -+paths? : object -+methods? : object -+methodStats? : object -} -class ProjectMetadata { -+root : string -+totalFiles : number -+totalTokens : number -} -class Paths { -+directoryPath : array -} -class Methods { -+filePath : array -} -class MethodStats { -+totalMethods : number -+includedMethods : number -+totalMethodTokens : number -} -LLMContext --> ProjectMetadata -LLMContext --> Paths -LLMContext --> Methods -LLMContext --> MethodStats -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L482-L503) -- [context-manager.js](file://context-manager.js#L521-L545) -- [context-manager.js](file://context-manager.js#L505-L519) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L482-L545) - -## Clipboard Format - -The clipboard format in context-manager maintains identical structure to the file-based exports, ensuring consistency across different output methods. When using the `--context-clipboard` flag, the tool copies the same JSON structure that would be saved to llm-context.json directly to the system clipboard. - -The implementation handles cross-platform clipboard operations: -- **macOS**: Uses `pbcopy` command -- **Linux**: Attempts `xclip` first, falls back to `xsel` if unavailable -- **Windows**: Uses `clip` command -- **Other platforms**: Provides fallback to file saving if clipboard operation fails - -If the clipboard operation fails for any reason, the tool automatically saves the context to llm-context.json as a fallback, ensuring the user always receives the output regardless of platform limitations. - -```mermaid -sequenceDiagram -participant User -participant Tool as context-manager -participant Clipboard -participant File as llm-context.json -User->>Tool : --context-clipboard -Tool->>Tool : generateLLMContext() -Tool->>Clipboard : Copy JSON (platform-specific) -alt Success -Clipboard-->>Tool : Success -Tool-->>User : "Context copied to clipboard!" -else Failure -Tool->>File : saveContextToFile() -File-->>Tool : Saved -Tool-->>User : "Failed to copy... saved to file" -end -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L547-L579) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L547-L579) - -## GitIngest Format - -The context-manager tool now supports a new output format: GitIngest-style digest files. This format consolidates the entire codebase analysis into a single, prompt-friendly text file that is ideal for LLM consumption. - -### GitIngest Format Overview - -The GitIngest format provides a comprehensive, human-readable summary of the codebase with the following components: -- Project summary and statistics -- Visual directory tree structure -- Complete file contents with clear separators -- Token count estimates -- Method-level filtering when enabled - -This format is inspired by [GitIngest](https://github.com/coderamp-labs/gitingest) and is implemented in pure JavaScript with zero additional dependencies. - -### Generation Methods - -The GitIngest digest can be generated through multiple pathways: - -**Direct Generation** -```bash -# Generate digest directly from codebase analysis -context-manager --gitingest -context-manager -g -``` - -**JSON-Based Generation** -```bash -# Generate digest from existing JSON report (instant, no re-scan) -context-manager --gitingest-from-report token-analysis-report.json - -# Generate digest from LLM context file -context-manager --gitingest-from-context llm-context.json -``` - -**Two-Step Workflow** -```bash -# Step 1: Create analysis report -context-manager --save-report - -# Step 2: Generate digest from report (instant) -context-manager --gitingest-from-report token-analysis-report.json -``` - -### Output Structure - -The generated `digest.txt` file follows this structure: - -``` -Directory: my-project -Files analyzed: 42 -Method filtering: INCLUDE mode active - -Estimated tokens: 15.2k -Directory structure: -└── my-project/ - ├── src/ - │ ├── index.js - │ └── utils.js - └── README.md - - -================================================ -FILE: src/index.js -================================================ -[complete file contents here] - -================================================ -FILE: src/utils.js -================================================ -[complete file contents here] -``` - -### Key Features - -- **Single File Output**: Everything consolidated into one file for easy LLM ingestion -- **Tree Visualization**: Clear directory structure with proper indentation -- **Token Estimates**: Formatted as "1.2k" or "1.5M" for readability -- **Sorted Output**: Files sorted by token count (largest first) -- **Filter Compatibility**: Respects all `.gitignore` and context ignore rules -- **Method-Level Filtering**: When enabled, only includes methods that match filter criteria -- **Performance Optimized**: JSON-based generation is instant with no re-scanning - -### Method-Level Filtering - -When method-level analysis is enabled, the GitIngest formatter applies method filtering based on `.methodinclude` and `.methodignore` configuration files: - -- **INCLUDE Mode**: Only methods specified in `.methodinclude` are included -- **EXCLUDE Mode**: Methods specified in `.methodignore` are excluded - -For code files, only the filtered methods are included in the digest, with clear annotations: - -``` -// File contains 15 methods, showing 5 filtered methods - -// Method: calculateTokens (line 45) -function calculateTokens(content) { - // method implementation -} - -// Method: validateInput (line 89) -function validateInput(data) { - // method implementation -} -``` - -### Implementation Details - -The GitIngest format is implemented through the `GitIngestFormatter` class in `lib/formatters/gitingest-formatter.js`. This class handles: -- Project summary generation -- Directory tree construction -- File content extraction -- Method-level filtering -- Output formatting and file saving - -The formatter automatically detects method filtering configuration and applies it when processing code files. - -```mermaid -classDiagram -class GitIngestFormatter { -+projectRoot : string -+stats : object -+analysisResults : array -+methodFilterEnabled : boolean -+generateDigest() : string -+generateSummary() : string -+generateTree() : string -+generateFileContents() : string -+saveToFile(outputPath) : number -} -class GitIngestFormatter --|> MethodAnalyzer -class GitIngestFormatter --|> MethodFilterParser -class GitIngestFormatter --|> ConfigUtils -class GitIngestFormatter --|> TokenUtils -class GitIngestFormatter --|> FileUtils -``` - -**Diagram sources** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L16-L127) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -## Use Cases and Performance - -The different output formats serve specific use cases in development workflows: - -**Compact Format Use Cases:** -- **LLM Integration**: Structured data for AI assistants with complete project context -- **Programmatic Processing**: JSON format for automated tools and scripts -- **Context Sharing**: Identical format in clipboard and file exports -- **Development Workflows**: Consistent structure for CI/CD and automation - -**Detailed Format Use Cases:** -- **Architecture Planning**: Comprehensive project overview for major decisions -- **New Team Member Onboarding**: Complete codebase understanding -- **Documentation Generation**: Full project structure analysis -- **Code Review Preparation**: Detailed file relationships and importance - -**GitIngest Format Use Cases:** -- **LLM Context Windows**: Paste entire codebase as single context -- **Code Reviews**: Share complete project snapshot -- **Documentation**: Single-file project reference -- **AI Analysis**: Perfect for ChatGPT, Claude, or other LLMs -- **Archival**: Simple project snapshot format -- **Performance-Critical Workflows**: Instant digest generation from existing JSON - -**Performance Considerations:** -- The compact format reduces context size by approximately 89% compared to the full codebase -- Token counting uses tiktoken for GPT-4 compatibility when available, with estimation fallback -- Directory grouping and common prefix compression optimize space usage -- Method-level analysis adds overhead but provides granular context for focused debugging -- JSON-based digest generation provides instant output without re-scanning the codebase - -**Section sources** -- [README.md](file://README.md#L1-L891) - -## Parsing Strategies - -Downstream processing of context-manager outputs can leverage the consistent JSON structure across formats: - -**For Detailed JSON Reports:** -- Extract metadata for audit trails and version tracking -- Analyze file-level statistics for codebase health monitoring -- Process method-level data for focused analysis of critical functions -- Generate visualizations from extension and directory statistics - -**For LLM Context Formats:** -- Parse project metadata to understand scope and scale -- Traverse path groups to reconstruct directory structure -- Utilize method information for targeted code analysis -- Integrate with AI tools that accept structured project context - -**For GitIngest Format:** -- Parse directory tree to understand project structure -- Extract file contents for code analysis -- Process method-level content when filtering is applied -- Use token estimates for context window management - -**General Parsing Recommendations:** -- Validate JSON structure before processing -- Handle optional fields (methods, methodStats) gracefully -- Use streaming parsers for large reports -- Cache parsed results to avoid repeated processing -- Implement error handling for malformed or incomplete data - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L482-L545) \ No newline at end of file diff --git a/docs/content-en/Programmatic API.md b/docs/content-en/Programmatic API.md deleted file mode 100644 index b215f0a..0000000 --- a/docs/content-en/Programmatic API.md +++ /dev/null @@ -1,449 +0,0 @@ -# Programmatic API - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - *Updated in recent commit* -- [index.js](file://index.js) - *Updated in recent commit* -- [README.md](file://README.md) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Core implementation* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in recent commit* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Added in recent commit* - - -## Update Summary -**Changes Made** -- Updated TokenAnalyzer class documentation to reflect its alias relationship with TokenCalculator -- Added new sections for GitIngestFormatter and MethodFilterParser classes -- Updated configuration options to include the new gitingest option -- Added documentation for the new generateDigestFromReport and generateDigestFromContext functions -- Updated usage examples to include the new formatter and parser classes -- Enhanced core components diagram to show new relationships - -## Table of Contents -1. [Introduction](#introduction) -2. [Core Components](#core-components) -3. [TokenAnalyzer Class](#tokenanalyzer-class) -4. [Configuration Options](#configuration-options) -5. [Data Models](#data-models) -6. [Usage Examples](#usage-examples) -7. [Error Handling](#error-handling) -8. [Performance Considerations](#performance-considerations) -9. [Migration Guidance](#migration-guidance) - -## Introduction - -The context-manager tool provides a programmatic interface for analyzing codebases and generating optimized context for LLM (Large Language Model) consumption. The primary entry point is the TokenAnalyzer class, which enables developers to integrate token analysis capabilities directly into Node.js applications. This API allows for automated analysis of project files, method-level extraction, and generation of context-optimized outputs for AI-assisted development workflows. - -The tool is designed to help developers understand their codebase complexity, optimize LLM context usage, and automate analysis tasks within development pipelines. It supports both file-level and method-level analysis, with flexible configuration options for filtering and output formats. - -**Section sources** -- [README.md](file://README.md#L1-L100) - -## Core Components - -The context-manager tool is built around several core components that work together through composition to provide comprehensive analysis capabilities. The TokenAnalyzer class serves as the primary interface, orchestrating interactions between specialized components for different aspects of the analysis process. - -The architecture follows a modular design where each component has a specific responsibility: -- GitIgnoreParser handles file exclusion based on .gitignore and custom ignore rules -- MethodAnalyzer extracts method definitions from code files -- MethodFilterParser applies inclusion/exclusion rules to methods -- TokenCalculator performs the core analysis and token counting -- GitIngestFormatter generates GitIngest-style digest files - -These components are composed within the TokenAnalyzer (implemented as TokenCalculator) to provide a cohesive analysis experience. This design allows for independent development and testing of each component while maintaining a simple interface for end users. - -```mermaid -classDiagram -class TokenAnalyzer { -+constructor(directoryPath, options) -+run() -} -class GitIgnoreParser { -+constructor(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+isIgnored(filePath, relativePath) -} -class MethodAnalyzer { -+extractMethods(content, filePath) -+getLineNumber(content, index) -+isKeyword(name) -} -class MethodFilterParser { -+constructor(methodIncludePath, methodIgnorePath) -+shouldIncludeMethod(methodName, fileName) -} -class GitIngestFormatter { -+constructor(projectRoot, stats, analysisResults) -+generateDigest() -+saveToFile(outputPath) -} -TokenAnalyzer --> GitIgnoreParser : "uses" -TokenAnalyzer --> MethodAnalyzer : "uses" -TokenAnalyzer --> MethodFilterParser : "uses" -TokenAnalyzer --> GitIngestFormatter : "uses for gitingest option" -GitIngestFormatter --> MethodAnalyzer : "uses for method extraction" -GitIngestFormatter --> MethodFilterParser : "uses for method filtering" -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L223) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## TokenAnalyzer Class - -The TokenAnalyzer class is the primary entry point for the context-manager tool's programmatic interface. It provides a simple yet powerful API for analyzing codebases and generating optimized context for LLM consumption. - -### Constructor Parameters - -The TokenAnalyzer constructor accepts two parameters: - -```javascript -const analyzer = new TokenAnalyzer(directoryPath, options); -``` - -- `directoryPath` (string): The path to the directory that should be analyzed. This is typically the root of your project or a specific subdirectory you want to analyze. -- `options` (object): Configuration options that control the behavior of the analysis. See the Configuration Options section for details. - -**Important Note**: TokenAnalyzer is actually an alias for the TokenCalculator class. In the codebase, TokenAnalyzer is exported as an alias of TokenCalculator in the index.js file for backward compatibility. This means that TokenAnalyzer and TokenCalculator are the same class with two different names. - -### run() Method - -The `run()` method executes the complete analysis process and generates the results. When called, it performs the following steps: - -1. Scans the specified directory and its subdirectories -2. Applies ignore rules from .gitignore and custom configuration files -3. Analyzes each file to calculate token counts -4. Optionally performs method-level analysis when enabled -5. Generates comprehensive reports and exports -6. Outputs results to console and/or files based on configuration - -The method is designed to be asynchronous in nature, though it doesn't return a Promise directly. Instead, it handles asynchronous operations internally, particularly when dealing with file system operations and clipboard integration. - -```mermaid -sequenceDiagram -participant Application -participant TokenAnalyzer -participant GitIgnoreParser -participant MethodAnalyzer -participant MethodFilterParser -participant GitIngestFormatter -Application->>TokenAnalyzer : new TokenAnalyzer(path, options) -TokenAnalyzer->>TokenAnalyzer : Initialize components -Application->>TokenAnalyzer : run() -TokenAnalyzer->>GitIgnoreParser : Check if file should be ignored -loop For each file -TokenAnalyzer->>TokenAnalyzer : Read file content -TokenAnalyzer->>TokenAnalyzer : Calculate tokens -alt methodLevel enabled -TokenAnalyzer->>MethodAnalyzer : extractMethods(content) -loop For each method -MethodAnalyzer->>MethodFilterParser : shouldIncludeMethod() -MethodFilterParser-->>MethodAnalyzer : Include/Exclude decision -end -end -TokenAnalyzer->>TokenAnalyzer : Update statistics -end -alt gitingest enabled -TokenAnalyzer->>GitIngestFormatter : Generate digest -GitIngestFormatter->>GitIngestFormatter : Apply method filtering -GitIngestFormatter->>GitIngestFormatter : Format as GitIngest digest -end -TokenAnalyzer->>TokenAnalyzer : Generate reports -TokenAnalyzer->>Application : Output results -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L225-L790) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L13-L522) - -**Section sources** -- [context-manager.js](file://context-manager.js#L225-L790) -- [index.js](file://index.js#L1-L8) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L13-L522) - -## Configuration Options - -The TokenAnalyzer class accepts various options through the options object parameter in its constructor. These options control the behavior of the analysis process and allow for customization based on specific use cases. - -### Available Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| methodLevel | boolean | false | Enables method-level analysis, extracting individual methods from code files | -| verbose | boolean | false | Controls whether detailed information is displayed during analysis | -| saveReport | boolean | false | Saves a detailed JSON report of the analysis to token-analysis-report.json | -| contextExport | boolean | false | Generates an LLM context file (llm-context.json) with optimized file listings | -| contextClipboard | boolean | false | Copies the LLM context directly to the system clipboard | -| gitingest | boolean | false | Generates a GitIngest-style digest file (digest.txt) containing the full codebase content | - -### Option Interactions - -These options can be combined to achieve different analysis workflows: - -- Using `methodLevel: true` enables extraction of individual methods from JavaScript/TypeScript files, providing more granular analysis -- Combining `saveReport: true` with other options allows for both immediate feedback and persistent storage of analysis results -- Using `contextExport: true` or `contextClipboard: true` generates optimized context for LLM consumption, either saving to a file or copying to clipboard -- The `verbose` option controls the amount of information displayed during analysis, with more details shown when enabled -- The `gitingest: true` option generates a comprehensive digest file that includes the full content of all analyzed files in a GitIngest-style format, which is particularly useful for providing complete context to LLMs - -When no export options are specified, the tool will prompt the user to select an export option after completing the analysis. - -**Section sources** -- [README.md](file://README.md#L100-L300) -- [context-manager.js](file://context-manager.js#L225-L232) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L13-L522) - -## Data Models - -The context-manager tool uses specific data models to represent files and methods during analysis. These models are used internally and form the structure of the generated reports and context exports. - -### FileInfo Model - -The FileInfo model represents information about an analyzed file: - -```typescript -interface FileInfo { - path: string; // Absolute path to the file - relativePath: string; // Path relative to the project root - sizeBytes: number; // File size in bytes - tokens: number; // Calculated token count - lines: number; // Number of lines in the file - extension: string; // File extension - methods?: MethodInfo[]; // Array of methods (when methodLevel is enabled) -} -``` - -### MethodInfo Model - -The MethodInfo model represents information about an extracted method: - -```typescript -interface MethodInfo { - name: string; // Method name - line: number; // Line number where the method is defined - tokens: number; // Token count for the method content - file: string; // Relative path to the file containing the method -} -``` - -These models are used to structure the analysis results and are serialized in the generated JSON reports. When method-level analysis is enabled, the tool creates a hierarchical structure where files contain arrays of their methods, allowing for detailed analysis of code complexity at both file and method levels. - -The data models are designed to be lightweight and focused on the essential information needed for token analysis and LLM context optimization. - -**Section sources** -- [context-manager.js](file://context-manager.js#L400-L420) -- [context-manager.js](file://context-manager.js#L480-L500) - -## Usage Examples - -The context-manager tool can be integrated into Node.js applications for automated analysis. The following examples demonstrate common usage patterns. - -### Basic Integration - -```javascript -const { TokenAnalyzer } = require('@hakkisagdic/context-manager'); - -// Basic file-level analysis -const analyzer = new TokenAnalyzer('./src', { - verbose: true, - saveReport: true -}); - -analyzer.run(); -``` - -### Method-Level Analysis - -```javascript -// Method-level analysis with all outputs -const methodAnalyzer = new TokenAnalyzer('./src', { - methodLevel: true, - saveReport: true, - contextExport: true, - verbose: true -}); - -methodAnalyzer.run(); -``` - -### LLM-Optimized Context Generation - -```javascript -// Generate context optimized for LLM consumption -const llmAnalyzer = new TokenAnalyzer('./src', { - methodLevel: true, - contextClipboard: true -}); - -llmAnalyzer.run(); -``` - -### GitIngest Digest Generation - -```javascript -// Generate GitIngest-style digest -const digestAnalyzer = new TokenAnalyzer('./src', { - gitingest: true, - methodLevel: true -}); - -digestAnalyzer.run(); -``` - -### Using GitIngestFormatter Directly - -```javascript -// Use GitIngestFormatter directly for custom digest generation -const { GitIngestFormatter } = require('@hakkisagdic/context-manager'); -const { TokenAnalyzer } = require('@hakkisagdic/context-manager'); - -// First run analysis to get results -const analyzer = new TokenAnalyzer('./src', { methodLevel: true }); -const analysisResults = []; // This would be populated during analysis - -// Create formatter with results -const formatter = new GitIngestFormatter( - process.cwd(), - analyzer.stats, - analysisResults -); - -// Generate and save digest -formatter.saveToFile('custom-digest.txt'); -``` - -### Using MethodFilterParser Directly - -```javascript -// Use MethodFilterParser directly for method filtering -const { MethodFilterParser } = require('@hakkisagdic/context-manager'); - -// Create filter parser with custom paths -const methodFilter = new MethodFilterParser( - './.methodinclude', // Path to include file - './.methodignore' // Path to ignore file -); - -// Check if a method should be included -const shouldInclude = methodFilter.shouldIncludeMethod('getUser', 'UserService'); -``` - -### Generate Digest from Existing Reports - -```javascript -// Generate GitIngest digest from existing token-analysis-report.json -const { generateDigestFromReport } = require('@hakkisagdic/context-manager'); - -generateDigestFromReport('token-analysis-report.json'); - -// Generate GitIngest digest from existing llm-context.json -const { generateDigestFromContext } = require('@hakkisagdic/context-manager'); - -generateDigestFromContext('llm-context.json'); -``` - -These examples show how the TokenAnalyzer can be configured for different use cases, from basic analysis to LLM-optimized context generation. The flexibility of the options allows developers to tailor the analysis to their specific needs, whether for development, debugging, or automated workflows. - -**Section sources** -- [README.md](file://README.md#L700-L800) -- [index.js](file://index.js#L1-L48) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## Error Handling - -The context-manager tool includes comprehensive error handling to ensure robust operation in various environments. The analysis process is designed to gracefully handle file system errors and other exceptions that may occur during execution. - -When a file cannot be read or analyzed, the tool creates an error entry in the results with the error message, allowing the analysis to continue with other files. This prevents a single problematic file from stopping the entire analysis process. - -The tool also handles platform-specific issues, particularly with clipboard operations. On unsupported platforms, it falls back to saving the context to a file instead of attempting clipboard operations that would fail. - -For configuration issues, the tool provides clear feedback about which configuration files are being used and in what mode (INCLUDE or EXCLUDE). This helps users understand why certain files might be included or excluded from the analysis. - -The error handling strategy prioritizes completing the analysis over stopping at the first error, ensuring that users receive as much information as possible even when some parts of the process encounter issues. - -**Section sources** -- [context-manager.js](file://context-manager.js#L400-L415) -- [context-manager.js](file://context-manager.js#L700-L730) - -## Performance Considerations - -When using the context-manager API programmatically, several performance considerations should be taken into account: - -### Token Counting Methods - -The tool supports two methods for token counting: -- **Exact counting** using the tiktoken library (requires installation) -- **Estimation** using character-based heuristics (fallback when tiktoken is not available) - -For optimal accuracy, install the tiktoken package: -```bash -npm install tiktoken -``` - -### Analysis Scope - -The performance of the analysis is directly related to the size of the codebase being analyzed. To optimize performance: -- Limit the analysis to specific directories when possible -- Use configuration files (.contextignore, .contextinclude) to exclude irrelevant files -- Consider the trade-off between analysis depth and execution time - -### Method-Level Analysis - -Enabling method-level analysis significantly increases processing time as it requires parsing code to identify individual methods. This feature should be used when method-level insights are needed, but disabled for simple file-level analysis. - -### Asynchronous Operations - -While the `run()` method doesn't return a Promise, it performs several asynchronous operations internally, particularly for file system access and clipboard operations. In automated workflows, consider the execution time required for large codebases. - -The tool is optimized for performance with caching and efficient file system operations, but very large codebases may still require significant processing time. - -**Section sources** -- [context-manager.js](file://context-manager.js#L300-L350) -- [README.md](file://README.md#L500-L600) - -## Migration Guidance - -When upgrading or migrating to newer versions of the context-manager tool, consider the following guidance: - -### Version Compatibility - -The tool maintains backward compatibility for its core API. The TokenAnalyzer class interface has remained stable across versions, ensuring that existing integrations continue to work. - -### Configuration Changes - -Check the release notes for any changes to configuration file formats or option parameters. While the core options remain consistent, new options may be added in newer versions. - -### New Features - -Recent updates have introduced several new features that enhance the tool's capabilities: -- **GitIngestFormatter**: A new formatter class that generates GitIngest-style digest files containing the full codebase content -- **MethodFilterParser**: A new parser class that handles method-level filtering based on .methodinclude and .methodignore files -- **gitingest option**: A new configuration option that enables generation of GitIngest-style digest files -- **generateDigestFromReport and generateDigestFromContext**: New utility functions that can generate GitIngest digests from existing report files without re-scanning the codebase - -### Dependency Management - -Ensure that required dependencies are properly installed, particularly tiktoken for exact token counting. The tool will fall back to estimation if tiktoken is not available, but with reduced accuracy. - -### Testing - -After upgrading, test the analysis with your typical codebases to ensure expected behavior. Pay particular attention to: -- File inclusion/exclusion patterns -- Token count accuracy -- Export functionality -- Method-level analysis (if used) - -The tool's output format for JSON reports and context exports is designed to be stable, minimizing the impact of upgrades on downstream processes that consume these outputs. - -**Section sources** -- [README.md](file://README.md#L800-L891) -- [index.js](file://index.js#L1-L48) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) \ No newline at end of file diff --git a/docs/content-en/Quick Start Guide.md b/docs/content-en/Quick Start Guide.md deleted file mode 100644 index f4f8d5c..0000000 --- a/docs/content-en/Quick Start Guide.md +++ /dev/null @@ -1,356 +0,0 @@ -# Quick Start Guide - - -**Referenced Files in This Document** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [bin/cli.js](file://bin/cli.js) - - -## Table of Contents -1. [Introduction](#introduction) -2. [Basic Workflow](#basic-workflow) -3. [Running the Tool Interactively](#running-the-tool-interactively) -4. [Understanding the Analysis Output](#understanding-the-analysis-output) -5. [Export Options and Selection](#export-options-and-selection) -6. [Common Usage Patterns](#common-usage-patterns) -7. [Method-Level Analysis](#method-level-analysis) -8. [Clipboard Integration](#clipboard-integration) -9. [Configuration and Pattern Files](#configuration-and-pattern-files) -10. [Troubleshooting Common Issues](#troubleshooting-common-issues) - -## Introduction - -The context-manager CLI tool is designed to optimize LLM context by providing exact token counting, method-level filtering, and intelligent file selection. This quick start guide will help you get up and running with the tool, understand its core functionality, and effectively use its features for AI-assisted development workflows. - -**Section sources** -- [README.md](file://README.md#L0-L891) - -## Basic Workflow - -The context-manager tool follows a simple three-step workflow: analysis, output interpretation, and export selection. The tool analyzes your codebase to calculate exact token counts, presents detailed information about file composition and token distribution, and provides multiple options for exporting the results in formats suitable for LLM consumption. - -The default behavior is interactive, guiding users through the process and prompting for export preferences when no specific export option is specified via command line flags. This ensures users can always choose the most appropriate output format for their current needs. - -```mermaid -flowchart TD -Start([Run context-manager]) --> Analysis["Analyze codebase\nCalculate token counts"] -Analysis --> Output["Display analysis results\nToken statistics, file types,\nlargest files, directories"] -Output --> ExportDecision{"Export option\nspecified?"} -ExportDecision --> |No| InteractiveExport["Prompt user for export choice"] -ExportDecision --> |Yes| DirectExport["Execute specified export"] -InteractiveExport --> SaveReport["Save detailed JSON report"] -InteractiveExport --> ContextFile["Generate LLM context file"] -InteractiveExport --> Clipboard["Copy context to clipboard"] -InteractiveExport --> NoExport["Skip export"] -DirectExport --> SaveReport -DirectExport --> ContextFile -DirectExport --> Clipboard -SaveReport --> End([Complete]) -ContextFile --> End -Clipboard --> End -NoExport --> End -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L793-L813) -- [README.md](file://README.md#L0-L891) - -**Section sources** -- [context-manager.js](file://context-manager.js#L793-L813) -- [README.md](file://README.md#L0-L891) - -## Running the Tool Interactively - -To run the context-manager tool interactively, simply execute the command without any flags: - -```bash -context-manager -``` - -This will initiate the analysis process, scan your project directory while respecting .gitignore rules and any calculator-specific ignore/include patterns, calculate token counts for all relevant files, and display a comprehensive report. After the analysis completes, if no export option was specified, the tool will prompt you to select an export method. - -The interactive mode is ideal for first-time users and those who want to explore different export options based on the analysis results. The tool provides clear guidance throughout the process, making it easy to understand what files were analyzed and how the token counts were calculated. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) - -## Understanding the Analysis Output - -When you run the context-manager tool, it produces a detailed analysis report that includes several key pieces of information. The output begins with metadata about the analysis process, including the project root directory, configuration mode (INCLUDE or EXCLUDE), and token calculation method (exact using tiktoken or estimated). - -The main report includes: -- Total files analyzed and total token count -- Total size in MB and total lines of code -- Average tokens per file -- Number of files ignored by .gitignore and context rules -- Breakdown by file type (extension), showing files, tokens, size, and lines -- Top 5 largest files by token count -- Top 5 largest directories by token count - -Understanding token counts is crucial for LLM context management. The tool uses tiktoken for GPT-4 compatible exact counting when available, falling back to estimation with approximately 95% accuracy if tiktoken is not installed. The verbose output (enabled by default) shows all included files, providing transparency into what contributes to your token count. - -```mermaid -flowchart TD -Start([Analysis Output]) --> Metadata["Metadata Section\nProject path, configuration mode,\ntoken calculation method"] -Metadata --> Summary["Summary Statistics\nTotal files, tokens, size,\nlines, average tokens per file"] -Summary --> IgnoredFiles["Ignored Files Count\n.gitignore exclusions,\ncalculator rule exclusions"] -IgnoredFiles --> FileTypeBreakdown["File Type Breakdown\nExtension, files, tokens,\nsize, lines"] -FileTypeBreakdown --> LargestFiles["Top 5 Largest Files\nBy token count with percentages"] -LargestFiles --> LargestDirectories["Top 5 Largest Directories\nBy token count with percentages"] -LargestDirectories --> Tip["Usage Tip\nSave detailed report option"] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L683-L703) -- [README.md](file://README.md#L0-L891) - -**Section sources** -- [context-manager.js](file://context-manager.js#L683-L703) -- [README.md](file://README.md#L0-L891) - -## Export Options and Selection - -The context-manager tool provides multiple export options to accommodate different use cases. When no export option is specified via command line flags, the tool enters interactive export mode, prompting the user to select from four options: - -1. Save detailed JSON report (token-analysis-report.json) -2. Generate LLM context file (llm-context.json) -3. Copy LLM context to clipboard -4. Skip export - -The interactive export selection ensures that users never miss the opportunity to export their analysis results in the format they need. This feature is particularly helpful for beginners who may not be familiar with all the available export options. - -For automated workflows, you can specify export options directly via command line flags, bypassing the interactive prompt. The available flags are: -- `--save-report` or `-s`: Save a detailed JSON report -- `--context-export`: Generate an LLM context file -- `--context-clipboard`: Copy context directly to clipboard - -```mermaid -stateDiagram-v2 -[*] --> AnalysisComplete -AnalysisComplete --> InteractiveMode : No export flags -AnalysisComplete --> DirectExport : Export flags specified -InteractiveMode --> SaveReport : User selects option 1 -InteractiveMode --> ContextFile : User selects option 2 -InteractiveMode --> Clipboard : User selects option 3 -InteractiveMode --> NoExport : User selects option 4 -DirectExport --> SaveReport : --save-report flag -DirectExport --> ContextFile : --context-export flag -DirectExport --> Clipboard : --context-clipboard flag -SaveReport --> Complete -ContextFile --> Complete -Clipboard --> Complete -NoExport --> Complete -Complete --> [*] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L575-L616) -- [bin/cli.js](file://bin/cli.js#L4-L25) - -**Section sources** -- [context-manager.js](file://context-manager.js#L575-L616) -- [bin/cli.js](file://bin/cli.js#L4-L25) - -## Common Usage Patterns - -The context-manager tool supports several common usage patterns that cater to different development workflows. The most basic pattern is running the tool interactively without any flags, which provides a complete analysis and prompts for export options: - -```bash -context-manager -``` - -For users who want to quickly generate LLM context and copy it to the clipboard, the `--context-clipboard` flag provides a streamlined workflow: - -```bash -context-manager --context-clipboard -``` - -This command analyzes the codebase and copies the optimized context directly to the clipboard in JSON format, ready for pasting into an LLM interface. - -Another common pattern is method-level analysis, which focuses on extracting and analyzing specific methods from JavaScript/TypeScript files rather than entire files: - -```bash -context-manager --method-level -``` - -You can also combine multiple flags to create more complex workflows. For example, to perform method-level analysis and save both a detailed report and export the context to a file: - -```bash -context-manager --method-level --save-report --context-export -``` - -The tool also supports verbose output (enabled by default) which shows all included files, or quiet mode with `--no-verbose` which suppresses the file listing. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) - -## Method-Level Analysis - -Method-level analysis is a powerful feature that allows you to focus on specific methods within your codebase rather than analyzing entire files. This is particularly useful for LLM context optimization, as it enables you to include only the most relevant code sections while excluding boilerplate and utility methods. - -To enable method-level analysis, use the `--method-level` flag: - -```bash -context-manager --method-level -``` - -When method-level analysis is enabled, the tool extracts methods from JavaScript/TypeScript files using pattern matching for function declarations, method assignments, and arrow functions. The analysis includes information about each method's name, line number, and token count. - -The tool supports method filtering through configuration files: -- `.methodinclude`: Include only specified methods (takes priority) -- `.methodignore`: Exclude specified methods - -These files use pattern matching syntax where you can specify exact method names, patterns with wildcards (*), or class.method notation. For example: - -``` -# .methodinclude - include only these methods -calculateTokens -*Handler -*Validator -TokenCalculator.* -``` - -Method-level analysis produces a different output format that organizes context by methods rather than files, making it easier to manage LLM context when you need to focus on specific functionality. - -```mermaid -flowchart TD -Start([Method-Level Analysis]) --> EnableFlag["Use --method-level flag"] -EnableFlag --> MethodExtraction["Extract methods from JS/TS files\nusing regex patterns"] -MethodExtraction --> MethodFiltering["Apply method filtering rules\nfrom .methodinclude/.methodignore"] -MethodFiltering --> TokenCalculation["Calculate tokens for each method"] -TokenCalculation --> ContextGeneration["Generate method-level context\norganized by file path"] -ContextGeneration --> ExportOptions["Export via specified method\nreport, file, or clipboard"] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L118-L223) - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L118-L223) - -## Clipboard Integration - -The context-manager tool provides seamless clipboard integration, allowing you to copy the generated LLM context directly to your system clipboard with the `--context-clipboard` flag: - -```bash -context-manager --context-clipboard -``` - -This feature works across platforms (macOS, Linux, and Windows) using the appropriate system commands (pbcopy, xclip/xsel, or clip). The tool copies the context in JSON format, identical to what would be saved in the llm-context.json file, ensuring consistency between clipboard and file exports. - -The clipboard integration is particularly useful for quickly sharing context with LLMs without having to save and manually copy from a file. The output is optimized for LLM consumption, using a compact format by default that minimizes character count while preserving essential information. - -If the clipboard operation fails (e.g., due to missing system utilities), the tool automatically falls back to saving the context to llm-context.json as a safeguard, ensuring you don't lose the generated context. - -```mermaid -sequenceDiagram -participant User as "User" -participant Tool as "context-manager" -participant System as "Operating System" -participant Clipboard as "System Clipboard" -User->>Tool : Run with --context-clipboard -Tool->>Tool : Analyze codebase and generate context -Tool->>Tool : Format context as JSON -Tool->>System : Execute platform-specific copy command -alt macOS -System->>Clipboard : pbcopy with context string -else Linux -System->>Clipboard : xclip or xsel with context string -else Windows -System->>Clipboard : clip with context string -end -Clipboard-->>Tool : Copy confirmation -alt Copy successful -Tool-->>User : "Context copied to clipboard!" -else Copy failed -Tool->>Tool : Save context to llm-context.json -Tool-->>User : "Failed to copy, saved to file instead" -end -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L541-L567) -- [README.md](file://README.md#L0-L891) - -**Section sources** -- [context-manager.js](file://context-manager.js#L541-L567) -- [README.md](file://README.md#L0-L891) - -## Configuration and Pattern Files - -The context-manager tool uses several configuration files to control which files and methods are included in the analysis. Understanding these files is essential for customizing the tool to your specific needs. - -The primary configuration files for file-level filtering are: -- `.contextinclude`: Include only files matching the specified patterns (takes priority) -- `.contextignore`: Exclude files matching the specified patterns - -The tool follows a priority order for configuration files: -1. `.gitignore` (always respected) -2. `.contextinclude` (highest priority for files) -3. `.contextignore` (used when no include file exists) - -When `.contextinclude` exists, the tool operates in INCLUDE mode, meaning only files matching the include patterns are analyzed (except those excluded by .gitignore). When only `.contextignore` exists, the tool operates in EXCLUDE mode, analyzing all files except those matching the ignore patterns. - -For method-level analysis, the tool uses: -- `.methodinclude`: Include only specified methods -- `.methodignore`: Exclude specified methods - -These files support pattern matching with wildcards (*) and can specify exact method names, patterns, or class.method notation. The syntax is straightforward, with each line representing a pattern and lines starting with # treated as comments. - -```mermaid -graph TB -subgraph "Configuration Priority" -A[".gitignore"] -B[".contextinclude"] -C[".contextignore"] -end -subgraph "Method Filtering" -D[".methodinclude"] -E[".methodignore"] -end -A --> |Always respected| Analysis["Code Analysis"] -B --> |Takes priority| Analysis -C --> |Used if no include file| Analysis -D --> |Method-level include| Analysis -E --> |Method-level exclude| Analysis -style A fill:#f9f,stroke:#333 -style B fill:#f9f,stroke:#333 -style C fill:#f9f,stroke:#333 -style D fill:#bbf,stroke:#333 -style E fill:#bbf,stroke:#333 -style Analysis fill:#9f9,stroke:#333 -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L118-L223) -- [README.md](file://README.md#L0-L891) - -**Section sources** -- [context-manager.js](file://context-manager.js#L118-L223) -- [README.md](file://README.md#L0-L891) - -## Troubleshooting Common Issues - -When getting started with the context-manager tool, you may encounter a few common issues. Understanding these and their solutions will help you use the tool more effectively. - -**Understanding verbose output**: The tool's verbose output (enabled by default) can be overwhelming for beginners. It shows all included files, token counts, and detailed statistics. To reduce output, use the `--no-verbose` flag, though this is not recommended as it reduces transparency about what files are being analyzed. - -**Interpreting token counts**: The tool uses tiktoken for exact token counting when available. If you haven't installed tiktoken, the tool falls back to estimation mode. To ensure exact counts, install tiktoken: -```bash -npm install tiktoken -``` - -**Configuration file issues**: A common source of confusion is the interaction between `.contextinclude` and `.contextignore`. Remember that `.contextinclude` takes priority - if it exists, the tool operates in INCLUDE mode and ignores `.contextignore`. If you're not seeing expected files, check whether a `.contextinclude` file exists. - -**Pattern matching problems**: When creating patterns in configuration files, ensure there are no inline comments and that patterns use the correct syntax. Use `**` for recursive matching and `*` for single-level matching. Test patterns with verbose output to verify they work as expected. - -**Method-level analysis issues**: When using method-level analysis, ensure your `.methodinclude` or `.methodignore` files are in the correct location (project root or tool directory) and use proper pattern syntax. The tool will indicate which mode is active in the output. - -**Section sources** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) \ No newline at end of file diff --git a/docs/content-en/Tool Overview & Core Value.md b/docs/content-en/Tool Overview & Core Value.md deleted file mode 100644 index 62a15ef..0000000 --- a/docs/content-en/Tool Overview & Core Value.md +++ /dev/null @@ -1,403 +0,0 @@ -# Tool Overview & Core Value - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - *Updated in recent commit* -- [bin/cli.js](file://bin/cli.js) - *Updated in recent commit* -- [index.js](file://index.js) - *Updated in recent commit* -- [README.md](file://README.md) - *Updated in recent commit* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in recent commit* - - -## Update Summary -**Changes Made** -- Added comprehensive documentation for the new GitIngest-style digest formatter feature -- Updated architecture section to include the new GitIngestFormatter component -- Enhanced CLI interface section with new GitIngest export options -- Added new section on GitIngest digest generation workflow -- Updated practical use cases to include GitIngest format examples -- Added new sequence diagram showing GitIngest digest generation - -## Table of Contents -1. [Tool Overview & Core Value](#tool-overview--core-value) -2. [Architecture and Component Relationships](#architecture-and-component-relationships) -3. [CLI Interface and Workflow Orchestration](#cli-interface-and-workflow-orchestration) -4. [GitIngest Digest Generation](#gitingest-digest-generation) -5. [Method-Level Analysis and Filtering](#method-level-analysis-and-filtering) -6. [Token Counting and Context Generation](#token-counting-and-context-generation) -7. [Configuration and Filtering Modes](#configuration-and-filtering-modes) -8. [Practical Use Cases and Examples](#practical-use-cases-and-examples) - -## Tool Overview & Core Value - -The context-manager CLI tool is a specialized utility designed for optimizing code context for Large Language Models (LLMs) through precise token counting, method-level filtering, and generating compact context representations. Its primary purpose is to help developers manage LLM context windows efficiently by providing exact token counts and enabling focused analysis of codebases. The tool supports dual filtering modes (include/exclude) and offers multiple output formats, making it ideal for AI-assisted development workflows, codebase analysis, and CI/CD integration. - -The tool's core value lies in its ability to generate ultra-compact context representations that are 89% smaller than full codebases, while maintaining essential information for LLM consumption. It achieves this through method-level analysis, smart file selection, and directory grouping with common prefix compression. The context-manager supports both file-level and method-level analysis, allowing developers to focus on specific business logic methods or analyze entire codebases. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L855) - -## Architecture and Component Relationships - -The context-manager is implemented as a modular, class-based JavaScript application with clear separation of concerns between its core components. The architecture follows a clean dependency hierarchy where specialized classes handle specific aspects of the analysis workflow, and a central orchestrator coordinates their interactions. - -The main components include: -- **TokenCalculator**: The central orchestrator that manages the analysis workflow -- **GitIgnoreParser**: Handles file-level filtering based on .gitignore and custom ignore/include rules -- **MethodAnalyzer**: Extracts methods from JavaScript/TypeScript files using regex patterns -- **MethodFilterParser**: Applies include/exclude rules to filter methods based on configuration files -- **GitIngestFormatter**: Generates GitIngest-style digest files for LLM consumption - -These components work together in a coordinated manner: the GitIgnoreParser determines which files to include in the analysis, the TokenCalculator processes these files and delegates method extraction to the MethodAnalyzer, the MethodFilterParser filters the extracted methods based on configuration rules, and the GitIngestFormatter generates single-file digest outputs. This modular design allows for independent development and testing of each component while maintaining a cohesive analysis workflow. - -```mermaid -classDiagram -class TokenCalculator { -+projectRoot string -+options object -+stats object -+gitIgnore GitIgnoreParser -+methodAnalyzer MethodAnalyzer -+methodFilter MethodFilterParser -+run() void -+scanDirectory(dir) string[] -+analyzeFile(filePath) object -+generateLLMContext(analysisResults) object -+saveGitIngestDigest(analysisResults) void -} -class GitIgnoreParser { -+patterns object[] -+calculatorPatterns object[] -+hasIncludeFile boolean -+isIgnored(filePath, relativePath) boolean -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) void -+parsePatternFile(filePath) object[] -+convertToRegex(pattern) object -} -class MethodAnalyzer { -+extractMethods(content, filePath) object[] -+getLineNumber(content, index) number -+isKeyword(name) boolean -+extractMethodContent(content, methodName) string -} -class MethodFilterParser { -+includePatterns object[] -+ignorePatterns object[] -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -+parseMethodFile(filePath) object[] -} -class GitIngestFormatter { -+projectRoot string -+stats object -+analysisResults object -+methodFilterEnabled boolean -+generateDigest() string -+generateSummary() string -+generateTree() string -+generateFileContents() string -+saveToFile(outputPath) number -} -TokenCalculator --> GitIgnoreParser : "uses" -TokenCalculator --> MethodAnalyzer : "uses" -TokenCalculator --> MethodFilterParser : "uses" -TokenCalculator --> GitIngestFormatter : "creates and uses" -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [context-manager.js](file://context-manager.js#L225-L790) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [context-manager.js](file://context-manager.js#L225-L790) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -## CLI Interface and Workflow Orchestration - -The CLI interface of the context-manager tool serves as the primary entry point for users and orchestrates the entire analysis workflow. Implemented in the bin/cli.js file, the CLI provides a user-friendly interface with various options for controlling the analysis process. The interface follows a clear execution flow: parsing command-line arguments, initializing the TokenAnalyzer with appropriate options, and executing the analysis. - -The CLI supports several key options that control the analysis behavior: -- `--save-report` or `-s`: Saves a detailed JSON report of the analysis -- `--verbose` or `-v`: Shows included files and directories during analysis -- `--context-export`: Generates an LLM context file list -- `--context-clipboard`: Copies the context directly to the clipboard -- `--method-level` or `-m`: Enables method-level analysis -- `--gitingest` or `-g`: Generates GitIngest-style digest file -- `--help` or `-h`: Displays help information - -When no export options are specified, the tool enters interactive mode and prompts the user to choose an export option after completing the analysis. This ensures that users never miss the opportunity to export their analysis results in the desired format. The CLI also handles the initialization of the TokenAnalyzer with the current working directory as the project root and processes the command-line arguments to configure the analysis options. - -```mermaid -sequenceDiagram -participant User as "User" -participant CLI as "CLI Interface" -participant Analyzer as "TokenAnalyzer" -User->>CLI : Execute command (e.g., context-manager --method-level --gitingest) -CLI->>CLI : Parse command-line arguments -CLI->>CLI : Initialize options object -CLI->>Analyzer : Create TokenAnalyzer instance with options -Analyzer->>Analyzer : Scan directory and filter files -Analyzer->>Analyzer : Analyze files and extract methods (if method-level enabled) -Analyzer->>Analyzer : Calculate token counts -Analyzer->>Analyzer : Generate LLM context or GitIngest digest -Analyzer->>CLI : Return analysis results -CLI->>CLI : Export context to file or clipboard -CLI->>User : Display completion message -``` - -**Diagram sources** -- [bin/cli.js](file://bin/cli.js#L1-L67) -- [context-manager.js](file://context-manager.js#L225-L790) - -**Section sources** -- [bin/cli.js](file://bin/cli.js#L1-L67) -- [context-manager.js](file://context-manager.js#L225-L790) - -## GitIngest Digest Generation - -The context-manager tool now supports generating GitIngest-style digest files - a single, prompt-friendly text file perfect for LLM consumption. This feature was implemented to provide an alternative format that consolidates the entire codebase into a single file with a clear directory tree structure and complete file contents. - -The GitIngestFormatter class is responsible for creating these digest files. It takes the analysis results from the TokenCalculator and formats them into a structured text file that includes: -- Project summary and statistics -- Visual directory tree structure using ASCII art -- Complete file contents with clear separators -- Token count estimates formatted in a human-readable way (e.g., "1.2k") - -The digest generation process respects all filtering rules, including .gitignore and calculator ignore/include rules. When method-level analysis is enabled, the formatter applies method filtering to include only the specified methods in each file, making the digest even more focused and relevant. - -The GitIngest digest can be generated in several ways: -1. Directly from a full analysis: `context-manager --gitingest` -2. From an existing JSON report: `context-manager --gitingest-from-report token-analysis-report.json` -3. From an existing LLM context file: `context-manager --gitingest-from-context llm-context.json` - -This two-step workflow allows for performance optimization, as the digest can be generated instantly from existing JSON files without re-scanning the entire codebase. - -```mermaid -sequenceDiagram -participant User as "User" -participant CLI as "CLI Interface" -participant Analyzer as "TokenAnalyzer" -participant Formatter as "GitIngestFormatter" -User->>CLI : Execute command (e.g., context-manager --gitingest) -CLI->>CLI : Parse command-line arguments -CLI->>Analyzer : Create TokenAnalyzer instance -Analyzer->>Analyzer : Scan and analyze codebase -Analyzer->>Analyzer : Collect analysis results -Analyzer->>Formatter : Create GitIngestFormatter with results -Formatter->>Formatter : Generate digest content -Formatter->>Formatter : Save digest to digest.txt -Formatter->>Analyzer : Return digest size -Analyzer->>CLI : Report completion -CLI->>User : Display success message with digest size -``` - -**Diagram sources** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L332-L339) - -**Section sources** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L332-L339) -- [README.md](file://README.md#L600-L700) - -## Method-Level Analysis and Filtering - -The context-manager tool provides sophisticated method-level analysis capabilities that allow developers to focus on specific methods within their codebase. This feature is particularly valuable for LLM context optimization, as it enables the extraction of only the most relevant business logic methods while excluding utility, test, and debug methods. - -Method-level analysis is controlled by the `--method-level` flag and is implemented through two key components: the MethodAnalyzer and MethodFilterParser classes. The MethodAnalyzer uses a series of regular expressions to identify methods in JavaScript/TypeScript files, supporting various syntax patterns including function declarations, object methods, arrow functions, and class methods. It extracts method names, line numbers, and file paths, creating a comprehensive inventory of methods in the codebase. - -The MethodFilterParser applies include/exclude rules to filter methods based on configuration files (.methodinclude and .methodignore). These files use pattern matching syntax that supports exact matches, wildcards (*pattern*), class-specific methods (Class.*), and file-specific methods (file.method). The filtering system supports both include mode (only specified methods are included) and exclude mode (specified methods are excluded), with include mode taking priority when both configuration files exist. - -```mermaid -flowchart TD -Start([Start Method-Level Analysis]) --> ExtractMethods["Extract Methods from Files"] -ExtractMethods --> HasFilter{"Method Filter Active?"} -HasFilter --> |Yes| ApplyFilter["Apply Include/Exclude Rules"] -HasFilter --> |No| IncludeAll["Include All Methods"] -ApplyFilter --> FilterMode{"Include Mode?"} -FilterMode --> |Yes| CheckInclude["Check Against .methodinclude"] -FilterMode --> |No| CheckExclude["Check Against .methodignore"] -CheckInclude --> IncludeResult{"Match Found?"} -CheckExclude --> ExcludeResult{"Match Found?"} -IncludeResult --> |Yes| IncludeMethod["Include Method"] -IncludeResult --> |No| ExcludeMethod["Exclude Method"] -ExcludeResult --> |Yes| ExcludeMethod -ExcludeResult --> |No| IncludeMethod -IncludeMethod --> CalculateTokens["Calculate Method Token Count"] -ExcludeMethod --> NextMethod["Process Next Method"] -CalculateTokens --> StoreResults["Store Method Information"] -StoreResults --> NextMethod -NextMethod --> MoreMethods{"More Methods?"} -MoreMethods --> |Yes| ExtractMethods -MoreMethods --> |No| GenerateContext["Generate LLM Context"] -GenerateContext --> End([End Analysis]) -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) - -**Section sources** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) -- [README.md](file://README.md#L499-L542) - -## Token Counting and Context Generation - -The context-manager tool provides accurate token counting capabilities essential for LLM context optimization. It uses the tiktoken library for exact token counting compatible with GPT-4, falling back to smart estimation when tiktoken is not available. The token counting system is designed to provide ~95% accuracy even without the tiktoken dependency, making it accessible for various development environments. - -The token counting process involves reading file content, calculating tokens based on character-to-token ratios specific to file extensions, and aggregating statistics across the codebase. For exact counting, the tool uses the cl100k_base encoding from tiktoken, which is the same encoding used by GPT-4, ensuring precise context window management. The estimation system uses predefined character-per-token ratios for different file types (e.g., 3.2 for JavaScript, 4.0 for Markdown) to provide reliable approximations. - -Context generation is a key feature that produces optimized file lists for LLM consumption in two formats: ultra-compact (default) and detailed. The ultra-compact format generates a structured JSON representation of ~2.3k characters that includes project metadata and organized file paths without token counts, while the detailed format produces ~8.6k characters of comprehensive information including full paths, categories, importance scores, and directory statistics. Both formats use identical JSON structures, ensuring consistency between clipboard and file exports. - -```mermaid -flowchart LR -A[Read File Content] --> B{tiktoken Available?} -B --> |Yes| C[Use cl100k_base Encoding] -B --> |No| D[Use Smart Estimation] -C --> E[Calculate Exact Token Count] -D --> F[Apply Extension-Specific Ratios] -F --> G[Estimate Token Count] -E --> H[Aggregate Statistics] -G --> H -H --> I{Method-Level Analysis?} -I --> |Yes| J[Extract and Filter Methods] -I --> |No| K[Process Files Only] -J --> L[Calculate Method Token Counts] -L --> M[Generate Method Context] -K --> N[Generate File Context] -M --> O[Create LLM Context] -N --> O -O --> P[Export to Clipboard or File] -``` - -**Diagram sources** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L639-L665) - -**Section sources** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L639-L665) -- [README.md](file://README.md#L499-L542) - -## Configuration and Filtering Modes - -The context-manager tool supports a flexible configuration system with dual filtering modes (include/exclude) that provide precise control over which files and methods are included in the analysis. This system allows developers to create focused analysis sets tailored to their specific needs, whether they want to analyze only core application logic or include specific files and directories. - -The file-level filtering system uses three configuration files with a clear priority hierarchy: -1. `.gitignore` (project root) - Standard git exclusions (always respected) -2. `.contextinclude` - INCLUDE mode (highest priority for files) -3. `.contextignore` - EXCLUDE mode (used when no include file exists) - -When `.contextinclude` exists, the tool operates in INCLUDE mode, including only files that match the patterns in this file and ignoring `.contextignore`. When only `.contextignore` exists, the tool operates in EXCLUDE mode, including all files except those matching the ignore patterns. This dual-mode system provides flexibility for different use cases, from comprehensive codebase analysis to focused examination of specific components. - -Method-level filtering follows a similar pattern with `.methodinclude` and `.methodignore` files that control which methods are included in the analysis. These files support pattern matching syntax including exact matches, wildcards (*pattern*), class-specific methods (Class.*), and file-specific methods (file.method). The pattern syntax also supports negation (!pattern) to exclude specific items from broad patterns. - -```mermaid -graph TD -A[Start Analysis] --> B{.contextinclude Exists?} -B --> |Yes| C[INCLUDE Mode] -B --> |No| D{.contextignore Exists?} -D --> |Yes| E[EXCLUDE Mode] -D --> |No| F[Include All Files] -C --> G[Load .contextinclude Patterns] -E --> H[Load .contextignore Patterns] -G --> I[Include Only Matching Files] -H --> J[Exclude Matching Files] -I --> K[Apply .gitignore Rules] -J --> K -K --> L{Method-Level Analysis?} -L --> |Yes| M{.methodinclude Exists?} -M --> |Yes| N[INCLUDE Mode for Methods] -M --> |No| O{.methodignore Exists?} -O --> |Yes| P[EXCLUDE Mode for Methods] -O --> |No| Q[Include All Methods] -N --> R[Include Only Matching Methods] -P --> S[Exclude Matching Methods] -R --> T[Generate Context] -S --> T -Q --> T -T --> U[Export Results] -``` - -**Diagram sources** -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L253-L286) - -**Section sources** -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L253-L286) - -## Practical Use Cases and Examples - -The context-manager tool supports a wide range of practical use cases that enhance AI-assisted development workflows. These use cases demonstrate the tool's versatility in optimizing LLM context, analyzing codebases, and integrating with development processes. - -For LLM context optimization, developers can generate minimal context for AI assistants using commands like `context-manager --method-level --context-clipboard`. This creates an ultra-compact representation of the codebase that focuses on core business logic methods, reducing context size by up to 89% compared to the full codebase. By creating a `.methodinclude` file with patterns like `*Handler`, `*Validator`, and `*Manager`, developers can ensure that only relevant methods are included in the context. - -Codebase analysis is another key use case, where the tool helps understand project complexity and structure. Running `context-manager --save-report --verbose` generates a detailed JSON report that can be used for historical tracking and CI/CD integration. This report includes comprehensive statistics on file types, largest files, and directory composition, providing valuable insights into codebase health and organization. - -The tool also supports method-level debugging by allowing developers to focus on specific problematic methods. For example, to debug authentication methods, a developer can create a `.methodinclude` file with patterns like `*auth*`, `*login*`, and `*validate*`, then run `context-manager --method-level --context-clipboard`. This isolates the relevant methods and provides a focused context for debugging. - -CI/CD integration is facilitated through automated token analysis for monitoring codebase growth and complexity. Scripts can run `context-manager --save-report` daily to track token counts and detect potential issues before they impact LLM context limits. Code quality gates can be implemented by checking if the codebase exceeds token budgets, ensuring that projects remain within manageable limits for AI-assisted development. - -A new use case enabled by the GitIngest formatter is creating single-file digests for LLM consumption. Developers can run `context-manager --gitingest` to generate a `digest.txt` file that contains the entire codebase in a structured format perfect for pasting into LLM prompts. This is particularly useful for code reviews, documentation generation, and AI analysis workflows. - -```mermaid -erDiagram -USER_REQUIREMENT { -string useCase PK -string description -string command -string configuration -string outputFormat -} -USER_REQUIREMENT ||--o{ CONFIG_FILE : "uses" -USER_REQUIREMENT ||--o{ OUTPUT_FORMAT : "produces" -CONFIG_FILE { -string filename PK -string patternSyntax -string mode -} -OUTPUT_FORMAT { -string formatType PK -string size -string content -string useCase -} -USER_REQUIREMENT { -"LLM Context Optimization" "Generate minimal context for AI assistants" "context-manager --method-level --context-clipboard" ".methodinclude with *Handler, *Validator" "Ultra-compact JSON (~2.3k chars)" -"Codebase Analysis" "Understand project complexity and structure" "context-manager --save-report --verbose" ".contextinclude with core JS files" "Detailed JSON report (~8.6k chars)" -"Method-Level Debugging" "Focus on specific problematic methods" "context-manager --method-level --verbose" ".methodinclude with *auth*, *login*" "Method context with line numbers" -"CI/CD Integration" "Monitor codebase growth and complexity" "context-manager --save-report" ".contextignore with test/ and docs/" "Detailed analysis for historical tracking" -"Code Quality Gates" "Ensure code stays within token budgets" "context-manager --method-level --save-report" ".methodinclude with core business logic" "Token count validation" -"GitIngest Digest" "Create single-file digest for LLM consumption" "context-manager --gitingest" ".methodinclude with core methods" "Single-file text digest (~10-50KB)" -} -CONFIG_FILE { -".contextinclude" "**/*.js, !test/**, !docs/**" "INCLUDE" -".contextignore" "**/*.md, **/*.json, node_modules/**" "EXCLUDE" -".methodinclude" "*Handler, *Validator, *Manager" "INCLUDE" -".methodignore" "*test*, *debug*, console" "EXCLUDE" -} -OUTPUT_FORMAT { -"Ultra-compact JSON" "~2.3k chars" "Project metadata, organized file paths" "LLM context optimization" -"Detailed JSON" "~8.6k chars" "Full paths, categories, importance scores" "Codebase analysis" -"Method context" "~4.5k chars" "Method names, line numbers, token counts" "Method-level debugging" -"Detailed report" "~12k chars" "Comprehensive statistics, largest files" "CI/CD integration" -"GitIngest digest" "~10-50KB" "Directory tree, file contents" "LLM consumption, code reviews" -} -``` - -**Diagram sources** -- [README.md](file://README.md#L499-L542) -- [README.md](file://README.md#L801-L879) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -**Section sources** -- [README.md](file://README.md#L499-L542) -- [README.md](file://README.md#L801-L879) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) \ No newline at end of file diff --git a/docs/content-en/Troubleshooting.md b/docs/content-en/Troubleshooting.md deleted file mode 100644 index d124113..0000000 --- a/docs/content-en/Troubleshooting.md +++ /dev/null @@ -1,186 +0,0 @@ -# Troubleshooting - - -**Referenced Files in This Document** -- [context-manager.js](file://context-manager.js) - *Updated in commit 6f5fea32* -- [README.md](file://README.md) - *Updated in commit 6f5fea32* -- [bin/cli.js](file://bin/cli.js) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Added in commit 6f5fea32* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Added in commit 6f5fea32* - - -## Table of Contents -1. [Include/Exclude Mode Confusion](#includeexclude-mode-confusion) -2. [Pattern Matching Issues](#pattern-matching-issues) -3. [Token Counting Discrepancies](#token-counting-discrepancies) -4. [Missing Files in Analysis](#missing-files-in-analysis) -5. [Unexpected File Inclusions](#unexpected-file-inclusions) -6. [Performance Issues with Large Codebases](#performance-issues-with-large-codebases) -7. [Diagnostic Steps](#diagnostic-steps) -8. [Common Environment Issues](#common-environment-issues) -9. [GitIngest Digest Generation Issues](#gitingest-digest-generation-issues) -10. [Method-Level Filtering Problems](#method-level-filtering-problems) - -## Include/Exclude Mode Confusion - -The context-manager tool uses a priority-based system for file inclusion and exclusion. The presence of a `.contextinclude` file takes precedence over `.contextignore`, which can lead to confusion when users expect files to be included but they're excluded. - -When `.contextinclude` exists, the tool operates in INCLUDE mode, meaning only files matching the patterns in this file will be included in the analysis. This overrides any `.contextignore` rules. Users might expect files to be included based on their `.contextignore` configuration, but if a `.contextinclude` file exists, those expectations will not be met. - -The tool clearly indicates which mode is active during execution. In INCLUDE mode, it displays "📅 Found calculator config - using INCLUDE mode", while in EXCLUDE mode it shows "📅 Found calculator config - using EXCLUDE mode". This visual cue helps identify the current filtering mode. - -**Section sources** -- [context-manager.js](file://context-manager.js#L134-L157) -- [context-manager.js](file://context-manager.js#L181-L217) -- [README.md](file://README.md#L121-L150) - -## Pattern Matching Issues - -Pattern matching in the context-manager tool follows specific syntax rules that users must understand to configure their `.contextignore` and `.methodinclude` files correctly. Common issues include incorrect syntax, missing negation patterns, and misunderstanding of wildcard behavior. - -The tool converts patterns to regular expressions for matching, with specific transformations: -- `**` becomes `.*` (matches any number of directories) -- `*` becomes `[^/]*` (matches any characters except directory separators) -- `?` becomes `[^/]` (matches any single character except directory separators) - -Negation patterns (prefixed with `!`) work differently in INCLUDE versus EXCLUDE modes. In INCLUDE mode, negation patterns exclude files from the included set, while in EXCLUDE mode, they re-include files that would otherwise be excluded. A common mistake is placing negation patterns in the wrong order, as the tool processes patterns sequentially. - -**Section sources** -- [context-manager.js](file://context-manager.js#L159-L179) -- [context-manager.js](file://context-manager.js#L219-L257) -- [README.md](file://README.md#L544-L610) - -## Token Counting Discrepancies - -The context-manager tool provides both exact and estimated token counts, which can lead to discrepancies that users might find confusing. The tool first attempts to use the tiktoken library for exact GPT-4 compatible token counting. If tiktoken is not available, it falls back to an estimation algorithm. - -The estimation algorithm uses predefined characters-per-token ratios for different file types: -- JavaScript/TypeScript: 3.2 characters per token -- JSON: 2.5 characters per token -- Markdown: 4.0 characters per token -- HTML/XML: 2.8 characters per token -- Default: 3.5 characters per token - -These estimates are typically around 95% accurate compared to exact counts. Users might notice differences between the estimated counts and what they expect from other tools. The tool clearly indicates which counting method is being used in the output: "🎯 Token calculation: ✅ Exact (using tiktoken)" for exact counts or "🎯 Token calculation: ⚠️ Estimated" for estimates. - -**Section sources** -- [context-manager.js](file://context-manager.js#L259-L292) -- [context-manager.js](file://context-manager.js#L385-L400) -- [README.md](file://README.md#L801-L879) - -## Missing Files in Analysis - -Files may be missing from analysis due to the multi-layered filtering system. The tool respects three levels of configuration files in order of priority: -1. `.gitignore` (always respected) -2. `.contextinclude` (highest priority for inclusion) -3. `.contextignore` (used when no include file exists) - -A file might be missing from analysis if it's excluded by any of these mechanisms. Even if a file is not explicitly mentioned in `.contextignore`, it might be excluded by a pattern like `**/*.md` or `node_modules/**`. Users should check all three configuration files to understand why a file is missing. - -Additionally, the tool only analyzes text files, determined by file extension and basename. Files with extensions not in the recognized text extensions list or basenames not in the text files list will be skipped entirely, even if they're not explicitly ignored. - -**Section sources** -- [context-manager.js](file://context-manager.js#L181-L217) -- [context-manager.js](file://context-manager.js#L414-L453) -- [README.md](file://README.md#L294-L356) - -## Unexpected File Inclusions - -Unexpected file inclusions can occur when users misunderstand the interaction between different configuration files. The most common cause is the presence of a `.contextinclude` file when the user expects EXCLUDE mode behavior. In INCLUDE mode, only files matching the patterns in `.contextinclude` are included, which might include files the user expected to be excluded. - -Another cause is the use of broad patterns like `**/*.js` without proper negation. For example, if a user wants to include all JavaScript files except those in test directories, they need to explicitly add a negation pattern like `!**/*.test.js` or `!test/**`. - -The tool's verbose output can help identify why files are being included. When running with the `--verbose` flag, the tool shows which mode is active and can help trace the inclusion logic. - -**Section sources** -- [context-manager.js](file://context-manager.js#L134-L157) -- [context-manager.js](file://context-manager.js#L181-L217) -- [README.md](file://README.md#L544-L610) - -## Performance Issues with Large Codebases - -Performance issues with large codebases typically stem from the tool needing to scan and analyze every file in the project directory. The scanning process recursively traverses directories, which can be slow for deeply nested structures with many files. - -The tool automatically skips certain directories like `node_modules`, `.git`, `dist`, and `build` to improve performance. However, if a codebase has many files in analyzable categories (JavaScript, TypeScript, Markdown, etc.), the analysis can still be time-consuming. - -Method-level analysis (`--method-level` flag) significantly increases processing time as the tool needs to parse each file to extract method definitions and calculate tokens for each method individually. For very large codebases, this can result in noticeable delays. - -**Section sources** -- [context-manager.js](file://context-manager.js#L455-L485) -- [context-manager.js](file://context-manager.js#L521-L545) -- [bin/cli.js](file://bin/cli.js#L20-L35) - -## Diagnostic Steps - -To diagnose issues with the context-manager tool, users should follow these steps: - -1. Run the tool with the `--verbose` flag to see detailed output about which files are being processed and which rules are being applied. - -2. Check the initial output to determine which mode is active (INCLUDE or EXCLUDE) and which configuration file is being used. - -3. Use the `--save-report` option to generate a detailed JSON report that includes information about all processed files, their token counts, and which rules were applied. - -4. Examine the configuration files (`.gitignore`, `.contextignore`, `.contextinclude`) for conflicting or incorrect patterns. - -5. Verify that the tiktoken dependency is installed if exact token counts are required. - -The tool provides clear visual indicators in its output that help with diagnosis, such as the number of files ignored due to `.gitignore` rules versus context rules, and whether exact or estimated token counting is being used. - -**Section sources** -- [context-manager.js](file://context-manager.js#L609-L643) -- [context-manager.js](file://context-manager.js#L715-L743) -- [bin/cli.js](file://bin/cli.js#L41-L66) - -## Common Environment Issues - -Common environment issues include missing dependencies and permission errors. The most frequent dependency issue is the absence of the tiktoken library, which is required for exact token counting. When tiktoken is not installed, the tool automatically falls back to estimation mode, but users should install it via `npm install tiktoken` for accurate results. - -Permission errors can occur when the tool doesn't have read access to certain files or directories in the codebase. This might happen when running the tool in restricted environments or when file permissions are set too narrowly. Users should ensure the tool has appropriate read permissions for all files they want to analyze. - -Another common issue is running the tool from the wrong directory. The tool analyzes the current working directory by default, so users must ensure they're in the correct project root when executing the command. - -**Section sources** -- [context-manager.js](file://context-manager.js#L259-L292) -- [context-manager.js](file://context-manager.js#L825-L840) -- [README.md](file://README.md#L294-L356) - -## GitIngest Digest Generation Issues - -With the implementation of GitIngest-style digest formatting, new issues may arise related to digest generation. The `--gitingest` flag generates a single-file digest for LLM consumption, but users may encounter problems with this feature. - -Common issues include: -- Missing digest.txt output when using `--gitingest` flag -- Incorrect token estimates in the generated digest -- Directory tree structure not reflecting actual project structure -- File contents missing from the digest output - -The GitIngestFormatter automatically detects and applies method-level filtering when `.methodinclude` or `.methodignore` files exist. If method filtering is active, the digest will include a note indicating whether INCLUDE or EXCLUDE mode is active for methods. - -When generating digests from existing JSON reports using `--gitingest-from-report` or `--gitingest-from-context`, ensure the specified JSON file exists and has the correct structure. The tool will display an error message if the file is not found or has invalid format. - -**Section sources** -- [context-manager.js](file://context-manager.js#L294-L382) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L1-L269) -- [README.md](file://README.md#L100-L150) - -## Method-Level Filtering Problems - -Method-level filtering allows users to include or exclude specific methods from analysis using `.methodinclude` and `.methodignore` files. Issues may arise when these files are not properly configured. - -The MethodFilterParser processes these files and converts patterns to regular expressions. Patterns support wildcards (`*`) which are converted to `.*` in regex. Patterns are case-insensitive and can match method names or file.method combinations. - -Common problems include: -- Patterns not matching expected methods due to incorrect syntax -- Negation patterns not working as expected -- Method filtering not being applied when expected - -The tool logs messages when method filter rules are loaded: -- "🔧 Method include rules loaded: X patterns" when `.methodinclude` is detected -- "🚫 Method ignore rules loaded: X patterns" when `.methodignore` is detected - -Method filtering is automatically detected and applied by the GitIngestFormatter when generating digests, ensuring consistent behavior between regular analysis and digest generation. - -**Section sources** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L1-L51) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L15-L25) -- [README.md](file://README.md#L200-L250) \ No newline at end of file diff --git a/docs/content-en/Use Cases.md b/docs/content-en/Use Cases.md deleted file mode 100644 index 18d6f61..0000000 --- a/docs/content-en/Use Cases.md +++ /dev/null @@ -1,98 +0,0 @@ -# Use Cases - - -**Referenced Files in This Document** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) - - -## Table of Contents -1. [LLM Context Optimization](#llm-context-optimization) -2. [Codebase Analysis](#codebase-analysis) -3. [CI/CD Integration](#cicd-integration) -4. [Common Challenges and Solutions](#common-challenges-and-solutions) -5. [Best Practices and Performance Considerations](#best-practices-and-performance-considerations) - -## LLM Context Optimization - -The context-manager tool enables efficient management of token budgets for AI assistants by generating focused context files and filtering out non-essential code. It supports two primary modes of operation: EXCLUDE mode (via `.contextignore`) and INCLUDE mode (via `.contextinclude`), with the latter taking precedence. This dual filtering system ensures precise control over which files are included in the analysis, allowing developers to focus exclusively on core application logic. - -For LLM context export, the tool provides two formats: an ultra-compact format (~2.3k characters) and a detailed format (~8.6k characters). The compact format generates structured JSON output ideal for programmatic processing and AI consumption, while the detailed format includes additional metadata such as file categories and importance scores. When using the `--context-clipboard` or `--context-export` options, the tool outputs a clean directory structure without token counts, making it suitable for frequent AI interactions. - -Method-level filtering further enhances context optimization through `.methodinclude` and `.methodignore` configuration files. These allow developers to include or exclude specific methods based on naming patterns, enabling highly targeted analysis. For example, specifying `*Handler`, `*Validator`, or `TokenCalculator.*` in `.methodinclude` focuses the context on critical business logic components. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## Codebase Analysis - -The context-manager tool provides comprehensive insights into token distribution across the codebase, identifying large files and methods while tracking complexity over time. Using exact token counting via tiktoken (GPT-4 compatible), it delivers accurate metrics that help maintain optimal code health. In the absence of tiktoken, the tool falls back to smart estimation with ~95% accuracy. - -Key analytical features include: -- **Token distribution by file type**: Detailed breakdown of tokens per extension -- **Largest files identification**: Top 5 largest files ranked by token count -- **Directory-level statistics**: Token usage aggregated by top-level directories -- **Method-level analysis**: Extraction and analysis of individual methods from JavaScript/TypeScript files - -The tool generates a detailed report showing total files analyzed, total tokens, average tokens per file, and files ignored due to `.gitignore` or context rules. This information is crucial for understanding project complexity and identifying potential refactoring opportunities. The `--save-report` option exports this data to `token-analysis-report.json`, enabling historical tracking and trend analysis. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## CI/CD Integration - -The context-manager tool can be seamlessly integrated into CI/CD pipelines for automated code size monitoring, quality gates, and documentation generation. Its command-line interface supports non-interactive execution, making it suitable for use in pre-commit hooks, daily monitoring scripts, and continuous integration workflows. - -Common integration patterns include: -- **Pre-commit hooks**: Running `context-manager --context-clipboard` before commits to ensure only essential code is considered for AI review -- **Daily monitoring scripts**: Executing `context-manager --save-report` to generate daily analysis reports for trend tracking -- **Quality gates**: Implementing token budget checks in pipelines using scriptable output (e.g., parsing JSON output to enforce maximum token limits) -- **Automated documentation**: Generating up-to-date context files that reflect current codebase structure - -The interactive export selection feature prompts users to choose between saving a detailed JSON report, generating an LLM context file, copying context to clipboard, or skipping export—ensuring flexibility in different usage scenarios. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [bin/cli.js](file://bin/cli.js#L1-L67) - -## Common Challenges and Solutions - -Several common challenges arise when using the context-manager tool, particularly around configuration and filtering behavior: - -**Include vs Exclude Mode Confusion**: The presence of `.contextinclude` takes priority over `.contextignore`. If unexpected files are being included or excluded, verify which configuration file exists and remove the unwanted one. - -**Pattern Matching Issues**: Ensure no inline comments exist in pattern files, as they can interfere with parsing. Use proper glob patterns (`docs/**` instead of `docs/`) and test configurations with verbose mode to see inclusion/exclusion reasons. - -**Token Count Discrepancies**: If token counts appear too high or low, check whether important files are being excluded by `.gitignore` or context rules. Use `--verbose` to inspect which files are being processed. - -**Missing Expected Files**: Files may be excluded due to `.gitignore` rules (always respected) or incorrect pattern syntax. Verify that files are recognized as text files and use verbose mode to determine exclusion reasons. - -**Clipboard Functionality Failures**: On Linux systems, ensure either `xclip` or `xsel` is installed for clipboard operations. The tool automatically attempts both utilities if one fails. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## Best Practices and Performance Considerations - -To maximize effectiveness when using the context-manager tool, follow these best practices: - -**Configuration Management**: Use `.contextinclude` for precise control over analysis scope, especially in large repositories. Keep patterns simple and test them incrementally. - -**Performance Optimization**: The tool is optimized for performance, but analyzing very large codebases may benefit from method-level filtering to reduce processing overhead. Enable method-level analysis only when necessary. - -**Exact Token Counting**: Install the `tiktoken` package (`npm install tiktoken`) for GPT-4 compatible exact token counting. Without it, the tool uses estimation with ~95% accuracy. - -**Regular Monitoring**: Integrate the tool into regular development workflows through pre-commit hooks or scheduled scripts to maintain awareness of codebase growth and complexity trends. - -**Output Utilization**: Leverage both compact and detailed output formats appropriately—use compact JSON for AI interactions and detailed reports for architectural planning and onboarding. - -**Method-Level Filtering**: Use `.methodinclude` and `.methodignore` files to focus on core business logic during debugging or code reviews, reducing cognitive load and improving analysis relevance. - -**Section sources** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) \ No newline at end of file diff --git a/docs/content-tr/Arac-Genel-Bakis-ve-Temel-Deger.md b/docs/content-tr/Arac-Genel-Bakis-ve-Temel-Deger.md deleted file mode 100644 index 6bc0043..0000000 --- a/docs/content-tr/Arac-Genel-Bakis-ve-Temel-Deger.md +++ /dev/null @@ -1,390 +0,0 @@ -# Araç Genel Bakış ve Temel Değer - - -**Bu Belgede Referans Verilen Dosyalar** -- [context-manager.js](file://context-manager.js) - *Son commit'te güncellendi* -- [bin/cli.js](file://bin/cli.js) - *Son commit'te güncellendi* -- [index.js](file://index.js) - *Son commit'te güncellendi* -- [README.md](file://README.md) - *Son commit'te güncellendi* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Son commit'te eklendi* - - -## Güncelleme Özeti -**Yapılan Değişiklikler** -- Yeni GitIngest formatı digest üretici özelliği için kapsamlı dokümantasyon eklendi -- Mimari bölümü yeni GitIngestFormatter bileşeni ile güncellendi -- CLI arayüzü bölümü yeni GitIngest export seçenekleri ile geliştirildi -- GitIngest digest üretim iş akışı için yeni bölüm eklendi -- Pratik kullanım senaryoları GitIngest format örneklerini içerecek şekilde güncellendi -- Yeni formatter ve parser dosyalarını içerecek şekilde sequence diyagramı eklendi - -## İçindekiler -1. [Araç Genel Bakış ve Temel Değer](#arac-genel-bakis-ve-temel-deger) -2. [Mimari ve Bileşen İlişkileri](#mimari-ve-bilesen-iliskileri) -3. [CLI Arayüzü ve İş Akışı Düzenlemesi](#cli-arayuzu-ve-is-akisi-duzenlemesi) -4. [GitIngest Digest Üretimi](#gitingest-digest-uretimi) -5. [Metod Seviyesi Analiz ve Filtreleme](#metod-seviyesi-analiz-ve-filtreleme) -6. [Token Sayımı ve Context Oluşturma](#token-sayimi-ve-context-olusturma) -7. [Yapılandırma ve Filtreleme Modları](#yapilandirma-ve-filtreleme-modlari) -8. [Pratik Kullanım Örnekleri](#pratik-kullanim-ornekleri) - -## Araç Genel Bakış ve Temel Değer - -context-manager CLI aracı, hassas token sayımı, metod seviyesi filtreleme ve compact context temsilleri oluşturma yoluyla Large Language Model'ler (LLM'ler) için kod context'ini optimize etmek üzere tasarlanmış özel bir yardımcı programdır. Birincil amacı, geliştiricilerin kesin token sayıları sağlayarak ve kod tabanlarının odaklanmış analizini mümkün kılarak LLM context pencerelerini verimli bir şekilde yönetmelerine yardımcı olmaktır. Araç, dual filtreleme modlarını (include/exclude) destekler ve birden fazla çıktı formatı sunar, bu da onu AI destekli geliştirme iş akışları, kod tabanı analizi ve CI/CD entegrasyonu için ideal hale getirir. - -Aracın temel değeri, temel bilgileri LLM tüketimi için korurken tam kod tabanlarından %89 daha küçük ultra-compact context temsilleri oluşturma yeteneğinde yatmaktadır. Bunu metod seviyesi analiz, akıllı dosya seçimi ve ortak önek sıkıştırması ile dizin gruplandırması yoluyla başarır. context-manager, geliştiricilerin belirli iş mantığı metodlarına odaklanmalarına veya tüm kod tabanlarını analiz etmelerine olanak tanıyan hem dosya seviyesi hem de metod seviyesi analizini destekler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L855) - -## Mimari ve Bileşen İlişkileri - -context-manager, modüler, sınıf tabanlı bir JavaScript uygulaması olarak uygulanmıştır ve temel bileşenleri arasında net bir endişe ayrımı vardır. Mimari, özelleşmiş sınıfların analiz iş akışının belirli yönlerini ele aldığı ve merkezi bir orkestratörün etkileşimlerini koordine ettiği temiz bir bağımlılık hiyerarşisini takip eder. - -Ana bileşenler şunları içerir: -- **TokenCalculator**: Analiz iş akışını yöneten merkezi orkestratör -- **GitIgnoreParser**: .gitignore ve özel ignore/include kurallarına dayalı dosya seviyesi filtrelemeyi yönetir -- **MethodAnalyzer**: Regex desenleri kullanarak JavaScript/TypeScript dosyalarından metodları çıkarır -- **MethodFilterParser**: Yapılandırma dosyalarına dayalı metodları filtrelemek için include/exclude kuralları uygular -- **GitIngestFormatter**: GitIngest-style digest dosyaları oluşturur - -Bu bileşenler koordineli bir şekilde birlikte çalışır: GitIgnoreParser analize hangi dosyaların dahil edileceğini belirler, TokenCalculator bu dosyaları işler ve metod çıkarmayı MethodAnalyzer'a devreder, ve MethodFilterParser yapılandırma kurallarına göre çıkarılan metodları filtreler. Bu modüler tasarım, tutarlı bir analiz iş akışını sürdürürken her bileşenin bağımsız geliştirme ve testine olanak tanır. - -```mermaid -classDiagram -class TokenCalculator { -+projectRoot string -+options object -+stats object -+gitIgnore GitIgnoreParser -+methodAnalyzer MethodAnalyzer -+methodFilter MethodFilterParser -+run() void -+scanDirectory(dir) string[] -+analyzeFile(filePath) object -+generateLLMContext(analysisResults) object -} -class GitIgnoreParser { -+patterns object[] -+calculatorPatterns object[] -+hasIncludeFile boolean -+isIgnored(filePath, relativePath) boolean -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) void -+parsePatternFile(filePath) object[] -+convertToRegex(pattern) object -} -class MethodAnalyzer { -+extractMethods(content, filePath) object[] -+getLineNumber(content, index) number -+isKeyword(name) boolean -+extractMethodContent(content, methodName) string -} -class MethodFilterParser { -+includePatterns object[] -+ignorePatterns object[] -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -+parseMethodFile(filePath) object[] -} -TokenCalculator --> GitIgnoreParser : "uses" -TokenCalculator --> MethodAnalyzer : "uses" -TokenCalculator --> MethodFilterParser : "uses" -TokenCalculator --> TokenCalculator : "coordinates workflow" -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [context-manager.js](file://context-manager.js#L225-L790) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [context-manager.js](file://context-manager.js#L225-L790) - -## CLI Arayüzü ve İş Akışı Düzenlemesi - -context-manager aracının CLI arayüzü, kullanıcılar için birincil giriş noktası olarak hizmet eder ve tüm analiz iş akışını düzenler. bin/cli.js dosyasında uygulanan CLI, analiz sürecini kontrol etmek için çeşitli seçenekler sunan kullanıcı dostu bir arayüz sağlar. Arayüz net bir yürütme akışını takip eder: komut satırı argümanlarını ayrıştırma, TokenAnalyzer'ı uygun seçeneklerle başlatma ve analizini yürütme. - -CLI, analiz davranışını kontrol eden çeşitli önemli seçenekleri destekler: -- `--save-report` veya `-s`: Analizin detaylı bir JSON raporunu kaydeder -- `--verbose` veya `-v`: Analiz sırasında dahil edilen dosyaları ve dizinleri gösterir -- `--context-export`: Bir LLM context dosya listesi oluşturur -- `--context-clipboard`: Context'i doğrudan panoya kopyalar -- `--method-level` veya `-m`: Metod seviyesi analizini etkinleştirir -- `--gitingest` veya `-g`: GitIngest-style digest dosyası oluşturur -- `--help` veya `-h`: Yardım bilgilerini görüntüler - -Export seçenekleri belirtilmediğinde, araç interaktif moda girer ve analizi tamamladıktan sonra kullanıcıdan bir export seçeneği seçmesini ister. Bu, kullanıcıların analiz sonuçlarını istenen formatta export etme fırsatını asla kaçırmamasını sağlar. CLI ayrıca, proje kök dizini olarak mevcut çalışma dizini ile TokenAnalyzer'ın başlatılmasını yönetir ve analiz seçeneklerini yapılandırmak için komut satırı argümanlarını işler. - -```mermaid -sequenceDiagram -participant User as "User" -participant CLI as "CLI Interface" -participant Analyzer as "TokenAnalyzer" -User->>CLI : Execute command (e.g., context-manager --method-level --gitingest) -CLI->>CLI : Parse command-line arguments -CLI->>CLI : Initialize options object -CLI->>Analyzer : Create TokenAnalyzer instance with options -Analyzer->>Analyzer : Scan directory and filter files -Analyzer->>Analyzer : Analyze files and extract methods (if method-level enabled) -Analyzer->>Analyzer : Calculate token counts -Analyzer->>Analyzer : Generate LLM context or GitIngest digest -Analyzer->>CLI : Return analysis results -CLI->>CLI : Export context to file or clipboard -CLI->>User : Display completion message -``` - -**Diagram kaynakları** -- [bin/cli.js](file://bin/cli.js#L1-L67) -- [context-manager.js](file://context-manager.js#L225-L790) - -**Bölüm kaynakları** -- [bin/cli.js](file://bin/cli.js#L1-L67) -- [context-manager.js](file://context-manager.js#L225-L790) - -## GitIngest Digest Üretimi - -context-manager aracı artık GitIngest-style digest dosyaları oluşturmayı desteklemektedir - LLM tüketimi için mükemmel olan tek, prompt-dostu metin dosyası. Bu özellik, tüm kod tabanını net bir dizin ağacı yapısı ve tam dosya içerikleriyle tek bir dosyada birleştiren alternatif bir format sağlamak için uygulanmıştır. - -GitIngestFormatter sınıfı bu digest dosyalarını oluşturmaktan sorumludur. TokenCalculator'dan gelen analiz sonuçlarını alır ve bunları şunları içeren yapılandırılmış bir metin dosyasına biçimlendirir: -- Proje özeti ve istatistikleri -- ASCII art kullanarak görsel dizin ağacı yapısı -- Net ayırıcılarla tam dosya içerikleri -- İnsan tarafından okunabilir şekilde biçimlendirilmiş token sayım tahminleri (örn., "1.2k") - -Digest oluşturma süreci, .gitignore ve calculator ignore/include kuralları dahil tüm filtreleme kurallarına uyar. Metod seviyesi analiz etkinleştirildiğinde, formatter her dosyada yalnızca belirtilen metodları dahil etmek için metod filtreleme uygular, bu da digest'i daha da odaklı ve alakalı hale getirir. - -GitIngest digest çeşitli şekillerde oluşturulabilir: -1. Doğrudan tam bir analizden: `context-manager --gitingest` -2. Mevcut bir JSON raporundan: `context-manager --gitingest-from-report token-analysis-report.json` -3. Mevcut bir LLM context dosyasından: `context-manager --gitingest-from-context llm-context.json` - -Bu iki adımlı iş akışı, digest'in tüm kod tabanını yeniden taramadan mevcut JSON dosyalarından anında oluşturulabilmesi nedeniyle performans optimizasyonuna olanak tanır. - -```mermaid -sequenceDiagram -participant User as "User" -participant CLI as "CLI Interface" -participant Analyzer as "TokenAnalyzer" -participant Formatter as "GitIngestFormatter" -User->>CLI : Execute command (e.g., context-manager --gitingest) -CLI->>CLI : Parse command-line arguments -CLI->>Analyzer : Create TokenAnalyzer instance -Analyzer->>Analyzer : Scan and analyze codebase -Analyzer->>Analyzer : Collect analysis results -Analyzer->>Formatter : Create GitIngestFormatter with results -Formatter->>Formatter : Generate digest content -Formatter->>Formatter : Save digest to digest.txt -Formatter->>Analyzer : Return digest size -Analyzer->>CLI : Report completion -CLI->>User : Display success message with digest size -``` - -**Diagram kaynakları** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L332-L339) - -**Bölüm kaynakları** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L332-L339) -- [README.md](file://README.md#L600-L700) - -## Metod Seviyesi Analiz ve Filtreleme - -context-manager aracı, geliştiricilerin kod tabanlarındaki belirli metodlara odaklanmalarını sağlayan sofistike metod seviyesi analiz yetenekleri sağlar. Bu özellik, özellikle LLM context optimizasyonu için değerlidir, çünkü yardımcı, test ve debug metodlarını hariç tutarken yalnızca en alakalı iş mantığı metodlarının çıkarılmasını sağlar. - -Metod seviyesi analiz, `--method-level` bayrağı tarafından kontrol edilir ve iki ana bileşen aracılığıyla uygulanır: MethodAnalyzer ve MethodFilterParser sınıfları. MethodAnalyzer, fonksiyon bildirimleri, nesne metodları, arrow fonksiyonlar ve sınıf metodları dahil olmak üzere çeşitli sözdizimi desenlerini destekleyerek JavaScript/TypeScript dosyalarındaki metodları tanımlamak için bir dizi düzenli ifade kullanır. Metod adlarını, satır numaralarını ve dosya yollarını çıkararak kod tabanındaki metodların kapsamlı bir envanterini oluşturur. - -MethodFilterParser, yapılandırma dosyalarına (.methodinclude ve .methodignore) dayalı metodları filtrelemek için include/exclude kuralları uygular. Bu dosyalar, tam eşleşmeleri, joker karakterleri (*pattern*), sınıfa özgü metodları (Class.*) ve dosyaya özgü metodları (file.method) destekleyen desen eşleştirme sözdizimini kullanır. Filtreleme sistemi hem include modunu (yalnızca belirtilen metodlar dahil edilir) hem de exclude modunu (belirtilen metodlar hariç tutulur) destekler; her iki yapılandırma dosyası da mevcut olduğunda include modu önceliklidir. - -```mermaid -flowchart TD -Start([Start Method-Level Analysis]) --> ExtractMethods["Extract Methods from Files"] -ExtractMethods --> HasFilter{"Method Filter Active?"} -HasFilter --> |Yes| ApplyFilter["Apply Include/Exclude Rules"] -HasFilter --> |No| IncludeAll["Include All Methods"] -ApplyFilter --> FilterMode{"Include Mode?"} -FilterMode --> |Yes| CheckInclude["Check Against .methodinclude"] -FilterMode --> |No| CheckExclude["Check Against .methodignore"] -CheckInclude --> IncludeResult{"Match Found?"} -CheckExclude --> ExcludeResult{"Match Found?"} -IncludeResult --> |Yes| IncludeMethod["Include Method"] -IncludeResult --> |No| ExcludeMethod["Exclude Method"] -ExcludeResult --> |Yes| ExcludeMethod -ExcludeResult --> |No| IncludeMethod -IncludeMethod --> CalculateTokens["Calculate Method Token Count"] -ExcludeMethod --> NextMethod["Process Next Method"] -CalculateTokens --> StoreResults["Store Method Information"] -StoreResults --> NextMethod -NextMethod --> MoreMethods{"More Methods?"} -MoreMethods --> |Yes| ExtractMethods -MoreMethods --> |No| GenerateContext["Generate LLM Context"] -GenerateContext --> End([End Analysis]) -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) -- [README.md](file://README.md#L499-L542) - -## Token Sayımı ve Context Oluşturma - -context-manager aracı, LLM context optimizasyonu için gerekli olan doğru token sayımı yetenekleri sağlar. GPT-4 ile uyumlu kesin token sayımı için tiktoken kütüphanesini kullanır, tiktoken mevcut olmadığında akıllı tahmini yönteme geri döner. Token sayım sistemi, tiktoken bağımlılığı olmadan bile ~%95 doğruluk sağlayacak şekilde tasarlanmıştır ve çeşitli geliştirme ortamları için erişilebilir hale getirir. - -Token sayım süreci, dosya içeriğini okumayı, dosya uzantılarına özgü karakter-token oranlarına dayalı token hesaplamayı ve kod tabanı genelinde istatistikleri toplamayı içerir. Kesin sayım için araç, GPT-4 tarafından kullanılan aynı encoding olan tiktoken'dan cl100k_base encoding'ini kullanır ve hassas context penceresi yönetimini sağlar. Tahmin sistemi, güvenilir yaklaşımlar sağlamak için farklı dosya tipleri için önceden tanımlanmış token başına karakter oranlarını (örneğin, JavaScript için 3.2, Markdown için 4.0) kullanır. - -Context oluşturma, LLM tüketimi için iki formatta optimize edilmiş dosya listeleri üreten önemli bir özelliktir: ultra-compact (varsayılan) ve detailed. Ultra-compact format, token sayıları olmadan proje metadata'sı ve organize edilmiş dosya yollarını içeren ~2.3k karakter yapılandırılmış JSON temsili oluştururken, detailed format tam yollar, kategoriler, önem puanları ve dizin istatistikleri dahil olmak üzere ~8.6k karakter kapsamlı bilgi üretir. Her iki format da aynı JSON yapılarını kullanır ve pano ile dosya export'ları arasında tutarlılığı sağlar. - -```mermaid -flowchart LR -A[Read File Content] --> B{tiktoken Available?} -B --> |Yes| C[Use cl100k_base Encoding] -B --> |No| D[Use Smart Estimation] -C --> E[Calculate Exact Token Count] -D --> F[Apply Extension-Specific Ratios] -F --> G[Estimate Token Count] -E --> H[Aggregate Statistics] -G --> H -H --> I{Method-Level Analysis?} -I --> |Yes| J[Extract and Filter Methods] -I --> |No| K[Process Files Only] -J --> L[Calculate Method Token Counts] -L --> M[Generate Method Context] -K --> N[Generate File Context] -M --> O[Create LLM Context] -N --> O -O --> P[Export to Clipboard or File] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L639-L665) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L639-L665) -- [README.md](file://README.md#L499-L542) - -## Yapılandırma ve Filtreleme Modları - -context-manager aracı, hangi dosya ve metodların analize dahil edileceği üzerinde hassas kontrol sağlayan dual filtreleme modları (include/exclude) ile esnek bir yapılandırma sistemini destekler. Bu sistem, geliştiricilerin yalnızca temel uygulama mantığını analiz etmek veya belirli dosya ve dizinleri dahil etmek istemeleri olsun, özel ihtiyaçlarına göre uyarlanmış odaklanmış analiz setleri oluşturmalarına olanak tanır. - -Dosya seviyesi filtreleme sistemi, net bir öncelik hiyerarşisi ile üç yapılandırma dosyası kullanır: -1. `.gitignore` (proje kök dizini) - Standart git hariç tutmaları (her zaman geçerlidir) -2. `.contextinclude` - INCLUDE modu (dosyalar için en yüksek öncelik) -3. `.contextignore` - EXCLUDE modu (include dosyası yokken kullanılır) - -`.contextinclude` mevcut olduğunda, araç INCLUDE modunda çalışır, yalnızca bu dosyadaki desenlere uyan dosyaları dahil eder ve `.contextignore`'u göz ardı eder. Yalnızca `.contextignore` mevcut olduğunda, araç EXCLUDE modunda çalışır ve ignore desenlerine uyan dosyalar hariç tüm dosyaları dahil eder. Bu dual-mod sistemi, kapsamlı kod tabanı analizinden belirli bileşenlerin odaklanmış incelemesine kadar farklı kullanım durumları için esneklik sağlar. - -Metod seviyesi filtreleme, analize hangi metodların dahil edileceğini kontrol eden `.methodinclude` ve `.methodignore` dosyalarıyla benzer bir deseni takip eder. Bu dosyalar, tam eşleşmeler, joker karakterler (*pattern*), sınıfa özgü metodlar (Class.*) ve dosyaya özgü metodlar (file.method) dahil olmak üzere desen eşleştirme sözdizimini destekler. Desen sözdizimi ayrıca geniş desenlerden belirli öğeleri hariç tutmak için olumsuzlama (!pattern) destekler. - -```mermaid -graph TD -A[Start Analysis] --> B{.contextinclude Exists?} -B --> |Yes| C[INCLUDE Mode] -B --> |No| D{.contextignore Exists?} -D --> |Yes| E[EXCLUDE Mode] -D --> |No| F[Include All Files] -C --> G[Load .contextinclude Patterns] -E --> H[Load .contextignore Patterns] -G --> I[Include Only Matching Files] -H --> J[Exclude Matching Files] -I --> K[Apply .gitignore Rules] -J --> K -K --> L{Method-Level Analysis?} -L --> |Yes| M{.methodinclude Exists?} -M --> |Yes| N[INCLUDE Mode for Methods] -M --> |No| O{.methodignore Exists?} -O --> |Yes| P[EXCLUDE Mode for Methods] -O --> |No| Q[Include All Methods] -N --> R[Include Only Matching Methods] -P --> S[Exclude Matching Methods] -R --> T[Generate Context] -S --> T -Q --> T -T --> U[Export Results] -``` - -**Diagram kaynakları** -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L253-L286) - -**Bölüm kaynakları** -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L253-L286) - -## Pratik Kullanım Örnekleri - -context-manager aracı, AI destekli geliştirme iş akışlarını geliştiren geniş bir pratik kullanım örneği yelpazesini destekler. Bu kullanım örnekleri, aracın LLM context'ini optimize etme, kod tabanlarını analiz etme ve geliştirme süreçleriyle entegre olma konusundaki çok yönlülüğünü gösterir. - -LLM context optimizasyonu için geliştiriciler, `context-manager --method-level --context-clipboard` gibi komutlar kullanarak AI asistanları için minimal context oluşturabilir. Bu, tam kod tabanına kıyasla context boyutunu %89'a kadar azaltan, temel iş mantığı metodlarına odaklanan kod tabanının ultra-compact bir temsilini oluşturur. `*Handler`, `*Validator` ve `*Manager` gibi desenlerle bir `.methodinclude` dosyası oluşturarak geliştiriciler, context'e yalnızca alakalı metodların dahil edilmesini sağlayabilir. - -Kod tabanı analizi, aracın proje karmaşıklığını ve yapısını anlamaya yardımcı olduğu bir diğer önemli kullanım örneğidir. `context-manager --save-report --verbose` çalıştırmak, geçmiş takip ve CI/CD entegrasyonu için kullanılabilecek detaylı bir JSON raporu oluşturur. Bu rapor, dosya tipleri, en büyük dosyalar ve dizin kompozisyonu hakkında kapsamlı istatistikler içerir ve kod tabanı sağlığı ve organizasyonu hakkında değerli içgörüler sağlar. - -Araç ayrıca geliştiricilerin belirli sorunlu metodlara odaklanmasına olanak tanıyarak metod seviyesi debugging'i destekler. Örneğin, authentication metodlarını debug etmek için bir geliştirici `*auth*`, `*login*` ve `*validate*` gibi desenlerle bir `.methodinclude` dosyası oluşturabilir, ardından `context-manager --method-level --context-clipboard` çalıştırabilir. Bu, alakalı metodları izole eder ve debugging için odaklanmış bir context sağlar. - -CI/CD entegrasyonu, kod tabanı büyümesini ve karmaşıklığını izlemek için otomatik token analizi aracılığıyla kolaylaştırılır. Script'ler, token sayılarını takip etmek ve LLM context limitleri etkilemeden önce potansiyel sorunları tespit etmek için günlük olarak `context-manager --save-report` çalıştırabilir. Kod tabanının token bütçelerini aşıp aşmadığını kontrol ederek kod kalitesi geçitleri uygulanabilir ve projelerin AI destekli geliştirme için yönetilebilir limitler içinde kalması sağlanır. - -GitIngest formatter tarafından etkinleştirilen yeni bir kullanım senaryosu, LLM tüketimi için tek dosyalık digest'ler oluşturmaktır. Geliştiriciler, tüm kod tabanını LLM prompt'larına yapıştırmak için mükemmel yapılandırılmış bir formatta içeren bir `digest.txt` dosyası oluşturmak için `context-manager --gitingest` çalıştırabilir. Bu özellikle kod incelemeleri, dokümantasyon oluşturma ve AI analiz iş akışları için kullanışlıdır. - -```mermaid -erDiagram -USER_REQUIREMENT { -string useCase PK -string description -string command -string configuration -string outputFormat -} -USER_REQUIREMENT ||--o{ CONFIG_FILE : "uses" -USER_REQUIREMENT ||--o{ OUTPUT_FORMAT : "produces" -CONFIG_FILE { -string filename PK -string patternSyntax -string mode -} -OUTPUT_FORMAT { -string formatType PK -string size -string content -string useCase -} -USER_REQUIREMENT { -"LLM Context Optimization" "Generate minimal context for AI assistants" "context-manager --method-level --context-clipboard" ".methodinclude with *Handler, *Validator" "Ultra-compact JSON (~2.3k chars)" -"Codebase Analysis" "Understand project complexity and structure" "context-manager --save-report --verbose" ".contextinclude with core JS files" "Detailed JSON report (~8.6k chars)" -"Method-Level Debugging" "Focus on specific problematic methods" "context-manager --method-level --verbose" ".methodinclude with *auth*, *login*" "Method context with line numbers" -"CI/CD Integration" "Monitor codebase growth and complexity" "context-manager --save-report" ".contextignore with test/ and docs/" "Detailed analysis for historical tracking" -"Code Quality Gates" "Ensure code stays within token budgets" "context-manager --method-level --save-report" ".methodinclude with core business logic" "Token count validation" -"GitIngest Digest" "Create single-file digest for LLM consumption" "context-manager --gitingest" ".methodinclude with core methods" "Single-file text digest (~10-50KB)" -} -CONFIG_FILE { -".contextinclude" "**/*.js, !test/**, !docs/**" "INCLUDE" -".contextignore" "**/*.md, **/*.json, node_modules/**" "EXCLUDE" -".methodinclude" "*Handler, *Validator, *Manager" "INCLUDE" -".methodignore" "*test*, *debug*, console" "EXCLUDE" -} -OUTPUT_FORMAT { -"Ultra-compact JSON" "~2.3k chars" "Project metadata, organized file paths" "LLM context optimization" -"Detailed JSON" "~8.6k chars" "Full paths, categories, importance scores" "Codebase analysis" -"Method context" "~4.5k chars" "Method names, line numbers, token counts" "Method-level debugging" -"Detailed report" "~12k chars" "Comprehensive statistics, largest files" "CI/CD integration" -"GitIngest digest" "~10-50KB" "Directory tree, file contents" "LLM consumption, code reviews" -} -``` - -**Diagram kaynakları** -- [README.md](file://README.md#L499-L542) -- [README.md](file://README.md#L801-L879) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) - -**Bölüm kaynakları** -- [README.md](file://README.md#L499-L542) -- [README.md](file://README.md#L801-L879) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [README.md](file://README.md#L801-L879) diff --git a/docs/content-tr/CLI-Referans.md b/docs/content-tr/CLI-Referans.md deleted file mode 100644 index 863323b..0000000 --- a/docs/content-tr/CLI-Referans.md +++ /dev/null @@ -1,300 +0,0 @@ -# CLI Referans - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [bin/cli.js](file://bin/cli.js) - *6f5fea32 commit'inde güncellendi* -- [context-manager.js](file://context-manager.js) - *6f5fea32 ve 0b9cbab0 commit'lerinde güncellendi* -- [README.md](file://README.md) - *Her iki commit'te de güncellendi* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *6f5fea32 commit'inde eklendi* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *6f5fea32 commit'inde eklendi* - - -## Güncelleme Özeti -**Yapılan Değişiklikler** -- Yeni GitIngest işlevselliği ve JSON tabanlı digest üretimi için kapsamlı dokümantasyon eklendi -- Kullanılabilir seçenekler bölümü yeni CLI bayrakları ile güncellendi: --gitingest (-g), --gitingest-from-report, ve --gitingest-from-context -- Method seviyesi analiz dokümantasyonu, method filtreleme konfigürasyonu hakkında detaylar ile geliştirildi -- Kullanım örnekleri ve çıktı formatı detayları ile GitIngest format export için yeni bölüm eklendi -- Kullanım örnekleri, yeni komut kombinasyonlarını içerecek şekilde güncellendi -- Bölüm kaynakları, yeni eklenen formatter ve parser dosyalarını içerecek şekilde genişletildi - -## İçindekiler -1. [Giriş](#giriş) -2. [Komut Sözdizimi](#komut-sözdizimi) -3. [Kullanılabilir Seçenekler](#kullanılabilir-seçenekler) -4. [İnteraktif Export Seçimi](#interaktif-export-seçimi) -5. [Kullanım Örnekleri](#kullanım-örnekleri) -6. [GitIngest Format Export](#gitingest-format-export) -7. [Exit Code'lar ve Hata Yönetimi](#exit-codelar-ve-hata-yönetimi) -8. [Performans Değerlendirmeleri](#performans-değerlendirmeleri) -9. [Shell Script Entegrasyonu](#shell-script-entegrasyonu) -10. [Sorun Giderme Rehberi](#sorun-giderme-rehberi) - -## Giriş -context-manager CLI, kod tabanlarını analiz etmek ve LLM tüketimi için context'i optimize etmek üzere kapsamlı bir araç sağlar. Method seviyesinde filtreleme, kesin token sayımı ve AI destekli geliştirme iş akışlarını desteklemek için birden fazla export formatı sunar. Araç hem .gitignore hem de özel ignore/include kurallarına saygı gösterir ve farklı analiz senaryoları için esnek konfigürasyon seçenekleri sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) - -## Komut Sözdizimi -context-manager CLI için temel sözdizimi: -``` -context-manager [options] -``` - -Komut, analiz davranışını, çıktı formatını ve export hedeflerini kontrol eden çeşitli seçenekleri kabul eder. Hiçbir seçenek belirtilmediğinde, araç interactive modda çalışır ve analiz tamamlandıktan sonra kullanıcıdan export seçeneklerini seçmesini ister. - -**Bölüm kaynakları** -- [bin/cli.js](file://bin/cli.js#L4-L25) -- [context-manager.js](file://context-manager.js#L815-L830) - -## Kullanılabilir Seçenekler -context-manager CLI aşağıdaki seçenekleri destekler: - -### --save-report (-s) -Analizin detaylı JSON raporunu proje kök dizininde token-analysis-report.json olarak kaydeder. - -**Davranış**: Metadata, özet istatistikleri ve analiz edilen her dosya hakkında detaylı bilgileri içeren kapsamlı bir rapor oluşturur. - -**Dönüş değeri**: Yapılandırılmış analiz verisi içeren token-analysis-report.json dosyası oluşturur. - -### --no-verbose -Verbose çıktı modunu devre dışı bırakır, analiz sırasında dahil edilen dosya ve dizinlerin görüntülenmesini engeller. - -**Davranış**: İşlenen dosyaların listesini göstermeden analizi çalıştırır, daha temiz bir çıktı sağlar. - -**Dönüş değeri**: Dosya listeleme detayları olmadan standart analiz raporu. - -### --context-export -Bir LLM context dosya listesi oluşturur ve bunu proje kök dizininde llm-context.json olarak kaydeder. - -**Davranış**: LLM tüketimi için uygun optimize edilmiş proje context'i içeren bir JSON dosyası oluşturur. - -**Dönüş değeri**: Proje metadata'sı ve organize edilmiş dosya yolları içeren llm-context.json dosyası oluşturur. - -### --context-clipboard -LLM context'ini doğrudan sistem panosuna kopyalar. - -**Davranış**: Context'i JSON formatında oluşturur ve platforma özel komutlar kullanarak panoya kopyalar (macOS'ta pbcopy, Linux'ta xclip/xsel, Windows'ta clip). - -**Dönüş değeri**: Context verisi panoya kopyalanır; başarı durumunda karakter sayısını gösterir. - -### --detailed-context -Varsayılan compact format yerine detailed context formatını kullanır. - -**Davranış**: Ek metadata, kategoriler ve önem skorları ile daha kapsamlı bir context çıktısı oluşturur. - -**Dönüş değeri**: Gelişmiş bilgilerle daha büyük context çıktısı (~8.6k karakter). - -### --method-level (-m) -Method seviyesinde analiz modunu etkinleştirir. - -**Davranış**: JavaScript/TypeScript dosyalarından bireysel methodları çıkarır ve analiz eder, .methodinclude ve .methodignore dosyalarından method seviyesinde filtreleme kurallarını uygular. - -**Dönüş değeri**: Method adları, satır numaraları ve token sayıları dahil olmak üzere çıktıya method'a özgü bilgileri dahil eder. - -### --gitingest (-g) -GitIngest-style digest dosyası oluşturur (digest.txt). - -**Davranış**: Tüm kod tabanını proje özeti, dizin ağacı yapısı ve tam dosya içerikleri ile birleştirerek LLM tüketimi için mükemmel tek bir metin dosyası oluşturur. - -**Dönüş değeri**: Digest içeriğini proje kök dizininde digest.txt dosyası olarak kaydeder. - -### --gitingest-from-report -Mevcut bir token-analysis-report.json dosyasından GitIngest digest oluşturur (hızlı, yeniden tarama yok). - -**Davranış**: Belirtilen JSON raporunu okur ve kod tabanını yeniden analiz etmeden digest.txt oluşturur. Dosya adı belirtilmezse, token-analysis-report.json varsayılan olarak kullanılır. - -**Dönüş değeri**: Rapor verisinden anında digest.txt dosyası oluşturur. - -### --gitingest-from-context -Mevcut bir llm-context.json dosyasından GitIngest digest oluşturur. - -**Davranış**: LLM context dosyasını okur ve kod tabanını yeniden taramadan digest oluşturur, hızlı digest üretimini mümkün kılar. - -**Dönüş değeri**: Context verisinden türetilen içerikle digest.txt dosyası oluşturur. - -### --help (-h) -Kullanılabilir seçenekler ve kullanım örnekleri ile yardım mesajını görüntüler. - -**Davranış**: Yardım metnini stdout'a yazdırır ve çıkar. - -**Dönüş değeri**: Yok; yardımı görüntüledikten sonra programı sonlandırır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [bin/cli.js](file://bin/cli.js#L4-L25) -- [context-manager.js](file://context-manager.js#L150-L170) - -## İnteraktif Export Seçimi -context-manager herhangi bir export seçeneği (--save-report, --context-export veya --context-clipboard) belirtilmeden çalıştırıldığında, otomatik olarak interactive export seçimi özelliğini etkinleştirir. Analiz tamamlandıktan sonra, araç dört export seçeneği içeren bir menü sunar: - -1. Detaylı JSON raporu kaydet (token-analysis-report.json) -2. LLM context dosyası oluştur (llm-context.json) -3. LLM context'ini panoya kopyala -4. Export yok (atla) - -Kullanıcıdan tercih ettiği export seçeneğini seçmek için bir sayı (1-4) girmesi istenir. Bu interactive mod, kullanıcıların analiz sonuçlarını inceledikten sonra en uygun export formatını seçmelerini sağlar ve değerli context verisini export etme fırsatlarını kaçırmalarını önler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L618-L637) - -## Kullanım Örnekleri -Aşağıdaki örnekler yaygın komut kombinasyonlarını gösterir: - -### Method seviyesinde analiz ile panoya export -```bash -context-manager --method-level --context-clipboard -``` -Bu komut method seviyesinde analiz yapar ve sonuç context'ini panoya kopyalar, odaklanmış kod context'ini AI asistanları ile hızlıca paylaşmak için idealdir. - -### Verbose çıktı ile rapor kaydetme -```bash -context-manager --save-report --verbose -``` -Bu kombinasyon, analiz sırasında tüm dahil edilen dosyaları gösterirken detaylı bir JSON raporu kaydeder, kapsamlı kod tabanı incelemeleri için yararlıdır. - -### Birden fazla çıktı ile kombine analiz -```bash -context-manager --method-level --save-report --context-export --verbose -``` -Bu komut, hem detaylı bir rapor hem de bir LLM context dosyası oluştuururken verbose çıktı ile method seviyesinde analiz yapar, CI/CD pipeline'ları ve kapsamlı kod tabanı dokümantasyonu için uygundur. - -### GitIngest digest üretimi -```bash -context-manager --gitingest -``` -Tüm kod tabanını LLM tüketimi için prompt-dostu bir formatta içeren tek bir digest.txt dosyası oluşturur. - -### İki adımlı digest üretimi -```bash -context-manager --save-report -context-manager --gitingest-from-report token-analysis-report.json -``` -Önce kod tabanını analiz eder ve bir rapor kaydeder, ardından mevcut rapordan yeniden tarama yapmadan hızlıca bir digest oluşturur. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) - -## GitIngest Format Export -context-manager artık GitIngest-style digest dosyaları oluşturmayı desteklemektedir - LLM tüketimi için mükemmel olan tek, prompt-dostu metin dosyası. - -### GitIngest Formatı Nedir? -GitIngest formatı, tüm kod tabanınızı şunları içeren tek bir metin dosyasına birleştirir: -- Proje özeti ve istatistikleri -- Görsel dizin ağacı yapısı -- Net ayırıcılarla tam dosya içerikleri -- Token sayımı tahminleri - -Bu format, [GitIngest](https://github.com/coderamp-labs/gitingest)'ten ilham alınmıştır ve sıfır ek bağımlılıkla tamamen JavaScript'te uygulanmıştır. - -### Kullanım -``` -# Standart iş akışı - tek adımda analiz et ve digest oluştur -context-manager --gitingest -context-manager -g - -# Diğer export'larla birleştir -context-manager -g -s # digest.txt + token-analysis-report.json - -# İki adımlı iş akışı - mevcut JSON'dan digest oluştur (hızlı, yeniden tarama yok) -context-manager -s # Adım 1: Rapor oluştur -context-manager --gitingest-from-report # Adım 2: Digest oluştur - -# Veya LLM context'inden -context-manager --context-export # Adım 1: Context oluştur -context-manager --gitingest-from-context # Adım 2: Digest oluştur -``` - -### Çıktı Formatı -Oluşturulan `digest.txt` dosyası şunları içerir: -- Proje adı ve dosya sayısı -- Tree formatıyla dizin yapısı görselleştirmesi -- Tahmini token sayısı -- Net sınırlayıcılarla ayrılmış dosya içerikleri -- Method seviyesi filtreleme aktifken, yalnızca dahil edilen methodlar gösterilir - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## Exit Code'lar ve Hata Yönetimi -context-manager CLI güçlü hata yönetim mekanizmaları uygular: - -- **Başarı (exit code 0)**: Analiz tüm istenen işlemler gerçekleştirilerek başarıyla tamamlandı. -- **Geçersiz seçenek (exit code 1)**: Komut tanınmayan veya hatalı biçimlendirilmiş seçeneklerle çağrıldı. -- **Dosya sistemi hatası (exit code 1)**: Analiz sırasında dosya veya dizinlere erişimde sorunlar. -- **Pano hatası**: Pano işlemleri başarısız olduğunda, araç bir uyarı mesajıyla context'i llm-context.json'a kaydetmeye geri döner. - -Araç, eksik konfigürasyon dosyalarını zarif bir şekilde ele alır ve bilgilendirici hata mesajları sağlar. tiktoken kesin token sayımı için mevcut olmadığında, bir uyarıyla akıllı tahmin yöntemine geri döner. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L750-L772) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Performans Değerlendirmeleri -Büyük kod tabanlarını analiz ederken, aşağıdaki performans optimizasyonlarını göz önünde bulundurun: - -- Analizi yalnızca gerekli dosyalarla sınırlamak için .contextinclude kullanın -- Belirli işlevselliğe odaklanmak için method seviyesinde analizi etkinleştirin -- Çıktı işlemeyi azaltmak için büyük repolar için verbose modu kullanmaktan kaçının -- Daha hızlı işleme ve daha küçük çıktı için compact context formatını kullanın -- Yeniden tarama yapmadan anında digest oluşturma için JSON tabanlı digest üretimini (--gitingest-from-report veya --gitingest-from-context) kullanın - -Araç, verimli dizin taraması ve token sayma algoritmaları ile performans için optimize edilmiştir. Çok büyük kod tabanları için, ilk tarama birkaç saniye sürebilir, ancak sonraki analizler işlenen dosya sayısını azaltan filtreleme kurallarından faydalanır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L225-L790) - -## Shell Script Entegrasyonu -context-manager CLI, otomatik iş akışları için shell scriptlere entegre edilebilir: - -```bash -# Kod tabanının token bütçesini aşıp aşmadığını kontrol et -TOKENS=$(context-manager --context-export --no-verbose | jq '.project.totalTokens') -if [ $TOKENS -gt 100000 ]; then - echo "Kod tabanı LLM context için çok büyük!" - exit 1 -fi -``` - -```bash -# Zaman damgalı raporlarla günlük analiz -context-manager --save-report > reports/analysis-$(date +%Y%m%d).json -``` - -Aracın öngörülebilir çıktı formatı ve exit code'ları, CI/CD pipeline'larında, pre-commit hook'larında ve otomatik dokümantasyon oluşturma iş akışlarında kullanım için uygun hale getirir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) - -## Sorun Giderme Rehberi -### Komut bulunamadı -Paketin global olarak yüklendiğinden emin olun: -```bash -npm install -g @hakkisagdic/context-manager -``` - -### Geçersiz seçenekler -Seçenek adlarını ve sözdizimini doğrulayın. Geçerli seçenekleri görmek için --help kullanın. - -### İzin hataları -Bazı sistemlerde, pano işlemleri ek izinler gerektirebilir. Araç, pano erişimi reddedildiğinde otomatik olarak dosya çıktısına geri döner. - -### Eksik beklenen dosyalar -Dosyaların .gitignore veya calculator kuralları tarafından hariç tutulup tutulmadığını kontrol edin. Hangi dosyaların işlendiğini görmek için verbose modunu kullanın. - -### Token sayımı tutarsızlıkları -Kesin token sayımı için tiktoken'ın yüklendiğinden emin olun. tiktoken olmadan, araç dosya türüne dayalı tahmin kullanır. - -### GitIngest digest sorunları -- --gitingest-from-report veya --gitingest-from-context kullanırken gerekli JSON dosyalarının var olduğundan emin olun -- digest.txt'yi okuma ve yazma için dosya izinlerini kontrol edin -- Mevcut dosyalardan oluştururken JSON formatının geçerli olduğunu doğrulayın - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [test/test.js](file://test/test.js#L0-L61) diff --git a/docs/content-tr/Cikti-Formatlari.md b/docs/content-tr/Cikti-Formatlari.md deleted file mode 100644 index 605d8cf..0000000 --- a/docs/content-tr/Cikti-Formatlari.md +++ /dev/null @@ -1,352 +0,0 @@ -# Çıktı Formatları - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [README.md](file://README.md) - *GitIngest format detayları ile güncellendi* -- [context-manager.js](file://context-manager.js) - *GitIngest oluşturma fonksiyonları eklendi* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Yeni GitIngest formatter uygulaması* - - -## İçindekiler -1. [Giriş](#giriş) -2. [Detaylı JSON Raporu](#detaylı-json-raporu) -3. [LLM Context Formatları](#llm-context-formatları) -4. [Pano Formatı](#pano-formatı) -5. [GitIngest Formatı](#gitingest-formatı) -6. [Kullanım Senaryoları ve Performans](#kullanım-senaryoları-ve-performans) -7. [Parsing Stratejileri](#parsing-stratejileri) - -## Giriş - -context-manager aracı, AI destekli geliştirme iş akışlarında farklı kullanım senaryoları için üç temel çıktı formatı sağlar. Bu formatlar kod analizi, LLM context optimizasyonu ve proje dokümantasyonunda farklı amaçlara hizmet eder. Araç kapsamlı analiz için detaylı bir JSON raporu oluşturur, hem compact hem de detailed formatlarda LLM context dosyaları oluşturur ve hızlı paylaşım için pano entegrasyonunu destekler. Tüm export formatları dosya ve pano çıktıları arasında tutarlı yapı korur, farklı kullanım senaryolarında güvenilirlik sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) - -## Detaylı JSON Raporu - -Detaylı JSON raporu, tam metadata, özet istatistikler, dosya seviyesinde detaylar ve uygulanabilir olduğunda method seviyesinde verilerle kod tabanının kapsamlı analizini sağlar. Bu format `--save-report` flag'i kullanıldığında veya interactive modda uygun seçenek seçildiğinde oluşturulur. - -Rapor yapısı üç ana bölümden oluşur: -- **metadata**: Oluşturma zaman damgası, proje kök yolu ve .gitignore ve calculator konfigürasyon dosyalarından konfigürasyon kurallarını içerir -- **summary**: Analiz edilen toplam dosyalar, token sayıları, dosya türü dağılımı ve en büyük dosyalar/dizinler gibi kapsamlı istatistikleri içerir -- **files**: Yol, token sayısı, boyut, satırlar ve uzantı dahil her analiz edilen dosya için detaylı bilgileri içerir - -Method seviyesinde analiz `--method-level` flag'i ile etkinleştirildiğinde, dosya nesnelerinde ek method'a özgü veriler dahil edilir ve bireysel fonksiyonlar ve bunların token kullanımı hakkında granüler içgörüler sağlanır. - -```mermaid -classDiagram -class DetailedJSONReport { -+metadata : object -+summary : object -+files : array -} -class Metadata { -+generatedAt : string -+projectRoot : string -+gitignoreRules : array -+calculatorRules : array -} -class Summary { -+totalFiles : number -+totalTokens : number -+byExtension : object -+largestFiles : array -+byDirectory : object -} -class File { -+path : string -+relativePath : string -+sizeBytes : number -+tokens : number -+lines : number -+extension : string -+methods? : array -} -DetailedJSONReport --> Metadata -DetailedJSONReport --> Summary -DetailedJSONReport --> File -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L784-L799) - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L784-L799) - -## LLM Context Formatları - -context-manager aracı farklı kullanım senaryoları için optimize edilmiş iki farklı LLM context formatı sunar: varsayılan olarak kullanılan ultra-compact format ve `--detailed-context` flag'i ile etkinleştirilen detailed format. Her iki format da token kullanımını minimize ederken AI asistanları için gerekli proje context'ini sağlamak üzere tasarlanmıştır. - -### Compact Format (~2.3k karakter) - -Varsayılan compact format, JSON formatında yaklaşık 2.3k karakter ile kod tabanının minimal ama yapılandırılmış bir temsilini sağlar. Bu format şunları içerir: -- Proje metadata'sı (kök dizin, toplam dosyalar, toplam tokenlar) -- Ortak önek sıkıştırmasıyla dizine göre gruplandırılmış organize dosya yolları -- Yer tasarrufu için dosya uzantılarının kaldırılması -- Gereksizliği minimize etmek için dizin gruplandırması - -Compact format verimliliği önceliklendirir ve token ekonomisinin kritik olduğu sık AI etkileşimleri için idealdir. llm-context.json dosyasıyla tamamen aynı JSON yapısını korur. - -### Detailed Format (~8.6k karakter) - -`--detailed-context` ile etkinleştirilen detailed format, yaklaşık 8.6k karakterde daha kapsamlı bir context sağlar. Bu format şunları içerir: -- Uzantılarla tam dosya yolları -- Token sayısı ve proje yapısına dayalı önem skorları -- Dizin istatistikleri ve dosya kategorilendirmesi -- Method analizi etkinleştirildiğinde method seviyesinde veriler -- Proje anlayışı için ek metadata - -Detailed format ilk proje analizi, kapsamlı dokümantasyon ve daha derin context anlayışı gerektiren durumlar için uygundur. - -```mermaid -classDiagram -class LLMContext { -+project : object -+paths? : object -+methods? : object -+methodStats? : object -} -class ProjectMetadata { -+root : string -+totalFiles : number -+totalTokens : number -} -class Paths { -+directoryPath : array -} -class Methods { -+filePath : array -} -class MethodStats { -+totalMethods : number -+includedMethods : number -+totalMethodTokens : number -} -LLMContext --> ProjectMetadata -LLMContext --> Paths -LLMContext --> Methods -LLMContext --> MethodStats -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L482-L503) -- [context-manager.js](file://context-manager.js#L521-L545) -- [context-manager.js](file://context-manager.js#L505-L519) - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L482-L545) - -## Pano Formatı - -context-manager'daki pano formatı, dosya tabanlı export'larla aynı yapıyı korur ve farklı çıktı methodları arasında tutarlılık sağlar. `--context-clipboard` flag'i kullanıldığında, araç llm-context.json'a kaydedilecek olan aynı JSON yapısını doğrudan sistem panosuna kopyalar. - -Uygulama platformlar arası pano işlemlerini yönetir: -- **macOS**: `pbcopy` komutunu kullanır -- **Linux**: Önce `xclip`'i dener, mevcut değilse `xsel`'e geri döner -- **Windows**: `clip` komutunu kullanır -- **Diğer platformlar**: Pano işlemi başarısız olursa dosya kaydetmeye fallback sağlar - -Pano işlemi herhangi bir nedenle başarısız olursa, araç otomatik olarak context'i llm-context.json'a kaydeder, platform sınırlamalarına bakılmaksızın kullanıcının her zaman çıktıyı almasını sağlar. - -```mermaid -sequenceDiagram -participant User -participant Tool as context-manager -participant Clipboard -participant File as llm-context.json -User->>Tool : --context-clipboard -Tool->>Tool : generateLLMContext() -Tool->>Clipboard : JSON'u Kopyala (platforma özel) -alt Başarılı -Clipboard-->>Tool : Başarılı -Tool-->>User : "Context panoya kopyalandı!" -else Başarısız -Tool->>File : saveContextToFile() -File-->>Tool : Kaydedildi -Tool-->>User : "Kopyalama başarısız... dosyaya kaydedildi" -end -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L547-L579) - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L547-L579) - -## GitIngest Formatı - -context-manager aracı artık yeni bir çıktı formatını desteklemektedir: GitIngest-style digest dosyaları. Bu format, tüm kod tabanı analizini LLM tüketimi için ideal olan tek, prompt-dostu bir metin dosyasında birleştirir. - -### GitIngest Format Genel Bakışı - -GitIngest formatı, aşağıdaki bileşenlerle kod tabanının kapsamlı, insan tarafından okunabilir bir özetini sağlar: -- Proje özeti ve istatistikler -- Görsel dizin ağacı yapısı -- Net ayırıcılarla tam dosya içerikleri -- Token sayım tahminleri -- Etkinleştirildiğinde method seviyesi filtreleme - -Bu format, [GitIngest](https://github.com/coderamp-labs/gitingest)'ten ilham alınmıştır ve sıfır ek bağımlılıkla saf JavaScript'te uygulanmıştır. - -### Oluşturma Methodları - -GitIngest digest birden fazla yoldan oluşturulabilir: - -**Doğrudan Oluşturma** -``` -# Kod tabanı analizinden doğrudan digest oluştur -context-manager --gitingest -context-manager -g -``` - -**JSON Tabanlı Oluşturma** -``` -# Mevcut JSON raporundan digest oluştur (anında, yeniden tarama yok) -context-manager --gitingest-from-report token-analysis-report.json - -# LLM context dosyasından digest oluştur -context-manager --gitingest-from-context llm-context.json -``` - -**İki Adımlı İş Akışı** -``` -# Adım 1: Analiz raporu oluştur -context-manager --save-report - -# Adım 2: Rapordan digest oluştur (anında) -context-manager --gitingest-from-report token-analysis-report.json -``` - -### Çıktı Yapısı - -Oluşturulan `digest.txt` dosyası şu yapıyı izler: - -``` -Directory: my-project -Files analyzed: 42 -Method filtering: INCLUDE mode active - -Estimated tokens: 15.2k -Directory structure: -└── my-project/ - ├── src/ - │ ├── index.js - │ └── utils.js - └── README.md - - -================================================ -FILE: src/index.js -================================================ -[tam dosya içeriği burada] - -================================================ -FILE: src/utils.js -================================================ -[tam dosya içeriği burada] -``` - -### Temel Özellikler - -- **Tek Dosya Çıktısı**: Kolay LLM alımı için her şey tek bir dosyada birleştirilir -- **Ağaç Görselleştirme**: Uygun girintili net dizin yapısı -- **Token Tahminleri**: Okunabilirlik için "1.2k" veya "1.5M" olarak formatlanmış -- **Sıralı Çıktı**: Dosyalar token sayısına göre sıralanmış (en büyük önce) -- **Filtre Uyumluluğu**: Tüm `.gitignore` ve calculator ignore kurallarına saygı gösterir -- **Method Seviyesi Filtreleme**: Etkinleştirildiğinde, yalnızca filtre kriterlerine uyan methodları içerir -- **Performans Optimize**: JSON tabanlı oluşturma, yeniden tarama olmadan anındadır - -### Method Seviyesi Filtreleme - -Method seviyesi analiz etkinleştirildiğinde, GitIngest formatter `.methodinclude` ve `.methodignore` yapılandırma dosyalarına dayalı method filtreleme uygular: - -- **INCLUDE Modu**: Yalnızca `.methodinclude`'da belirtilen methodlar dahil edilir -- **EXCLUDE Modu**: `.methodignore`'da belirtilen methodlar hariç tutulur - -Kod dosyaları için, digest'te yalnızca filtrelenmiş methodlar net açıklamalarla birlikte dahil edilir: - -``` -// Dosya 15 method içeriyor, 5 filtrelenmiş method gösteriliyor - -// Method: calculateTokens (satır 45) -function calculateTokens(content) { - // method implementasyonu -} - -// Method: validateInput (satır 89) -function validateInput(data) { - // method implementasyonu -} -``` - -### Uygulama Detayları - -GitIngest formatı, `lib/formatters/gitingest-formatter.js`'deki `GitIngestFormatter` sınıfı aracılığıyla uygulanır. Bu sınıf şunları yönetir: -- Proje özet oluşturma -- Dizin ağacı inşası -- Dosya içeriği çıkarma -- Method seviyesi filtreleme -- Çıktı formatlama ve dosya kaydetme - -Formatter, method filtreleme yapılandırmasını otomatik olarak algılar ve kod dosyalarını işlerken uygular. - -**Bölüm kaynakları** -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L332-L339) -- [README.md](file://README.md#L600-L700) - -## Kullanım Senaryoları ve Performans - -Farklı çıktı formatları geliştirme iş akışlarında belirli kullanım senaryolarına hizmet eder: - -**Compact Format Kullanım Senaryoları:** -- **LLM Entegrasyonu**: Tam proje context'i ile AI asistanları için yapılandırılmış veri -- **Programatik İşleme**: Otomatik araçlar ve scriptler için JSON formatı -- **Context Paylaşımı**: Pano ve dosya export'larında özdeş format -- **Geliştirme İş Akışları**: CI/CD ve otomasyon için tutarlı yapı - -**Detailed Format Kullanım Senaryoları:** -- **Mimari Planlama**: Büyük kararlar için kapsamlı proje genel bakışı -- **Yeni Takım Üyesi Adaptasyonu**: Tam kod tabanı anlayışı -- **Dokümantasyon Oluşturma**: Tam proje yapısı analizi -- **Kod İnceleme Hazırlığı**: Detaylı dosya ilişkileri ve önemi - -**Performans Değerlendirmeleri:** -- Compact format, tam kod tabanına kıyasla context boyutunu yaklaşık %89 azaltır -- Token sayımı, mevcut olduğunda GPT-4 uyumluluğu için tiktoken kullanır, tahmin fallback'i ile -- Dizin gruplandırması ve ortak önek sıkıştırması alan kullanımını optimize eder -- Method seviyesinde analiz ek yük ekler ancak odaklanmış hata ayıklama için granüler context sağlar - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) - -## Parsing Stratejileri - -context-manager çıktılarının downstream işlemesi, formatlar arasında tutarlı JSON yapısından yararlanabilir: - -**Detaylı JSON Raporları İçin:** -- Audit trail'leri ve versiyon takibi için metadata çıkarın -- Kod tabanı sağlık izleme için dosya seviyesinde istatistikleri analiz edin -- Kritik fonksiyonların odaklanmış analizi için method seviyesinde verileri işleyin -- Uzantı ve dizin istatistiklerinden görselleştirmeler oluşturun - -**LLM Context Formatları İçin:** -- Kapsam ve ölçeği anlamak için proje metadata'sını parse edin -- Dizin yapısını yeniden oluşturmak için yol gruplarını gezin -- Hedefli kod analizi için method bilgilerini kullanın -- Yapılandırılmış proje context'ini kabul eden AI araçlarıyla entegre edin - -**Genel Parsing Önerileri:** -- İşlemeden önce JSON yapısını doğrulayın -- İsteğe bağlı alanları (methods, methodStats) zarif bir şekilde ele alın -- Büyük raporlar için streaming parser'lar kullanın -- Tekrarlanan işlemden kaçınmak için parse edilmiş sonuçları önbelleğe alın -- Hatalı veya eksik veriler için hata yönetimi uygulayın - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L482-L545) diff --git a/docs/content-tr/Gelismis-Yapilandirma.md b/docs/content-tr/Gelismis-Yapilandirma.md deleted file mode 100644 index 415fe41..0000000 --- a/docs/content-tr/Gelismis-Yapilandirma.md +++ /dev/null @@ -1,345 +0,0 @@ -# Gelişmiş Yapılandırma - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) - - -## İçindekiler -1. [Giriş](#giriş) -2. [Konfigürasyon Dosyası Önceliği](#konfigürasyon-dosyası-önceliği) -3. [Özel Filtre Desenleri](#özel-filtre-desenleri) -4. [Gelişmiş Desen Sözdizimi](#gelişmiş-desen-sözdizimi) -5. [Performans Optimizasyonu](#performans-optimizasyonu) -6. [Entegrasyon ve Scripting](#entegrasyon-ve-scripting) -7. [En İyi Uygulamalar](#en-iyi-uygulamalar) -8. [Sorun Giderme](#sorun-giderme) - -## Giriş - -context-manager aracı, token analizi ve LLM context oluşturmaya hangi dosya ve methodların dahil edileceğini kontrol etmek için sofistike konfigürasyon seçenekleri sağlar. Bu doküman, özel kullanım senaryoları için gelişmiş konfigürasyon tekniklerini detaylandırır, özel filtre desenlerine, öncelik hiyerarşilerine ve performans optimizasyon stratejilerine odaklanır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) - -## Konfigürasyon Dosyası Önceliği - -context-manager aracı, birden fazla konfigürasyon dosyası mevcut olduğunda dosyaların analize nasıl dahil edildiğini veya hariç tutulduğunu belirleyen iyi tanımlanmış bir öncelik hiyerarşisi uygular. Bu hiyerarşi, öngörülebilir davranış sağlar. - -En yüksekten en düşüğe öncelik sırası: - -1. **`.contextinclude`** - INCLUDE modu (en yüksek öncelik) -2. **`.contextignore`** - EXCLUDE modu -3. **`.gitignore`** - Standart git hariç tutmaları (her zaman saygı gösterilir) - -`.contextinclude` mevcut olduğunda, araç INCLUDE modunda çalışır, yani yalnızca bu dosyadaki desenlere uyan dosyalar analiz edilecektir ve `.contextignore` tamamen göz ardı edilir. Yalnızca `.contextignore` mevcut olduğunda, araç EXCLUDE modunda çalışır, göz ardı desenlerine uyan dosyalar hariç tüm dosyaları analiz eder. `.gitignore` dosyası moddan bağımsız olarak her zaman saygı gösterilir. - -```mermaid -graph TD -A[Analiz Başlat] --> B{.contextinclude var mı?} -B --> |Evet| C[INCLUDE Modu] -B --> |Hayır| D{.contextignore var mı?} -D --> |Evet| E[EXCLUDE Modu] -D --> |Hayır| F[Tüm Dosyaları Dahil Et] -C --> G[Yalnızca .contextinclude desenlerine uyan dosyaları analiz et] -E --> H[.contextignore desenlerine uyan dosyalar hariç hepsini analiz et] -F --> I[.gitignore'u dikkate alarak tüm dosyaları analiz et] -G --> J[.gitignore hariç tutmalarına saygı göster] -H --> J -I --> J -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L231-L800) - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L124-L229) - -## Özel Filtre Desenleri - -context-manager aracı, hem dosya seviyesinde hem de method seviyesinde filtreleme mekanizmaları aracılığıyla özel kullanım senaryoları için özel filtre desenleri oluşturmayı destekler. - -### Dosya Seviyesinde Filtreleme - -Dosya seviyesinde filtreleme, `.contextinclude` ve `.contextignore` dosyaları aracılığıyla kontrol edilir. Bu dosyalar esnek dosya seçimi için glob desenlerini destekler: - -- `**/*.md` - Tüm markdown dosyalarını özyinelemeli olarak hariç tut -- `infrastructure/**` - Tüm infrastructure dizinini hariç tut -- `utility-mcp/src/**/*.js` - src dizinindeki tüm JavaScript dosyalarını dahil et -- `!utility-mcp/src/testing/**` - Test dosyalarını hariç tutmak için negasyon deseni - -Belirli özellik alanlarına odaklanmak için, istenen dizinleri hedefleyen desenlerle bir `.contextinclude` dosyası oluşturun: - -```bash -# Yalnızca authentication ile ilgili dosyaları dahil et -src/auth/**/*.js -src/middleware/auth.js -config/auth-config.json -``` - -Legacy kodu hariç tutmak için, `.contextinclude`'da negasyon desenleri kullanın: - -```bash -# Tüm core dosyaları dahil et ancak legacy modülleri hariç tut -src/**/*.js -!src/legacy/** -!src/deprecated/** -``` - -### Method Seviyesinde Filtreleme - -Method seviyesinde filtreleme, `.methodinclude` ve `.methodignore` dosyaları aracılığıyla daha da granüler kontrol sağlar. Bunlar method adları için desen eşleştirmesini destekler: - -- `*Handler` - 'Handler' ile biten tüm methodları dahil et -- `*Validator` - 'Validator' ile biten tüm methodları dahil et -- `TokenCalculator.*` - TokenCalculator sınıfındaki tüm methodları dahil et -- `server.printStatus` - Belirli dosya methodunu dahil et -- `*test*` - 'test' içeren tüm methodları hariç tut - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : boolean -+parseMethodFile(filePath) : Array -+shouldIncludeMethod(methodName, fileName) : boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+initMethodFilter() : MethodFilterParser -+analyzeFileMethods(content, filePath) : Array -} -TokenCalculator --> MethodFilterParser : "kullanır" -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L75-L115) -- [context-manager.js](file://context-manager.js#L231-L800) - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L75-L115) - -## Gelişmiş Desen Sözdizimi - -context-manager aracı, hem dosya hem de method filtrlemesi için karmaşık negasyon kurallarını, dizine özel desenleri ve kombine include/exclude mantığını destekleyen sofistike desen sözdizimi uygular. - -### Desen Dönüşümü ve Eşleştirme - -GitIgnoreParser'daki `convertToRegex` methodu, glob desenlerini belirli kurallarla regex'lere dönüştürür: - -- `**`, `.*`'a dönüştürülür (herhangi bir sayıda dizini eşleştirir) -- `*`, `[^/]*`'a dönüştürülür (yol ayırıcılar hariç herhangi bir karakteri eşleştirir) -- `?`, `[^/]`'a dönüştürülür (yol ayırıcı hariç herhangi bir tek karakteri eşleştirir) -- `/` ile başlayan desenler kök dizine sabitlenir -- `/` ile biten dizin desenleri dizini ve tüm içeriğini eşleştirir - -```mermaid -flowchart TD -A[Ham Desen] --> B{Deseni İşle} -B --> C[Baştan /! kaldır] -B --> D[Sondan / kaldır] -C --> E[Özel karakterleri escape et] -D --> E -E --> F[** ile .* değiştir] -F --> G[* ile [^/]* değiştir] -G --> H[? ile [^/] değiştir] -H --> I{/ ile mi başlıyor?} -I --> |Evet| J[^'ye sabitle] -I --> |Hayır| K[(^|/) öneki ekle] -J --> L{/ ile mi bitiyor?} -K --> L -L --> |Evet| M[(/.*?)? $ soneki ekle] -L --> |Hayır| N[$ soneki ekle] -M --> O[Tam Regex] -N --> O -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L159-L179) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L159-L179) - -### Karmaşık Negasyon Kuralları - -Araç, negasyon desenlerini (`!pattern`) belirli öncelik kurallarıyla ele alır. INCLUDE modunda, negasyon desenleri geniş dahil etme desenlerinden dosyaları hariç tutar. EXCLUDE modunda, negasyon desenleri başka türlü hariç tutulacak dosyaları yeniden dahil edebilir. - -Birden fazla negasyon deseni olduğunda, bunlar sırayla işlenir ve sonraki desenler öncekilerden önceliklidir. Bu, sofistike filtreleme mantığına izin verir: - -```bash -# Tüm JS dosyalarını dahil et ancak test ve legacy kodu hariç tut -src/**/*.js -!src/**/*.test.js -!src/legacy/** -!src/deprecated/** -``` - -## Performans Optimizasyonu - -context-manager aracı, analiz hızını artırmak ve kaynak kullanımını azaltmak için çeşitli performans optimizasyon teknikleri içerir. - -### Dizine Özel Analiz - -Araç, konfigürasyon dosyalarını iki konumda arar: araç dizini (`__dirname`) ve proje kök dizini (`this.projectRoot`). Bu, her projede konfigürasyon dosyaları gerektirmeden hem global hem de projeye özel konfigürasyonlara izin verir. - -```javascript -findConfigFile(filename) { - const locations = [ - path.join(__dirname, filename), - path.join(this.projectRoot, filename) - ]; - return locations.find(loc => fs.existsSync(loc)); -} -``` - -### Sonuç Önbelleğe Alma ve Verimli İşleme - -Mevcut uygulama açık önbelleğe alma içermese de, performansı şu yollarla optimize eder: - -- **Verimli dosya taraması**: `node_modules`, `.git` ve `dist` gibi yaygın dizinleri atlar -- **Toplu işleme**: Alt dizinlere geçmeden önce bir dizindeki tüm dosyaları işler -- **Minimum I/O işlemleri**: Konfigürasyon dosyalarını yalnızca başlatma sırasında bir kez okur - -Büyük projeler için, `.contextinclude`'ı yalnızca ilgili alanları hedefleyecek şekilde yapılandırarak analizi belirli dizinlerle sınırlamayı düşünün: - -```bash -# Analizi yalnızca core modüllere odakla -src/core/**/*.js -src/services/**/*.js -src/api/**/*.js -``` - -```mermaid -flowchart TD -A[Analiz Başlat] --> B[Dizini Tara] -B --> C{Dizin hariç tutma listesinde mi?} -C --> |Evet| D[Dizini Atla] -C --> |Hayır| E[Dosyaları İşle] -E --> F{Dosya dizin mi?} -F --> |Evet| G[Dizine Özyinelemeli Gir] -F --> |Hayır| H{Metin dosyası mı?} -H --> |Hayır| I[Dosyayı Atla] -H --> |Evet| J[GitIgnore Kontrol Et] -J --> K{Göz ardı edildi mi?} -K --> |Evet| L[Göz ardı edildi olarak say] -K --> |Hayır| M[Dosyayı Analiz Et] -M --> N[İstatistikleri Güncelle] -D --> O[Devam Et] -I --> O -L --> O -N --> O -G --> B -O --> P{Daha fazla öğe var mı?} -P --> |Evet| B -P --> |Hayır| Q[Tamamlandı] -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L272-L278) -- [context-manager.js](file://context-manager.js#L380-L400) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L272-L278) - -## Entegrasyon ve Scripting - -context-manager aracı, otomatik iş akışlarında ve özel scriptlerde kullanım için birden fazla entegrasyon noktası sağlar. - -### Programatik Kullanım - -Araç, TokenAnalyzer sınıfı import edilerek programatik olarak kullanılabilir: - -```javascript -const { TokenAnalyzer } = require('@hakkisagdic/context-manager'); - -const analyzer = new TokenAnalyzer('./src', { - methodLevel: true, - saveReport: true, - verbose: true -}); - -analyzer.run(); -``` - -### Export Formatları - -Araç, farklı kullanım senaryoları için birden fazla export formatını destekler: - -- **Detaylı JSON raporu**: CI/CD pipeline'ları için kapsamlı analiz verisi -- **LLM context dosyası**: AI asistanları için optimize edilmiş dosya listesi -- **Pano export'u**: Anında kullanım için context'in doğrudan kopyalanması - -`saveDetailedReport` methodu, metadata, özet istatistikler ve detaylı dosya bilgilerini içeren yapılandırılmış bir JSON raporu oluşturur: - -```mermaid -erDiagram -METADATA { -string generatedAt PK -string projectRoot -array gitignoreRules -array calculatorRules -} -SUMMARY { -number totalFiles -number totalTokens -number totalBytes -number totalLines -object byExtension -object byDirectory -array largestFiles -} -FILE { -string path PK -string relativePath -number sizeBytes -number tokens -number lines -string extension -array methods -} -METADATA ||--o{ SUMMARY : içerir -SUMMARY ||--o{ FILE : içerir -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L784-L799) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L784-L799) - -## En İyi Uygulamalar - -### Konfigürasyon Dosyası Yönetimi - -- **Açıklayıcı desen yorumları kullanın**: Karmaşık desenlerin amacını açıklamak için yorumlar ekleyin -- **Kategoriye göre organize edin**: İlgili desenleri birlikte gruplandırın (örneğin, tüm test hariç tutmaları) -- **Konfigürasyonları test edin**: Beklenen dosyaların dahil edildiğini/hariç tutulduğunu doğrulamak için verbose modunu kullanın -- **Versiyon kontrolü**: Ortamlar arasında tutarlılık sağlamak için konfigürasyon dosyalarını versiyon kontrolüne dahil edin - -### Performans Değerlendirmeleri - -- **Kapsamı sınırlayın**: İlgili kod alanlarına odaklanmak için `.contextinclude` kullanın -- **Aşırı geniş desenlerden kaçının**: Belirli desenler, birçok negasyonlu geniş olanlardan daha verimlidir -- **Düzenli bakım**: Kod tabanı geliştikçe desenleri periyodik olarak gözden geçirin ve güncelleyin -- **Sonuçları önbelleğe alın**: CI/CD pipeline'ları için, kaynak dosyalar değişmediğinde analiz sonuçlarını önbelleğe almayı düşünün - -## Sorun Giderme - -### Yaygın Sorunlar - -- **Desenler çalışmıyor**: Desen dosyalarında satır içi yorum olmadığından ve doğru glob sözdizimi kullandığınızdan emin olun -- **Yanlış dosyalar dahil edildi**: `.contextinclude`'ın var olup olmadığını kontrol edin (`.contextignore` üzerinde öncelik alır) -- **Performans sorunları**: Hedefli include desenleri kullanarak analizi belirli dizinlerle sınırlayın -- **Eksik beklenen dosyalar**: Dosyaların `.gitignore` tarafından hariç tutulmadığını doğrulayın (her zaman saygı gösterilir) - -### Hata Ayıklama İpuçları - -- Hangi dosyaların dahil edildiğini/hariç tutulduğunu görmek için `--verbose` flag'ini kullanın -- Konfigürasyon modu (INCLUDE/EXCLUDE) için konsol çıktısını kontrol edin -- Glob desen test ediciIeri kullanarak desen sözdizimini doğrulayın -- Büyük projelere uygulamadan önce küçük, izole kod tabanlarıyla desenleri test edin diff --git a/docs/content-tr/GitIngest-Format-Spesifikasyonu.md b/docs/content-tr/GitIngest-Format-Spesifikasyonu.md deleted file mode 100644 index 823258e..0000000 --- a/docs/content-tr/GitIngest-Format-Spesifikasyonu.md +++ /dev/null @@ -1,348 +0,0 @@ -# GitIngest Format Spesifikasyonu - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [GitIngestFormatter](file://lib/formatters/gitingest-formatter.js) -- [context-manager.js](file://context-manager.js) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md) -- [README.md](file://README.md) -- [test-gitingest.js](file://test/test-gitingest.js) -- [test-gitingest-json.js](file://test/test-gitingest-json.js) - - -## İçindekiler -1. [Giriş](#giriş) -2. [Amaç ve Kullanım Senaryoları](#amaç-ve-kullanım-senaryoları) -3. [Format Yapısı](#format-yapısı) -4. [Versiyon Sistemi](#versiyon-sistemi) -5. [Uygulama Detayları](#uygulama-detayları) -6. [Method Seviyesi Filtreleme](#method-seviyesi-filtreleme) -7. [Pratik Örnekler](#pratik-örnekler) -8. [LLM Tüketim Kılavuzu](#llm-tüketim-kılavuzu) -9. [Sorun Giderme](#sorun-giderme) -10. [Entegrasyon İş Akışları](#entegrasyon-iş-akışları) - -## Giriş - -GitIngest format spesifikasyonu, Large Language Model (LLM) tüketimi için optimize edilmiş kod tabanı temsili için standart bir metin tabanlı digest formatını tanımlar. Bu format, geliştiricilerin tüm proje context'lerini ChatGPT, Claude veya diğer LLM'ler gibi AI asistanları tarafından verimli bir şekilde işlenebilen tek, yapılandırılmış bir metin dosyasına birleştirmesini sağlar. - -context-manager aracındaki uygulama, proje metadata'sı, dizin yapısı görselleştirmesi ve prompt-dostu bir formatta tam dosya içeriklerini içeren kod tabanlarından GitIngest-style digest'ler oluşturan JavaScript tabanlı bir çözüm sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L150-L170) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L10) - -## Amaç ve Kullanım Senaryoları - -GitIngest formatı, karmaşık kod tabanları ile LLM context pencereleri arasında bir köprü görevi görür ve dil modellerindeki sonlu context boyutlarının temel sınırlamasını ele alır. Temel proje bilgilerini tek, iyi yapılandırılmış bir metin dosyasına birleştirerek, kapsamlı kod anlayışı ve analizini mümkün kılar. - -Temel amaçlar: -- **LLM Context Sağlama**: Token limitleri içinde tam proje context'i sunma -- **Kod Tabanı Anlık Görüntüsü**: Proje durumlarının arşiv temsillerini oluşturma -- **İşbirliği Kolaylaştırma**: Ekip üyeleri veya AI asistanları ile tam proje context'i paylaşma -- **Analiz Etkinleştirme**: Derin kod analizi, refactoring önerileri ve dokümantasyon oluşturmayı destekleme - -Başlıca kullanım senaryoları: -- **AI Destekli Geliştirme**: Kod oluşturma, debugging ve optimizasyon için tam context sağlama -- **Kod İncelemeleri**: Kapsamlı inceleme için tam proje anlık görüntüleri paylaşma -- **Onboarding**: Kapsamlı proje genel bakışları ile yeni geliştirici entegrasyonunu hızlandırma -- **Dokümantasyon Oluşturma**: Otomatik dokümantasyon sistemleri için girdi olarak hizmet etme -- **Mimari Analiz**: Kod yapısı ve desenlerinin bütünsel değerlendirmesini mümkün kılma - -**Bölüm kaynakları** -- [README.md](file://README.md#L150-L200) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L10) - -## Format Yapısı - -GitIngest formatı, hem insanlar hem de LLM'ler tarafından maksimum okunabilirlik ve verimli ayrıştırma için tasarlanmış hiyerarşik bir yapıyı takip eder. Format üç ana bölümden oluşur: özet başlığı, dizin ağacı ve dosya içerikleri. - -### Özet Başlığı -Başlık, temel proje metadata'sını sağlar: -- Dizin adı -- Analiz edilen dosya sayısı -- Method filtreleme durumu (uygulanabilir olduğunda) -- Tahmini token sayısı - -### Dizin Ağacı -ASCII karakterler kullanarak proje yapısının görsel temsili, dosya ve dizinlerin hiyerarşik organizasyonunu gösterir. Ağaç, uygun bağlayıcılarla standart dizin listeleme konvansiyonlarını takip eder. - -### Dosya İçerikleri -Digest'in özü, net sınırlayıcılarla ayrılmış tam dosya içeriklerini içerir. Dosyalar, LLM context pencereleri içinde önemli dosyalara öncelik vermek için token sayısına göre sıralanır (en büyük önce). - -```mermaid -flowchart TD -A[GitIngest Digest] --> B[Özet Başlığı] -A --> C[Dizin Ağacı] -A --> D[Dosya İçerikleri] -B --> B1["Directory: proje-adı"] -B --> B2["Files analyzed: sayı"] -B --> B3["Method filtering: mod"] -B --> B4["Estimated tokens: sayı"] -C --> C1["Directory structure:"] -C --> C2["└── proje/"] -C --> C3[" ├── src/"] -C --> C4[" └── README.md"] -D --> D1["================================================"] -D --> D2["FILE: relative-path"] -D --> D3["================================================"] -D --> D4["dosya içeriği"] -``` - -**Diagram kaynakları** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L35-L50) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L15-L30) - -## Versiyon Sistemi - -context-manager uygulaması, kendi uyumluluğunu ve özellik takibini sürdürürken referans GitIngest formatıyla uyumlu bir versiyon takip sistemi izler. - -### Mevcut Uygulama -- **GitIngest Versiyon Referansı**: v0.3.1 (2025-07-31) -- **Uygulama Tarihi**: 13 Ekim 2025 -- **Kaynak Depo**: https://github.com/coderamp-labs/gitingest - -### Versiyon Geçmişi -| Tarih | GitIngest Versiyonu | Notlar | -|------|-------------------|-------| -| 2025-10-13 | v0.3.1 | GitIngest formatına dayalı ilk uygulama | - -Versiyon sistemi, JavaScript'e özgü optimizasyonlar ve özellik eklemeleri için izin verirken, gelişen GitIngest spesifikasyonu ile uyumluluğu sağlar. Uygulama, denetim amaçları için dokümantasyon dizininde referans uygulamasının bir anlık görüntüsünü tutar. - -**Bölüm kaynakları** -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L79) - -## Uygulama Detayları - -GitIngest formatı, analiz edilmiş kod tabanı verisinden digest dosyasının oluşturulmasını düzenleyen `GitIngestFormatter` sınıfı aracılığıyla uygulanır. Uygulama, bağımlılıksız olacak ve çekirdek context-manager analiz hattı ile uyumlu olacak şekilde tasarlanmıştır. - -### Çekirdek Bileşenler -- **GitIngestFormatter Sınıfı**: Digest oluşturan ana formatter -- **Token Sayım Formatlama**: Ham token sayılarını insan tarafından okunabilir formatlara dönüştürür (k/M) -- **Ağaç Yapısı Oluşturucu**: Görsel dizin temsillerini oluşturur -- **Dosya İçerik İşlemcisi**: Dosya okuma ve içerik dahil etmeyi yönetir - -### İşleme Hattı -1. **Başlatma**: Proje kök dizinini, istatistikleri ve analiz sonuçlarını kabul eder -2. **Method Filtre Algılama**: Method seviyesi filtreleme yapılandırmasını otomatik olarak algılar -3. **Digest Oluşturma**: Özet, ağaç ve dosya içeriklerini birleştirir -4. **Çıktı**: Tam digest'i bir metin dosyasına kaydeder - -```mermaid -classDiagram -class GitIngestFormatter { -+string projectRoot -+object stats -+array analysisResults -+boolean methodFilterEnabled -+MethodAnalyzer methodAnalyzer -+MethodFilterParser methodFilter -+generateDigest() string -+generateSummary() string -+generateTree() string -+buildFileTree() object -+formatTreeNode(node, prefix, isLast) string -+generateFileContents() string -+generateFilteredFileContent(content, filePath) string -+extractMethodBlock(lines, startLine) string -+saveToFile(outputPath) number -} -class MethodAnalyzer { -+extractMethods(content, filePath) array -} -class MethodFilterParser { -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -} -GitIngestFormatter --> MethodAnalyzer : "uses" -GitIngestFormatter --> MethodFilterParser : "uses" -GitIngestFormatter --> TokenUtils : "uses format" -GitIngestFormatter --> FileUtils : "uses isCode" -``` - -**Diagram kaynakları** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [context-manager.js](file://context-manager.js#L4-L5) - -## Method Seviyesi Filtreleme - -GitIngest uygulaması, digest'e dahil edilen içerik üzerinde daha ayrıntılı kontrol sağlayan isteğe bağlı method seviyesi filtrelemeyi destekler. Bu özellik, geliştiricilerin boilerplate veya utility fonksiyonlarını hariç tutarken ilgi alanındaki belirli methodlara odaklanmasını sağlar. - -### Filtre Yapılandırması -- **.methodinclude**: INCLUDE modu - yalnızca belirtilen methodlar dahil edilir -- **.methodignore**: EXCLUDE modu - belirtilen methodlar hariç tutulur - -### Filtre Sözdizimi -| Desen | Açıklama | -|---------|-------------| -| `methodName` | Tam method adı eşleşmesi | -| `*pattern*` | Wildcard eşleştirme (desen içerir) | -| `Class.*` | Belirli bir sınıftaki tüm methodlar | -| `file.method` | Belirli bir dosyadaki belirli method | -| `!pattern` | Negasyon (deseni hariç tut) | - -Method filtreleme aktifken, digest her dosya içinde yalnızca filtrelenmiş methodları içerir ve hangi methodların dahil edildiğini gösteren metadata ile birlikte gelir. Bu seçici dahil etme, kritik işlevselliğe odaklanmayı korurken token kullanımını önemli ölçüde azaltır. - -```mermaid -sequenceDiagram -participant Formatter as GitIngestFormatter -participant Analyzer as MethodAnalyzer -participant Filter as MethodFilterParser -participant File as File System -Formatter->>Formatter : detectMethodFilters() -alt Method filtreleme etkin -Formatter->>Analyzer : extractMethods(content) -Formatter->>Filter : shouldIncludeMethod() -Formatter->>Formatter : generateFilteredContent() -loop Her dahil edilen method için -Formatter->>Formatter : extractMethodBlock() -Formatter->>Formatter : Metadata ile method ekle -end -else Tam dosya içeriği -Formatter->>File : readFileSync() -Formatter->>Formatter : Tam içeriği dahil et -end -Formatter->>Formatter : Tam digest'i döndür -``` - -**Diagram kaynakları** -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L200-L225) -- [gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L226-L257) - -## Pratik Örnekler - -GitIngest formatı, farklı kullanım senaryoları ve performans gereksinimleri için esneklik sağlayan birden fazla iş akışı aracılığıyla oluşturulabilir. - -### Doğrudan Oluşturma -Doğrudan kod tabanı analizinden bir digest oluşturun: -```bash -context-manager --gitingest -context-manager -g -``` - -### JSON Tabanlı Oluşturma -Mevcut JSON raporlarından digest oluşturun (daha hızlı, yeniden tarama yok): -```bash -# Detaylı analiz raporundan -context-manager --gitingest-from-report token-analysis-report.json - -# LLM context dosyasından -context-manager --gitingest-from-context llm-context.json - -# Varsayılan dosya adlarını kullanarak -context-manager --gitingest-from-report -context-manager --gitingest-from-context -``` - -### Kombine İş Akışları -Digest oluşturmayı diğer çıktılarla birleştirin: -```bash -# Hem digest hem de detaylı rapor oluştur -context-manager -g -s - -# Tekrarlanan digest oluşturma için iki adımlı iş akışı -context-manager --save-report -context-manager --gitingest-from-report -``` - -Çıktı `digest.txt` dosyası, LLM tüketimi veya arşivleme amaçları için hazır tam formatlanmış digest'i içerir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L170-L200) -- [test-gitingest-json.js](file://test/test-gitingest-json.js#L1-L225) - -## LLM Tüketim Kılavuzu - -LLM etkileşimleri için GitIngest formatının etkinliğini maksimize etmek için şu en iyi uygulamaları izleyin: - -### Optimal Kullanım Desenleri -- **Context Sağlama**: Tüm digest'i LLM ile konuşmanızın başında yapıştırın -- **Odaklanmış Sorgular**: Context sağladıktan sonra, mimari, uygulama veya iyileştirmeler hakkında belirli sorular sorun -- **Artımlı Analiz**: Çok büyük kod tabanları için, belirli alt sistemlere odaklanan birden fazla digest oluşturmayı düşünün - -### Önerilen Sorgu Türleri -- **Mimari Soruları**: "Dizin yapısına göre, ana mimari desen ne gibi görünüyor?" -- **Kod Anlama**: "[dosya]'nın amacını içeriğine ve projedeki pozisyonuna göre açıklayın" -- **İyileştirme Önerileri**: "Bu kod tabanındaki hata yönetimi deseninde potansiyel iyileştirmeleri belirleyin" -- **Dokümantasyon Oluşturma**: "Bu dosyalardaki export edilen methodlara dayalı API dokümantasyonu oluşturun" - -### Performans Değerlendirmeleri -- **Token Verimliliği**: Digest formatı, token limitleri içinde maksimum context sağlamak için optimize edilmiştir -- **Dosya Sıralaması**: Dosyalar, context pencerelerinde önemli dosyalara öncelik vermek için boyuta göre sıralanır (en büyük önce) -- **Method Filtreleme**: Belirli işlevselliğe odaklanırken token kullanımını daha da azaltmak için method seviyesi filtreleme kullanın - -**Bölüm kaynakları** -- [README.md](file://README.md#L190-L200) -- [GITINGEST_VERSION.md](file://docs/GITINGEST_VERSION.md#L1-L79) - -## Sorun Giderme - -GitIngest formatı ile çalışırken yaygın sorunlar ve çözümleri: - -### Dosya Oluşturma Sorunları -- **Digest oluşturulmadı**: Çıktı dizininin yazılabilir olduğundan ve yeterli izinlere sahip olduğunuzdan emin olun -- **Eksik dosyalar**: Dosyaların `.gitignore`, `.contextignore` veya diğer filtre kuralları tarafından hariç tutulmadığını doğrulayın -- **Boş digest**: Analizin dahil etme kriterlerine uyan dosyaları bulduğunu kontrol edin - -### Method Filtreleme Sorunları -- **Filtre uygulanmadı**: `.methodinclude` veya `.methodignore` dosyalarının proje kök dizininde var olduğundan emin olun -- **Beklenmeyen methodlar dahil edildi**: Desen sözdizimini gözden geçirin ve negasyon desenlerini kullanmayı düşünün -- **Hiçbir method gösterilmedi**: Method çıkarma desenlerinin kod stilinizle eşleştiğini doğrulayın (fonksiyon bildirimleri, arrow fonksiyonlar, vb.) - -### İçerik Kalitesi Sorunları -- **Kırpılmış methodlar**: Uygulama, güvenlik için method çıkarmayı 100 satırla sınırlar; çok uzun methodlar kırpılır -- **Encoding sorunları**: Okuma hatalarını önlemek için dosyaların UTF-8 encoding'inde kaydedildiğinden emin olun -- **Büyük digest boyutu**: Çıktı boyutunu azaltmak için method seviyesi filtreleme kullanın veya include/exclude desenlerini ayarlayın - -### JSON Kaynak Sorunları -- **Geçersiz JSON formatı**: Kaynak JSON dosyalarının rapor veya context dosyaları için beklenen yapıyı izlediğinden emin olun -- **Eksik alanlar**: Gerekli alanların (project, paths, files) kaynak JSON'da mevcut olduğunu doğrulayın -- **Yol çözümleme sorunları**: JSON dosyalarındaki göreli yolların doğru olduğundan ve dosyaların belirtilen konumlarda var olduğundan emin olun - -**Bölüm kaynakları** -- [test-gitingest-json.js](file://test/test-gitingest-json.js#L150-L180) -- [context-manager.js](file://context-manager.js#L20-L50) - -## Entegrasyon İş Akışları - -GitIngest formatı, geliştirme verimliliğini ve AI destekli kodlamayı artıran çeşitli entegrasyon iş akışlarını destekler. - -### Geliştirme İş Akışı Entegrasyonu -```mermaid -flowchart LR -A[Kod Değişiklikleri] --> B[Analiz Çalıştır] -B --> C{Export Seçimi} -C --> D[Rapor Kaydet] -C --> E[Context Oluştur] -C --> F[Digest Oluştur] -C --> G[Panoya Kopyala] -D --> H[Geçmiş için Arşivle] -E --> I[CI/CD Entegrasyonu] -F --> J[LLM Analizi] -G --> K[Anında AI Yardımı] -``` - -### CI/CD Pipeline Entegrasyonu -GitIngest oluşturmayı otomatik iş akışlarına entegre edin: -```bash -# CI/CD script'inde -npm run analyze -- --save-report -npm run gitingest -- --gitingest-from-report - -# Digest'i artifact olarak yükle -aws s3 cp digest.txt s3://project-artifacts/${GIT_COMMIT}/digest.txt -``` - -### İnteraktif Geliştirme Döngüsü -1. Kod değişiklikleri yapın -2. `context-manager --gitingest` çalıştırın -3. Digest içeriğini kopyalayın -4. LLM arayüzüne sorgu ile yapıştırın -5. Önerileri uygulayın -6. Tekrarlayın - -Bu sıkı geri bildirim döngüsü, AI yardımıyla hızlı iterasyon ve sürekli iyileştirmeyi mümkün kılar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L200-L220) -- [context-manager.js](file://context-manager.js#L100-L150) diff --git a/docs/content-tr/Hizli-Baslangic-Rehberi.md b/docs/content-tr/Hizli-Baslangic-Rehberi.md deleted file mode 100644 index 4ebed41..0000000 --- a/docs/content-tr/Hizli-Baslangic-Rehberi.md +++ /dev/null @@ -1,356 +0,0 @@ -# Hızlı Başlangıç Rehberi - - -**Bu Belgede Referans Verilen Dosyalar** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [bin/cli.js](file://bin/cli.js) - - -## İçindekiler -1. [Giriş](#giris) -2. [Temel İş Akışı](#temel-is-akisi) -3. [Aracı İnteraktif Olarak Çalıştırma](#araci-interaktif-olarak-calistirma) -4. [Analiz Çıktısını Anlama](#analiz-ciktisini-anlama) -5. [Export Seçenekleri ve Seçimi](#export-secenekleri-ve-secimi) -6. [Yaygın Kullanım Desenleri](#yaygin-kullanim-desenleri) -7. [Metod Seviyesi Analiz](#metod-seviyesi-analiz) -8. [Pano Entegrasyonu](#pano-entegrasyonu) -9. [Yapılandırma ve Desen Dosyaları](#yapilandirma-ve-desen-dosyalari) -10. [Yaygın Sorunları Giderme](#yaygin-sorunlari-giderme) - -## Giriş - -context-manager CLI aracı, kesin token sayımı, metod seviyesi filtreleme ve akıllı dosya seçimi sağlayarak LLM context'ini optimize etmek için tasarlanmıştır. Bu hızlı başlangıç rehberi, aracı çalışır hale getirmenize, temel işlevselliğini anlamanıza ve özelliklerini AI destekli geliştirme iş akışları için etkili bir şekilde kullanmanıza yardımcı olacaktır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) - -## Temel İş Akışı - -context-manager aracı basit üç adımlı bir iş akışı izler: analiz, çıktı yorumlama ve export seçimi. Araç, kod tabanınızı analiz ederek kesin token sayılarını hesaplar, dosya kompozisyonu ve token dağılımı hakkında detaylı bilgiler sunar ve sonuçları LLM tüketimi için uygun formatlarda export etmek için birden fazla seçenek sağlar. - -Varsayılan davranış interaktiftir, kullanıcılara süreç boyunca rehberlik eder ve komut satırı bayrakları aracılığıyla belirli bir export seçeneği belirtilmediğinde export tercihleri için sorgular. Bu, kullanıcıların mevcut ihtiyaçları için her zaman en uygun çıktı formatını seçebilmelerini sağlar. - -```mermaid -flowchart TD -Start([Run context-manager]) --> Analysis["Analyze codebase\nCalculate token counts"] -Analysis --> Output["Display analysis results\nToken statistics, file types,\nlargest files, directories"] -Output --> ExportDecision{"Export option\nspecified?"} -ExportDecision --> |No| InteractiveExport["Prompt user for export choice"] -ExportDecision --> |Yes| DirectExport["Execute specified export"] -InteractiveExport --> SaveReport["Save detailed JSON report"] -InteractiveExport --> ContextFile["Generate LLM context file"] -InteractiveExport --> Clipboard["Copy context to clipboard"] -InteractiveExport --> NoExport["Skip export"] -DirectExport --> SaveReport -DirectExport --> ContextFile -DirectExport --> Clipboard -SaveReport --> End([Complete]) -ContextFile --> End -Clipboard --> End -NoExport --> End -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L793-L813) -- [README.md](file://README.md#L0-L891) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L793-L813) -- [README.md](file://README.md#L0-L891) - -## Aracı İnteraktif Olarak Çalıştırma - -context-manager aracını interaktif olarak çalıştırmak için komutu herhangi bir bayrak olmadan çalıştırın: - -```bash -context-manager -``` - -Bu, analiz sürecini başlatır, .gitignore kurallarına ve calculator'a özgü ignore/include desenlerine uyarak proje dizininizi tarar, tüm ilgili dosyalar için token sayılarını hesaplar ve kapsamlı bir rapor görüntüler. Analiz tamamlandıktan sonra, bir export seçeneği belirtilmemişse, araç bir export yöntemi seçmenizi ister. - -İnteraktif mod, ilk kez kullanıcılar ve analiz sonuçlarına göre farklı export seçeneklerini keşfetmek isteyenler için idealdir. Araç, süreç boyunca net rehberlik sağlar ve hangi dosyaların analiz edildiğini ve token sayılarının nasıl hesaplandığını anlamayı kolaylaştırır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) - -## Analiz Çıktısını Anlama - -context-manager aracını çalıştırdığınızda, çeşitli önemli bilgi parçalarını içeren detaylı bir analiz raporu üretir. Çıktı, proje kök dizini, yapılandırma modu (INCLUDE veya EXCLUDE) ve token hesaplama yöntemi (tiktoken kullanarak kesin veya tahmini) dahil olmak üzere analiz süreci hakkında metadata ile başlar. - -Ana rapor şunları içerir: -- Analiz edilen toplam dosya sayısı ve toplam token sayısı -- MB cinsinden toplam boyut ve toplam kod satırı sayısı -- Dosya başına ortalama token sayısı -- .gitignore ve calculator kuralları tarafından göz ardı edilen dosya sayısı -- Dosya tipi (uzantı) bazında dökümü, dosyaları, token'ları, boyutu ve satırları gösterir -- Token sayısına göre en büyük 5 dosya -- Token sayısına göre en büyük 5 dizin - -Token sayılarını anlamak, LLM context yönetimi için çok önemlidir. Araç, mevcut olduğunda GPT-4 uyumlu kesin sayım için tiktoken kullanır, tiktoken kurulu değilse yaklaşık %95 doğrulukla tahmini yönteme geri döner. Verbose çıktı (varsayılan olarak etkin) tüm dahil edilen dosyaları gösterir ve token sayınıza neyin katkıda bulunduğu konusunda şeffaflık sağlar. - -```mermaid -flowchart TD -Start([Analysis Output]) --> Metadata["Metadata Section\nProject path, configuration mode,\ntoken calculation method"] -Metadata --> Summary["Summary Statistics\nTotal files, tokens, size,\nlines, average tokens per file"] -Summary --> IgnoredFiles["Ignored Files Count\n.gitignore exclusions,\ncalculator rule exclusions"] -IgnoredFiles --> FileTypeBreakdown["File Type Breakdown\nExtension, files, tokens,\nsize, lines"] -FileTypeBreakdown --> LargestFiles["Top 5 Largest Files\nBy token count with percentages"] -LargestFiles --> LargestDirectories["Top 5 Largest Directories\nBy token count with percentages"] -LargestDirectories --> Tip["Usage Tip\nSave detailed report option"] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L683-L703) -- [README.md](file://README.md#L0-L891) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L683-L703) -- [README.md](file://README.md#L0-L891) - -## Export Seçenekleri ve Seçimi - -context-manager aracı, farklı kullanım durumlarına uyum sağlamak için birden fazla export seçeneği sunar. Komut satırı bayrakları aracılığıyla bir export seçeneği belirtilmediğinde, araç interaktif export moduna girer ve kullanıcıdan dört seçenekten birini seçmesini ister: - -1. Detaylı JSON raporu kaydet (token-analysis-report.json) -2. LLM context dosyası oluştur (llm-context.json) -3. LLM context'ini panoya kopyala -4. Export'u atla - -İnteraktif export seçimi, kullanıcıların analiz sonuçlarını ihtiyaç duydukları formatta export etme fırsatını asla kaçırmamasını sağlar. Bu özellik, tüm mevcut export seçeneklerine aşina olmayan yeni başlayanlar için özellikle yararlıdır. - -Otomatik iş akışları için, interaktif istemi atlayarak export seçeneklerini doğrudan komut satırı bayrakları aracılığıyla belirtebilirsiniz. Mevcut bayraklar: -- `--save-report` veya `-s`: Detaylı bir JSON raporu kaydet -- `--context-export`: Bir LLM context dosyası oluştur -- `--context-clipboard`: Context'i doğrudan panoya kopyala - -```mermaid -stateDiagram-v2 -[*] --> AnalysisComplete -AnalysisComplete --> InteractiveMode : No export flags -AnalysisComplete --> DirectExport : Export flags specified -InteractiveMode --> SaveReport : User selects option 1 -InteractiveMode --> ContextFile : User selects option 2 -InteractiveMode --> Clipboard : User selects option 3 -InteractiveMode --> NoExport : User selects option 4 -DirectExport --> SaveReport : --save-report flag -DirectExport --> ContextFile : --context-export flag -DirectExport --> Clipboard : --context-clipboard flag -SaveReport --> Complete -ContextFile --> Complete -Clipboard --> Complete -NoExport --> Complete -Complete --> [*] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L575-L616) -- [bin/cli.js](file://bin/cli.js#L4-L25) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L575-L616) -- [bin/cli.js](file://bin/cli.js#L4-L25) - -## Yaygın Kullanım Desenleri - -context-manager aracı, farklı geliştirme iş akışlarına hitap eden çeşitli yaygın kullanım desenlerini destekler. En temel desen, aracı hiçbir bayrak olmadan interaktif olarak çalıştırmaktır; bu, tam bir analiz sağlar ve export seçenekleri için sorgular: - -```bash -context-manager -``` - -Hızlıca LLM context'i oluşturmak ve panoya kopyalamak isteyen kullanıcılar için, `--context-clipboard` bayrağı basitleştirilmiş bir iş akışı sağlar: - -```bash -context-manager --context-clipboard -``` - -Bu komut kod tabanını analiz eder ve optimize edilmiş context'i JSON formatında doğrudan panoya kopyalar, bir LLM arayüzüne yapıştırmaya hazır hale getirir. - -Bir diğer yaygın desen, tüm dosyalar yerine JavaScript/TypeScript dosyalarından belirli metodları çıkarma ve analiz etmeye odaklanan metod seviyesi analizdir: - -```bash -context-manager --method-level -``` - -Daha karmaşık iş akışları oluşturmak için birden fazla bayrağı da birleştirebilirsiniz. Örneğin, metod seviyesi analiz yapmak ve hem detaylı bir rapor kaydetmek hem de context'i bir dosyaya export etmek için: - -```bash -context-manager --method-level --save-report --context-export -``` - -Araç ayrıca, tüm dahil edilen dosyaları gösteren verbose çıktıyı (varsayılan olarak etkin) veya dosya listesini bastıran `--no-verbose` ile sessiz modu da destekler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) - -## Metod Seviyesi Analiz - -Metod seviyesi analiz, tüm dosyaları analiz etmek yerine kod tabanınızdaki belirli metodlara odaklanmanızı sağlayan güçlü bir özelliktir. Bu, özellikle LLM context optimizasyonu için kullanışlıdır, çünkü boilerplate ve yardımcı metodları hariç tutarken yalnızca en alakalı kod bölümlerini dahil etmenizi sağlar. - -Metod seviyesi analizini etkinleştirmek için `--method-level` bayrağını kullanın: - -```bash -context-manager --method-level -``` - -Metod seviyesi analiz etkinleştirildiğinde, araç fonksiyon bildirimleri, metod atamaları ve arrow fonksiyonlar için desen eşleştirme kullanarak JavaScript/TypeScript dosyalarından metodları çıkarır. Analiz, her metodun adı, satır numarası ve token sayısı hakkında bilgi içerir. - -Araç, yapılandırma dosyaları aracılığıyla metod filtrelemeyi destekler: -- `.methodinclude`: Yalnızca belirtilen metodları dahil et (önceliklidir) -- `.methodignore`: Belirtilen metodları hariç tut - -Bu dosyalar, tam metod adları, joker karakterlerle desenler (*), veya sınıf.metod notasyonu belirtebileceğiniz desen eşleştirme sözdizimini kullanır. Örneğin: - -``` -# .methodinclude - sadece bu metodları dahil et -calculateTokens -*Handler -*Validator -TokenCalculator.* -``` - -Metod seviyesi analiz, belirli işlevselliğe odaklanmanız gerektiğinde LLM context'ini yönetmeyi kolaylaştıran, dosyalar yerine metodlar tarafından organize edilmiş farklı bir çıktı formatı üretir. - -```mermaid -flowchart TD -Start([Method-Level Analysis]) --> EnableFlag["Use --method-level flag"] -EnableFlag --> MethodExtraction["Extract methods from JS/TS files\nusing regex patterns"] -MethodExtraction --> MethodFiltering["Apply method filtering rules\nfrom .methodinclude/.methodignore"] -MethodFiltering --> TokenCalculation["Calculate tokens for each method"] -TokenCalculation --> ContextGeneration["Generate method-level context\norganized by file path"] -ContextGeneration --> ExportOptions["Export via specified method\nreport, file, or clipboard"] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L118-L223) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L118-L223) - -## Pano Entegrasyonu - -context-manager aracı, `--context-clipboard` bayrağı ile oluşturulan LLM context'ini doğrudan sistem panonuza kopyalamanıza olanak tanıyan kusursuz pano entegrasyonu sağlar: - -```bash -context-manager --context-clipboard -``` - -Bu özellik, uygun sistem komutlarını (pbcopy, xclip/xsel veya clip) kullanarak platformlar arası (macOS, Linux ve Windows) çalışır. Araç, llm-context.json dosyasına kaydedilecek olanla aynı olan JSON formatında context'i kopyalar ve pano ile dosya export'ları arasında tutarlılık sağlar. - -Pano entegrasyonu, bir dosyaya kaydetmek ve manuel olarak kopyalamak zorunda kalmadan context'i LLM'lerle hızla paylaşmak için özellikle kullanışlıdır. Çıktı, temel bilgileri korurken karakter sayısını minimize eden varsayılan olarak compact bir format kullanarak LLM tüketimi için optimize edilmiştir. - -Pano işlemi başarısız olursa (örneğin, eksik sistem yardımcı programları nedeniyle), araç otomatik olarak context'i llm-context.json dosyasına kaydetmeye geri döner ve oluşturulan context'i kaybetmemenizi sağlar. - -```mermaid -sequenceDiagram -participant User as "User" -participant Tool as "context-manager" -participant System as "Operating System" -participant Clipboard as "System Clipboard" -User->>Tool : Run with --context-clipboard -Tool->>Tool : Analyze codebase and generate context -Tool->>Tool : Format context as JSON -Tool->>System : Execute platform-specific copy command -alt macOS -System->>Clipboard : pbcopy with context string -else Linux -System->>Clipboard : xclip or xsel with context string -else Windows -System->>Clipboard : clip with context string -end -Clipboard-->>Tool : Copy confirmation -alt Copy successful -Tool-->>User : "Context copied to clipboard!" -else Copy failed -Tool->>Tool : Save context to llm-context.json -Tool-->>User : "Failed to copy, saved to file instead" -end -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L541-L567) -- [README.md](file://README.md#L0-L891) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L541-L567) -- [README.md](file://README.md#L0-L891) - -## Yapılandırma ve Desen Dosyaları - -context-manager aracı, hangi dosya ve metodların analize dahil edileceğini kontrol etmek için birkaç yapılandırma dosyası kullanır. Bu dosyaları anlamak, aracı özel ihtiyaçlarınıza göre özelleştirmek için gereklidir. - -Dosya seviyesi filtreleme için birincil yapılandırma dosyaları: -- `.contextinclude`: Yalnızca belirtilen desenlere uyan dosyaları dahil et (önceliklidir) -- `.contextignore`: Belirtilen desenlere uyan dosyaları hariç tut - -Araç, yapılandırma dosyaları için bir öncelik sırası izler: -1. `.gitignore` (her zaman geçerlidir) -2. `.contextinclude` (dosyalar için en yüksek öncelik) -3. `.contextignore` (include dosyası yokken kullanılır) - -`.contextinclude` mevcut olduğunda, araç INCLUDE modunda çalışır, yani yalnızca include desenlerine uyan dosyalar analiz edilir (.gitignore tarafından hariç tutulanlar hariç). Yalnızca `.contextignore` mevcut olduğunda, araç EXCLUDE modunda çalışır ve ignore desenlerine uyan dosyalar hariç tüm dosyaları analiz eder. - -Metod seviyesi analiz için araç şunları kullanır: -- `.methodinclude`: Yalnızca belirtilen metodları dahil et -- `.methodignore`: Belirtilen metodları hariç tut - -Bu dosyalar, joker karakterlerle (*) desen eşleştirmeyi destekler ve tam metod adları, desenler veya sınıf.metod notasyonu belirtebilir. Sözdizimi basittir; her satır bir deseni temsil eder ve # ile başlayan satırlar yorum olarak değerlendirilir. - -```mermaid -graph TB -subgraph "Configuration Priority" -A[".gitignore"] -B[".contextinclude"] -C[".contextignore"] -end -subgraph "Method Filtering" -D[".methodinclude"] -E[".methodignore"] -end -A --> |Always respected| Analysis["Code Analysis"] -B --> |Takes priority| Analysis -C --> |Used if no include file| Analysis -D --> |Method-level include| Analysis -E --> |Method-level exclude| Analysis -style A fill:#f9f,stroke:#333 -style B fill:#f9f,stroke:#333 -style C fill:#f9f,stroke:#333 -style D fill:#bbf,stroke:#333 -style E fill:#bbf,stroke:#333 -style Analysis fill:#9f9,stroke:#333 -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L118-L223) -- [README.md](file://README.md#L0-L891) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L118-L223) -- [README.md](file://README.md#L0-L891) - -## Yaygın Sorunları Giderme - -context-manager aracına başlarken birkaç yaygın sorunla karşılaşabilirsiniz. Bunları ve çözümlerini anlamak, aracı daha etkili kullanmanıza yardımcı olacaktır. - -**Verbose çıktıyı anlama**: Aracın verbose çıktısı (varsayılan olarak etkin) yeni başlayanlar için bunaltıcı olabilir. Tüm dahil edilen dosyaları, token sayılarını ve detaylı istatistikleri gösterir. Çıktıyı azaltmak için `--no-verbose` bayrağını kullanın, ancak hangi dosyaların analiz edildiği konusunda şeffaflığı azalttığı için bu önerilmez. - -**Token sayılarını yorumlama**: Araç, mevcut olduğunda kesin token sayımı için tiktoken kullanır. tiktoken'ı kurmadıysanız, araç tahmin moduna geri döner. Kesin sayımları sağlamak için tiktoken'ı kurun: -```bash -npm install tiktoken -``` - -**Yapılandırma dosyası sorunları**: Yaygın bir kafa karışıklığı kaynağı, `.contextinclude` ve `.contextignore` arasındaki etkileşimdir. Unutmayın ki `.contextinclude` önceliklidir - mevcutsa, araç INCLUDE modunda çalışır ve `.contextignore`'u göz ardı eder. Beklenen dosyaları görmüyorsanız, bir `.contextinclude` dosyasının var olup olmadığını kontrol edin. - -**Desen eşleştirme sorunları**: Yapılandırma dosyalarında desenler oluştururken, satır içi yorumların olmadığından ve desenlerin doğru sözdizimini kullandığından emin olun. Özyinelemeli eşleştirme için `**`, tek seviyeli eşleştirme için `*` kullanın. Desenlerin beklendiği gibi çalıştığını doğrulamak için verbose çıktı ile test edin. - -**Metod seviyesi analiz sorunları**: Metod seviyesi analiz kullanırken, `.methodinclude` veya `.methodignore` dosyalarınızın doğru konumda (proje kök dizini veya araç dizini) olduğundan ve doğru desen sözdizimini kullandığından emin olun. Araç, hangi modun etkin olduğunu çıktıda belirtir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [context-manager.js](file://context-manager.js#L793-L813) diff --git a/docs/content-tr/Katki-Rehberi.md b/docs/content-tr/Katki-Rehberi.md deleted file mode 100644 index 8f05819..0000000 --- a/docs/content-tr/Katki-Rehberi.md +++ /dev/null @@ -1,267 +0,0 @@ -# Katkı Rehberi - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) -- [test/test.js](file://test/test.js) -- [test/test-suite.js](file://test/test-suite.js) -- [package.json](file://package.json) - - -## İçindekiler -1. [Giriş](#giriş) -2. [Geliştirme İş Akışı](#geliştirme-iş-akışı) -3. [Kod Yapısı ve Mimari](#kod-yapısı-ve-mimari) -4. [Test Stratejisi](#test-stratejisi) -5. [Katkı Rehberleri](#katkı-rehberleri) -6. [Kodlama Standartları](#kodlama-standartları) -7. [Aracı Genişletme](#aracı-genişletme) -8. [Sonuç](#sonuç) - -## Giriş -context-manager projesi, method seviyesinde filtreleme ve token analiz yeteneklerine sahip bir LLM context optimizasyon aracıdır. Bu rehber, katkıda bulunanlara geliştirme iş akışını, kod yapısını, test stratejisini ve katkı rehberlerini anlamaları için kapsamlı bilgi sağlar. Araç, geliştiricilerin kod tabanlarını analiz etmelerine ve tiktoken (GPT-4 uyumlu) kullanarak kesin token sayıları hesaplayarak AI asistanları için optimize edilmiş context oluşturmalarına yardımcı olmak üzere tasarlanmıştır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) - -## Geliştirme İş Akışı - -### Yerel Ortamı Kurma -context-manager için yerel geliştirme ortamını kurmak için şu adımları izleyin: - -1. Repoyu GitHub'dan klonlayın -2. `npm install` kullanarak bağımlılıkları yükleyin -3. Kesin token sayımı için tiktoken'ı yükleyin: `npm install tiktoken` - -Araç hem global CLI aracı hem de programatik olarak kullanılabilir. Paket, Node.js sürüm 14.0.0 veya üstü ile çalışacak şekilde yapılandırılmıştır. - -### Testleri Çalıştırma -Proje, npm scriptleri kullanılarak çalıştırılabilen kapsamlı bir test paketi içerir: - -```bash -npm test # Temel testleri çalıştır -npm run test:all # Kapsamlı test paketini çalıştır -``` - -Test paketi, dosya seviyesinde analiz, method seviyesinde analiz, dosya ve panoya context export'u, detaylı rapor oluşturma ve çeşitli CLI seçenekleri dahil olmak üzere core fonksiyonelliği doğrular. - -### Pull Request Gönderme -Pull request gönderirken, şunlardan emin olun: -- Tüm testler başarıyla geçer -- Kod, belirlenen kodlama standartlarına uyar -- Yeni özellikler uygun testlerle birlikte gelir -- Dokümantasyon değişiklikleri yansıtacak şekilde güncellenir -- prepublishOnly scripti başarıyla çalışır, bu yayınlamadan önce testleri çalıştırır - -**Bölüm kaynakları** -- [package.json](file://package.json#L0-L55) -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Kod Yapısı ve Mimari - -### Modüler, Sınıf Tabanlı Tasarım -context-manager projesi, net sorumluluk ayrımı ile modüler, sınıf tabanlı bir tasarım desenini takip eder. Mimari, aracın fonksiyonelliğini sağlamak için birlikte çalışan birkaç core bileşenden oluşur. - -```mermaid -classDiagram -class TokenCalculator { -+projectRoot string -+options object -+stats object -+gitIgnore GitIgnoreParser -+methodAnalyzer MethodAnalyzer -+methodFilter MethodFilterParser -+run() void -+scanDirectory(dir) string[] -+analyzeFile(filePath) object -+generateLLMContext(analysisResults) object -} -class GitIgnoreParser { -+patterns string[] -+calculatorPatterns string[] -+hasIncludeFile boolean -+isIgnored(filePath, relativePath) boolean -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) void -} -class MethodAnalyzer { -+extractMethods(content, filePath) object[] -+getLineNumber(content, index) number -+isKeyword(name) boolean -+extractMethodContent(content, methodName) string -} -class MethodFilterParser { -+includePatterns object[] -+ignorePatterns object[] -+hasIncludeFile boolean -+shouldIncludeMethod(methodName, fileName) boolean -} -TokenCalculator --> GitIgnoreParser : "kullanır" -TokenCalculator --> MethodAnalyzer : "kullanır" -TokenCalculator --> MethodFilterParser : "kullanır" -MethodAnalyzer --> MethodFilterParser : "filtreleme için methodlar sağlar" -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L231-L800) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L14-L73) -- [context-manager.js](file://context-manager.js#L75-L115) - -### Core Bileşenler -Sistemin ana bileşenleri şunlardır: - -- **TokenCalculator**: Analiz sürecini yöneten, dosya taramayı, token sayımını ve rapor oluşturmayı koordine eden birincil orkestratör -- **GitIgnoreParser**: Analize hangi dosyaların dahil edileceğini veya hariç tutulacağını belirlemek için .gitignore, .contextignore ve .contextinclude dosyaları için desen eşleştirmesini yönetir -- **MethodAnalyzer**: Regex desenleri kullanarak JavaScript/TypeScript dosyalarından methodları çıkarır ve bireysel methodlar için token sayılarını hesaplar -- **MethodFilterParser**: .methodinclude ve .methodignore konfigürasyon dosyalarında tanımlanan kurallara göre methodları filtreler - -Bu bileşenler, modül giriş noktası olarak hizmet eden ve programatik kullanım için tüm core sınıfları export eden index.js dosyası aracılığıyla açığa çıkarılır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L864) -- [index.js](file://index.js#L0-L7) - -## Test Stratejisi - -### Test Dizin Yapısı -Test dizini iki birincil test dosyası içerir: - -- **test.js**: Core bileşenlerin örneklenebileceğini ve temel işlemlerin doğru çalıştığını doğrulayan temel fonksiyonellik testleri -- **test-suite.js**: Entegrasyon testleri aracılığıyla aracın fonksiyonelliğinin çeşitli yönlerini doğrulayan kapsamlı test paketi - -### Test Kapsamı -Test stratejisi birkaç temel alana odaklanır: - -1. **Temel fonksiyonellik**: Core sınıfların örneklenebileceğini ve temel işlemlerin çalıştığını doğrular -2. **Paket yapısı**: Modül export'larının doğru yapılandırıldığından emin olur -3. **Dosya seviyesinde analiz**: Dosyaları analiz etme ve rapor oluşturma yeteneğini test eder -4. **Method seviyesinde analiz**: Method çıkarma ve analiz yeteneklerini doğrular -5. **Context export**: Hem dosya hem de pano export fonksiyonelliğini test eder -6. **Rapor oluşturma**: Detaylı JSON raporlarının doğru oluşturulduğunu doğrular -7. **CLI arayüzü**: Komut satırı arayüzü seçeneklerini ve davranışını doğrular -8. **Hata yönetimi**: Aracın geçersiz girdileri ve kenar durumlarını nasıl ele aldığını test eder -9. **Method çıkarma doğruluğu**: Methodların koddan doğru şekilde tanımlandığını ve çıkarıldığını sağlar - -Test paketi CLI arayüzünü test etmek için child process yürütme kullanır ve fonksiyonelliği onaylamak için çıktının beklenen stringleri içerdiğini doğrular. - -```mermaid -flowchart TD -Start([Test Yürütme]) --> BasicFunctionality["Temel Fonksiyonelliği Test Et"] -BasicFunctionality --> PackageStructure["Paket Yapısını Test Et"] -PackageStructure --> FileLevelAnalysis["Dosya Seviyesinde Analizi Test Et"] -FileLevelAnalysis --> MethodLevelAnalysis["Method Seviyesinde Analizi Test Et"] -MethodLevelAnalysis --> ContextExport["Context Export'unu Test Et"] -ContextExport --> ReportGeneration["Rapor Oluşturmayı Test Et"] -ReportGeneration --> CLIInterface["CLI Arayüzünü Test Et"] -CLIInterface --> ErrorHandling["Hata Yönetimini Test Et"] -ErrorHandling --> MethodAccuracy["Method Çıkarma Doğruluğunu Test Et"] -MethodAccuracy --> Results["Test Sonuçları Özetini Oluştur"] -Results --> End([Test Tamamlandı]) -``` - -**Diyagram kaynakları** -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -**Bölüm kaynakları** -- [test/test.js](file://test/test.js#L0-L61) -- [test/test-suite.js](file://test/test-suite.js#L0-L280) - -## Katkı Rehberleri - -### Hata Raporları -Hata bildirirken lütfen şunları dahil edin: -- Sorunun net bir açıklaması -- Sorunu yeniden oluşturma adımları -- Beklenen davranış vs. gerçek davranış -- Ortam bilgisi (Node.js sürümü, işletim sistemi) -- İlgili hata mesajları veya stack trace'ler -- Uygulanabilirse ekran görüntüleri - -### Özellik İstekleri -Özellik istekleri için şunları sağlayın: -- İstenen fonksiyonelliğin detaylı açıklaması -- Özelliğin faydalı olacağı kullanım senaryoları ve senaryolar -- İlgili örnekler veya referanslar -- Biliniyorsa potansiyel uygulama yaklaşımları -- Kullanıcılar için beklenen faydalar - -### Kod Katkıları -Kod katkısında bulunurken: -1. Repoyu fork edin ve bir özellik branch'i oluşturun -2. Kodunuzun belirlenen kodlama standartlarına uyduğundan emin olun -3. Yeni fonksiyonellik için uygun testler yazın -4. Dokümantasyonu gerektiği gibi güncelleyin -5. Değişikliklerin net bir açıklamasıyla bir pull request gönderin -6. Pull request açıklamasında ilgili issue'lara referans verin - -Proje, güvenilirliği sağlamak ve regresyonları önlemek için yüksek test kapsamını korur. Tüm katkılar bu kapsamı korumalı veya geliştirmelidir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L0-L891) -- [package.json](file://package.json#L0-L55) - -## Kodlama Standartları - -### Kod Stili -Proje şu kodlama standartlarını takip eder: -- Core bileşenler için ES6 sınıf sözdizimi -- Regex tabanlı parsing (AST bağımlılıkları yok) -- Zarif fallback'ler (tiktoken opsiyonel, pano için dosyaya fallback) -- Minimum bağımlılıklar (yalnızca tiktoken opsiyonel olarak) -- TypeScript yok, maksimum taşınabilirlik için saf JavaScript -- Tutarlı isimlendirme kuralları -- Karmaşık mantık için kapsamlı yorumlama -- Uygun fallback'ler ile hata yönetimi - -### Commit Mesaj Kuralları -Proje geleneksel commit mesaj formatlamasını takip eder: -- Emir kipi kullanın ("fix", "add", "remove", "update") -- İlk satırı 72 karakterle sınırlayın -- Konu ile gövde arasına boş satır ekleyin -- Ne ve neden vs. nasıl açıklamak için gövdeyi kullanın -- Uygulanabilir olduğunda issue'lara ve pull request'lere referans verin - -### Kod İnceleme Süreci -Kod inceleme süreci şunları içerir: -1. prepublishOnly scripti aracılığıyla otomatik test -2. Kod kalitesinin ve standartlara uygunluğun manuel incelemesi -3. Test kapsamının doğrulanması -4. Dokümantasyon güncellemelerinin değerlendirilmesi -5. Farklı ortamlarda fonksiyonelliğin test edilmesi -6. Potansiyel güvenlik açıkları için güvenlik incelemesi - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L864) -- [package.json](file://package.json#L0-L55) - -## Aracı Genişletme - -### Yeni Özellikler Ekleme -Aracı yeni özelliklerle genişletmek için: -1. Yeni fonksiyonellik için uygun bileşeni belirleyin -2. Mevcut tasarım desenlerini ve kodlama standartlarını takip edin -3. Kapsamlı testlerle özelliği uygulayın -4. Yeni yetenekleri yansıtmak için dokümantasyonu güncelleyin -5. Mümkün olduğunda geriye dönük uyumluluğu sağlayın - -### Yeni Çıktı Formatları Ekleme -Yeni çıktı formatları eklemek için: -1. TokenCalculator sınıfındaki generateLLMContext methodunu genişletin -2. Belirli format için yeni bir method oluşturun -3. Yeni formatı etkinleştirmek için uygun CLI seçenekleri ekleyin -4. Yeni çıktı formatı için testler uygulayın -5. Yeni formatın örnekleriyle dokümantasyonu güncelleyin - -Araç şu anda detaylı JSON raporları, LLM context dosyaları ve pano entegrasyonu dahil olmak üzere birden fazla çıktı formatını desteklemektedir. Yeni formatlar, AI asistanları için yararlı olan yapılandırılmış, makine tarafından okunabilir çıktı sağlamanın aynı prensiplerini takip etmelidir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L231-L800) -- [bin/cli.js](file://bin/cli.js#L0-L66) - -## Sonuç -context-manager projesi, kod tabanlarını analiz etmek ve AI asistanları için optimize edilmiş context oluşturmak için sağlam bir temel sağlar. Bu dokümanda özetlenen rehberleri takip ederek, katkıda bulunanlar aracın geliştirilmesine etkili bir şekilde katılabilir, projenin mimarisi ve hedefleriyle uyumlu yüksek kaliteli katkılar sağlayabilirler. Modüler, sınıf tabanlı tasarım, kod kalitesini ve test kapsamını korurken aracı yeni özellikler veya çıktı formatları ile genişletmeyi nispeten basit hale getirir. diff --git a/docs/content-tr/Kullanim-Senaryolari.md b/docs/content-tr/Kullanim-Senaryolari.md deleted file mode 100644 index 0ca3b4c..0000000 --- a/docs/content-tr/Kullanim-Senaryolari.md +++ /dev/null @@ -1,98 +0,0 @@ -# Kullanım Senaryoları - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [README.md](file://README.md) -- [context-manager.js](file://context-manager.js) -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) - - -## İçindekiler -1. [LLM Context Optimizasyonu](#llm-context-optimizasyonu) -2. [Kod Tabanı Analizi](#kod-tabanı-analizi) -3. [CI/CD Entegrasyonu](#cicd-entegrasyonu) -4. [Yaygın Zorluklar ve Çözümler](#yaygın-zorluklar-ve-çözümler) -5. [En İyi Uygulamalar ve Performans Değerlendirmeleri](#en-iyi-uygulamalar-ve-performans-değerlendirmeleri) - -## LLM Context Optimizasyonu - -context-manager aracı, odaklanmış context dosyaları oluşturarak ve gerekli olmayan kodu filtreleyerek AI asistanları için token bütçelerinin verimli yönetimini sağlar. İki temel operasyon modunu destekler: EXCLUDE modu (`.contextignore` aracılığıyla) ve INCLUDE modu (`.contextinclude` aracılığıyla), ikincisi öncelik alır. Bu ikili filtreleme sistemi, hangi dosyaların analize dahil edileceği üzerinde kesin kontrol sağlar ve geliştiricilerin yalnızca temel uygulama mantığına odaklanmalarına izin verir. - -LLM context export'u için araç iki format sağlar: ultra-compact format (~2.3k karakter) ve detailed format (~8.6k karakter). Compact format, programatik işleme ve AI tüketimi için ideal yapılandırılmış JSON çıktısı oluştururken, detailed format dosya kategorileri ve önem skorları gibi ek metadata içerir. `--context-clipboard` veya `--context-export` seçenekleri kullanıldığında, araç token sayıları olmadan temiz bir dizin yapısı çıktısı verir, sık AI etkileşimleri için uygundur. - -Method seviyesinde filtreleme, `.methodinclude` ve `.methodignore` konfigürasyon dosyaları aracılığıyla context optimizasyonunu daha da geliştirir. Bunlar, geliştiricilerin adlandırma desenlerine dayalı olarak belirli methodları dahil etmesine veya hariç tutmasına izin vererek son derece hedeflenmiş analizi mümkün kılar. Örneğin, `.methodinclude`'da `*Handler`, `*Validator` veya `TokenCalculator.*` belirtmek context'i kritik iş mantığı bileşenlerine odaklar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## Kod Tabanı Analizi - -context-manager aracı, kod tabanı genelinde token dağılımı hakkında kapsamlı içgörüler sağlar, büyük dosya ve methodları tanımlar ve karmaşıklığı zaman içinde izler. tiktoken aracılığıyla kesin token sayımı kullanarak (GPT-4 uyumlu), optimal kod sağlığını korumaya yardımcı olan doğru metrikler sunar. tiktoken yokluğunda, araç ~%95 doğrulukla akıllı tahmine geri döner. - -Temel analitik özellikler şunları içerir: -- **Dosya türüne göre token dağılımı**: Uzantı başına tokenlerin detaylı dökümü -- **En büyük dosyaların tanımlanması**: Token sayısına göre sıralanmış ilk 5 en büyük dosya -- **Dizin seviyesinde istatistikler**: Üst düzey dizinlere göre toplanmış token kullanımı -- **Method seviyesinde analiz**: JavaScript/TypeScript dosyalarından bireysel methodların çıkarılması ve analizi - -Araç, analiz edilen toplam dosyaları, toplam tokenleri, dosya başına ortalama tokenleri ve `.gitignore` veya calculator kuralları nedeniyle göz ardı edilen dosyaları gösteren detaylı bir rapor oluşturur. Bu bilgi, proje karmaşıklığını anlamak ve potansiyel refactoring fırsatlarını belirlemek için kritiktir. `--save-report` seçeneği bu verileri `token-analysis-report.json`'a export eder, geçmiş izleme ve trend analizini mümkün kılar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## CI/CD Entegrasyonu - -context-manager aracı, otomatik kod boyutu izleme, kalite kapıları ve dokümantasyon oluşturma için CI/CD pipeline'larına sorunsuzca entegre edilebilir. Komut satırı arayüzü, interactive olmayan yürütmeyi destekler, pre-commit hook'larında, günlük izleme scriptlerinde ve sürekli entegrasyon iş akışlarında kullanım için uygundur. - -Yaygın entegrasyon desenleri şunları içerir: -- **Pre-commit hook'ları**: AI incelemesi için yalnızca gerekli kodun dikkate alındığından emin olmak için commit'lerden önce `context-manager --context-clipboard` çalıştırma -- **Günlük izleme scriptleri**: Trend takibi için günlük analiz raporları oluşturmak üzere `context-manager --save-report` çalıştırma -- **Kalite kapıları**: Scriptable çıktı kullanarak pipeline'larda token bütçesi kontrollerini uygulama (örneğin, maksimum token limitlerini uygulamak için JSON çıktısını parse etme) -- **Otomatik dokümantasyon**: Mevcut kod tabanı yapısını yansıtan güncel context dosyaları oluşturma - -Interactive export seçimi özelliği, kullanıcılardan detaylı JSON raporu kaydetme, LLM context dosyası oluşturma, context'i panoya kopyalama veya export'u atlama arasında seçim yapmalarını ister—farklı kullanım senaryolarında esneklik sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [bin/cli.js](file://bin/cli.js#L1-L67) - -## Yaygın Zorluklar ve Çözümler - -context-manager aracını kullanırken, özellikle konfigürasyon ve filtreleme davranışı etrafında birkaç yaygın zorluk ortaya çıkar: - -**Include vs Exclude Mod Karışıklığı**: `.contextinclude`'ın varlığı `.contextignore` üzerinde öncelik alır. Beklenmeyen dosyalar dahil ediliyorsa veya hariç tutuluyorsa, hangi konfigürasyon dosyasının mevcut olduğunu doğrulayın ve istenmeyen olanı kaldırın. - -**Desen Eşleştirme Sorunları**: Desen dosyalarında satır içi yorumların bulunmadığından emin olun, çünkü bunlar parse etmeyi engelleyebilir. Doğru glob desenlerini kullanın (`docs/` yerine `docs/**`) ve verbose mod ile konfigürasyonları test ederek dahil etme/hariç tutma nedenlerini görün. - -**Token Sayımı Tutarsızlıkları**: Token sayıları çok yüksek veya düşük görünüyorsa, önemli dosyaların `.gitignore` veya calculator kuralları tarafından hariç tutulup tutulmadığını kontrol edin. Hangi dosyaların işlendiğini incelemek için `--verbose` kullanın. - -**Eksik Beklenen Dosyalar**: Dosyalar `.gitignore` kuralları (her zaman saygı gösterilir) veya yanlış desen sözdizimi nedeniyle hariç tutulabilir. Dosyaların metin dosyaları olarak tanındığını doğrulayın ve hariç tutma nedenlerini belirlemek için verbose modunu kullanın. - -**Pano Fonksiyonelliği Başarısızlıkları**: Linux sistemlerinde, pano işlemleri için `xclip` veya `xsel`'in yüklü olduğundan emin olun. Araç, biri başarısız olursa otomatik olarak her iki yardımcı programı dener. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) - -## En İyi Uygulamalar ve Performans Değerlendirmeleri - -context-manager aracını kullanırken verimliliği maksimize etmek için şu en iyi uygulamaları izleyin: - -**Konfigürasyon Yönetimi**: Özellikle büyük repolarda analiz kapsamı üzerinde kesin kontrol için `.contextinclude` kullanın. Desenleri basit tutun ve bunları aşamalı olarak test edin. - -**Performans Optimizasyonu**: Araç performans için optimize edilmiştir, ancak çok büyük kod tabanlarını analiz etmek, işleme yükünü azaltmak için method seviyesinde filtrelemeden faydalanabilir. Method seviyesinde analizi yalnızca gerekli olduğunda etkinleştirin. - -**Kesin Token Sayımı**: GPT-4 uyumlu kesin token sayımı için `tiktoken` paketini yükleyin (`npm install tiktoken`). Onsuz, araç ~%95 doğrulukla tahmin kullanır. - -**Düzenli İzleme**: Kod tabanı büyümesi ve karmaşıklık eğilimleri hakkında farkındalığı sürdürmek için aracı pre-commit hook'ları veya planlı scriptler aracılığıyla düzenli geliştirme iş akışlarına entegre edin. - -**Çıktı Kullanımı**: Hem compact hem de detailed çıktı formatlarını uygun şekilde kullanın—AI etkileşimleri için compact JSON ve mimari planlama ve adaptasyon için detailed raporları kullanın. - -**Method Seviyesinde Filtreleme**: Hata ayıklama veya kod incelemeleri sırasında temel iş mantığına odaklanmak, bilişsel yükü azaltmak ve analiz alaka düzeyini artırmak için `.methodinclude` ve `.methodignore` dosyalarını kullanın. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L891) -- [context-manager.js](file://context-manager.js#L1-L865) diff --git a/docs/content-tr/Kurulum.md b/docs/content-tr/Kurulum.md deleted file mode 100644 index f22b9b7..0000000 --- a/docs/content-tr/Kurulum.md +++ /dev/null @@ -1,290 +0,0 @@ -# Kurulum - - -**Bu Belgede Referans Verilen Dosyalar** -- [README.md](file://README.md) -- [package.json](file://package.json) -- [bin/cli.js](file://bin/cli.js) -- [context-manager.js](file://context-manager.js) - - -## İçindekiler -1. [Gereksinimler](#gereksinimler) -2. [Kurulum Yöntemleri](#kurulum-yontemleri) -3. [Token Sayım Yapılandırması](#token-sayim-yapılandırması) -4. [Yapılandırma Dosyaları](#yapılandırma-dosyaları) -5. [Doğrulama ve Kullanım](#dogrulama-ve-kullanım) -6. [Geliştirme İş Akışları ile Entegrasyon](#gelistirme-is-akislari-ile-entegrasyon) -7. [Sorun Giderme](#sorun-giderme) - -## Gereksinimler - -context-manager aracını kurmadan önce, sisteminizin aşağıdaki gereksinimleri karşıladığından emin olun: - -- **Node.js**: Sürüm 14.0.0 veya üzeri (package.json dosyasında "engines" altında belirtilmiştir) -- **npm**: Node Package Manager, genellikle Node.js ile birlikte kurulur - -Bu gereksinimler, paketin hem global hem de yerel kurulumları için gereklidir. Araç, Node.js'in çapraz platform yeteneklerinden yararlanarak tutarlı davranış için macOS, Linux ve Windows dahil farklı işletim sistemlerinde çalışacak şekilde tasarlanmıştır. - -**Bölüm kaynakları** -- [package.json](file://package.json#L15-L17) - -## Kurulum Yöntemleri - -context-manager aracı, npm kullanılarak iki temel yöntemle kurulabilir: global veya yerel. Her yöntem, geliştirme iş akışınıza bağlı olarak farklı kullanım durumlarına hizmet eder. - -### Global Kurulum - -Global kurulum, `context-manager` komutunu sistem genelinde kullanılabilir hale getirir ve terminalinizde herhangi bir dizinden kullanmanıza olanak tanır: - -```bash -npm install -g @hakkisagdic/context-manager -``` - -Bu yaklaşım, aracı birden fazla proje genelinde kullanmayı planlıyorsanız veya sisteminizde herhangi bir yerden bağımsız bir CLI aracı olarak erişmek istiyorsanız önerilir. Global kurulumdan sonra, `context-manager` komutlarını `npx` ile öneklendirmeden doğrudan çalıştırabilirsiniz. - -### Yerel Kurulum - -Yerel kurulum, paketi mevcut projenize bir bağımlılık olarak ekler: - -```bash -npm install @hakkisagdic/context-manager -``` - -Bu yöntem, context-manager'ı belirli bir projenin araç zincirinin parçası olarak dahil etmek istediğinizde veya tutarlı araç sürümlerinin önemli olduğu bir ekip ortamında çalışırken idealdir. Yerel kurulumda, aracı `npx` kullanarak çalıştırabilirsiniz: - -```bash -npx context-manager --help -``` - -Yerel kurulum, tüm ekip üyelerinin projenin package-lock.json dosyasında tanımlandığı gibi aynı araç sürümünü kullanmasını sağlayarak geliştirme ortamları arasında tutarlılığı destekler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L235-L245) - -## Token Sayım Yapılandırması - -context-manager aracı, doğruluğu artıran isteğe bağlı bir bağımlılıkla birlikte token sayımı için iki yöntem sağlar. - -### tiktoken ile Kesin Token Sayımı - -GPT-4'ün tokenizasyonuyla eşleşen hassas token sayımı için tiktoken paketini kurun: - -```bash -npm install tiktoken -``` - -tiktoken mevcut olduğunda, araç cl100k_base encoding'i (GPT-4 tarafından kullanılır) yükleyerek kesin token sayımı kullanır. Bu, LLM context yönetimi için en doğru token sayımlarını sağlar. - -### Akıllı Tahmine Geri Dönüş - -tiktoken kurulu değilse, araç otomatik olarak yaklaşık %95 doğrulukla akıllı bir tahmin algoritmasına geri döner. Tahmin, dosya tiplerine özgü karakter-token oranlarını kullanır: - -- JavaScript/TypeScript: Token başına 3.2 karakter -- JSON: Token başına 2.5 karakter -- Markdown: Token başına 4.0 karakter -- HTML/XML: Token başına 2.8 karakter -- Diğer metin dosyaları: Token başına 3.5 karakter - -Araç önce tiktoken'ı yüklemeye çalışır ve başarısız olursa tahmini yöntemi kullanır. Bu, TokenCalculator sınıfının `calculateTokens` metodunda uygulanmıştır; tiktoken'ı require etmeye çalışır ve tahmini yönteme geri dönmek için hataları yakalar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L219-L223) -- [context-manager.js](file://context-manager.js#L287-L317) - -## Yapılandırma Dosyaları - -context-manager aracı, dosya ve metod dahil etme/hariç tutma kontrolü için tanımlı bir öncelik hiyerarşisi ile birkaç yapılandırma dosyası kullanır. - -### Dosya Seviyesi Yapılandırma - -#### .contextignore (EXCLUDE Modu) -Bu dosya, analizden hariç tutulacak dosyalar için desenler içerir. gitignore-tarzı sözdizimi kullanır: -```bash -**/*.md # Tüm dokümantasyon -**/*.json # Tüm yapılandırma dosyaları -infrastructure/** # Altyapı kodu -``` - -#### .contextinclude (INCLUDE Modu) -Bu dosya, analize dahil edilecek dosyalar için desenler belirtir ve .contextignore'dan önceliklidir: -```bash -utility-mcp/src/**/*.js -!utility-mcp/src/workflows/** -``` - -### Metod Seviyesi Yapılandırma - -#### .methodinclude -Metod seviyesi analizine dahil edilecek metodları tanımlar: -```bash -calculateTokens -*Handler -TokenCalculator.* -``` - -#### .methodignore -Analizden hariç tutulacak metodları belirtir: -```bash -*test* -*debug* -console -``` - -### Yapılandırma Öncelik Hiyerarşisi - -Araç, hangi dosya ve metodların analiz edileceğini belirlerken katı bir öncelik sırası izler: - -1. **`.gitignore`** - Her zaman geçerlidir (proje kök dizini) -2. **`.contextinclude`** - Dosyalar için en yüksek öncelik (INCLUDE modu) -3. **`.contextignore`** - Include dosyası yokken kullanılır (EXCLUDE modu) -4. **`.methodinclude`** - Metodlar için en yüksek öncelik (INCLUDE modu) -5. **`.methodignore`** - Method include dosyası yokken kullanılır (EXCLUDE modu) - -Hem .contextinclude hem de .contextignore mevcut olduğunda, include dosyası önceliklidir ve ignore dosyası göz ardı edilir. Bu, analiz kapsamı üzerinde hassas kontrol sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L145-L184) -- [context-manager.js](file://context-manager.js#L108-L218) - -## Doğrulama ve Kullanım - -Kurulumdan sonra, aracın düzgün çalıştığını doğrulayın ve temel kullanım desenlerini keşfedin. - -### Doğrulama - -Yardım menüsüne erişerek kurulumu test edin: - -```bash -context-manager --help -``` - -Bu, CLI seçeneklerini ve kullanım bilgilerini görüntülemeli, aracın düzgün şekilde kurulu ve erişilebilir olduğunu doğrulamalıdır. Yardım çıktısı, yaygın kullanım desenlerinin örnekleriyle birlikte `--save-report`, `--context-export` ve `--method-level` gibi mevcut seçenekleri içerir. - -### Temel Kullanım Örnekleri - -#### İnteraktif Analiz -Aracı argümansız çalıştırmak, export seçenekleriyle interaktif modu başlatır: -```bash -context-manager -``` - -#### Doğrudan Export Seçenekleri -```bash -# Detaylı JSON raporu kaydet -context-manager --save-report - -# LLM context dosyası oluştur -context-manager --context-export - -# Context'i panoya kopyala -context-manager --context-clipboard -``` - -#### Metod Seviyesi Analiz -```bash -# Sadece belirli metodları analiz et -context-manager --method-level --context-clipboard -``` - -Araç, yürütme sırasında anında geri bildirim sağlar; kesin token sayımı (tiktoken ile) veya tahmin kullanıp kullanmadığını, analiz modunu (INCLUDE/EXCLUDE) ve tamamlanma sonrasında özet istatistikleri gösterir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L247-L255) -- [bin/cli.js](file://bin/cli.js#L35-L65) - -## Geliştirme İş Akışları ile Entegrasyon - -context-manager aracı, LLM context kullanımını optimize etmek ve kod tabanı karmaşıklığını izlemek için çeşitli geliştirme iş akışlarına entegre edilebilir. - -### Package.json Scriptleri -Projenizin package.json dosyasına özel scriptler ekleyin: -```json -"scripts": { - "analyze": "context-manager", - "analyze:methods": "context-manager --method-level", - "llm-context": "context-manager --context-clipboard" -} -``` - -Ardından bunları şu şekilde kullanın: -```bash -npm run analyze -npm run llm-context -``` - -### CI/CD Entegrasyonu -Kod tabanı büyümesini izlemek için aracı sürekli entegrasyon pipeline'larına dahil edin: -```bash -# CI script'inde -context-manager --save-report -TOKENS=$(jq '.summary.totalTokens' token-analysis-report.json) -if [ $TOKENS -gt 100000 ]; then - echo "Codebase exceeds LLM context limits" - exit 1 -fi -``` - -### Pre-commit Hook'ları -Değişiklikleri push etmeden önce kodun token bütçeleri içinde kalmasını sağlamak için pre-commit hook olarak kullanın. - -### LLM Context Hazırlama -Araç, LLM tüketimi için iki formatta optimize edilmiş dosya listeleri oluşturur: -- **Compact format** (~2.3k karakter): Sık AI etkileşimleri için minimal JSON yapısı -- **Detailed format** (~8.6k karakter): İlk proje analizi için kapsamlı context - -Bu çıktılar, AI destekli geliştirme iş akışlarına otomatik olarak beslenebilir ve geliştiricilerin en alakalı kod context'i ile çalışmasını sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L201-L217) -- [package.json](file://package.json#L7-L13) - -## Sorun Giderme - -context-manager aracının kurulumu ve kullanımı sırasında ortaya çıkabilecek yaygın sorunları çözün. - -### İzin Hataları (Global Kurulum) -Global kurulum yaparken izin hatalarıyla karşılaşabilirsiniz: -```bash -npm install -g @hakkisagdic/context-manager -# Error: EACCES: permission denied -``` - -**Çözümler:** -- Node.js'i home dizininize kuran nvm gibi bir Node.js sürüm yöneticisi kullanın -- İzin sorunlarından kaçınmak için npm'in varsayılan dizinini değiştirin -- sudo kullanın (güvenlik nedenleriyle önerilmez): `sudo npm install -g @hakkisagdic/context-manager` - -### Eksik Bağımlılıklar -tiktoken kurulumu başarısız olursa, araç otomatik olarak tahmin moduna geri döner. Kurulum sorunlarını çözmek için: -```bash -# npm önbelleğini temizle -npm cache clean --force - -# Taze bağımlılıklarla yeniden kur -npm install tiktoken -``` - -### Yapılandırma Sorunları -#### Include vs Exclude Mod Karışıklığı -- **Problem**: Beklenmeyen dosyalar dahil edildi/hariç tutuldu -- **Çözüm**: .contextinclude dosyasının varlığını kontrol edin, çünkü .contextignore'dan önceliklidir - -#### Desen Eşleştirme Sorunları -- Desenlerin satır içi yorumları olmadığından emin olun -- Özyinelemeli eşleştirme için `**`, tek seviye için `*` kullanın -- Eşleştirme davranışını görmek için verbose mod ile desenleri test edin - -### Platforma Özgü Sorunlar -Uygun pano araçları olmayan Linux sistemlerinde: -```bash -# Gerekli pano yardımcı programlarını kurun -sudo apt-get install xclip xsel # Debian/Ubuntu -sudo yum install xclip # CentOS/RHEL -``` - -Araç, birincil komut başarısız olursa otomatik olarak alternatif pano komutlarını dener ve çapraz platform uyumluluğu için geri dönüş mekanizmaları sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L257-L284) -- [context-manager.js](file://context-manager.js#L565-L585) diff --git a/docs/content-tr/Programatik-API.md b/docs/content-tr/Programatik-API.md deleted file mode 100644 index e8f8f32..0000000 --- a/docs/content-tr/Programatik-API.md +++ /dev/null @@ -1,378 +0,0 @@ -# Programatik API - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [context-manager.js](file://context-manager.js) - *Son commit'te güncellendi* -- [index.js](file://index.js) - *Son commit'te güncellendi* -- [README.md](file://README.md) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Core uygulama* -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Son commit'te eklendi* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Son commit'te eklendi* - - -## Güncelleme Özeti -**Yapılan Değişiklikler** -- TokenAnalyzer sınıfı dokümantasyonu TokenCalculator ile alias ilişkisini yansıtacak şekilde güncellendi -- GitIngestFormatter ve MethodFilterParser sınıfları için yeni bölümler eklendi -- Yapılandırma seçenekleri yeni gitingest seçeneğini içerecek şekilde güncellendi -- Yeni generateDigestFromReport ve generateDigestFromContext fonksiyonları için dokümantasyon eklendi -- Kullanım örnekleri yeni formatter ve parser sınıflarını içerecek şekilde güncellendi -- Core bileşenler diyagramı yeni ilişkileri gösterecek şekilde geliştirildi - -## İçindekiler -1. [Giriş](#giriş) -2. [Core Bileşenler](#core-bileşenler) -3. [TokenAnalyzer Sınıfı](#tokenanalyzer-sınıfı) -4. [Konfigürasyon Seçenekleri](#konfigürasyon-seçenekleri) -5. [Veri Modelleri](#veri-modelleri) -6. [Kullanım Örnekleri](#kullanım-örnekleri) -7. [Hata Yönetimi](#hata-yönetimi) -8. [Performans Değerlendirmeleri](#performans-değerlendirmeleri) -9. [Migrasyon Rehberi](#migrasyon-rehberi) - -## Giriş - -context-manager aracı, kod tabanlarını analiz etmek ve LLM (Large Language Model) tüketimi için optimize edilmiş context oluşturmak üzere programatik bir arayüz sağlar. Birincil giriş noktası TokenAnalyzer sınıfıdır ve geliştiricilerin token analizi yeteneklerini doğrudan Node.js uygulamalarına entegre etmelerini sağlar. Bu API, proje dosyalarının otomatik analizine, method seviyesinde çıkarmaya ve AI destekli geliştirme iş akışları için context'e optimize edilmiş çıktıların oluşturulmasına izin verir. - -Araç, geliştiricilerin kod tabanı karmaşıklığını anlamalarına, LLM context kullanımını optimize etmelerine ve geliştirme pipeline'larında analiz görevlerini otomatikleştirmelerine yardımcı olmak üzere tasarlanmıştır. Filtreleme ve çıktı formatları için esnek konfigürasyon seçenekleriyle hem dosya seviyesinde hem de method seviyesinde analizi destekler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L1-L100) - -## Core Bileşenler - -context-manager aracı, kapsamlı analiz yetenekleri sağlamak için kompozisyon yoluyla birlikte çalışan birkaç core bileşen etrafında inşa edilmiştir. TokenAnalyzer sınıfı, analiz sürecinin farklı yönleri için özel bileşenler arasındaki etkileşimleri düzenleyen birincil arayüz olarak hizmet eder. - -Mimari, her bileşenin belirli bir sorumluluğa sahip olduğu modüler bir tasarımı takip eder: -- GitIgnoreParser, .gitignore ve özel ignore kurallarına dayalı dosya hariç tutmayı yönetir -- MethodAnalyzer, kod dosyalarından method tanımlarını çıkarır -- MethodFilterParser, methodlara dahil etme/hariç tutma kurallarını uygular -- TokenCalculator, core analizi ve token sayımını gerçekleştirir -- GitIngestFormatter, GitIngest-style digest dosyaları oluşturur - -Bu bileşenler, tutarlı bir analiz deneyimi sağlamak için TokenAnalyzer (TokenCalculator olarak uygulanmıştır) içinde kompoze edilir. Bu tasarım, son kullanıcılar için basit bir arayüz korurken her bileşenin bağımsız geliştirilmesine ve test edilmesine izin verir. - -```mermaid -classDiagram -class TokenAnalyzer { -+constructor(directoryPath, options) -+run() -} -class GitIgnoreParser { -+constructor(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+isIgnored(filePath, relativePath) -} -class MethodAnalyzer { -+extractMethods(content, filePath) -+getLineNumber(content, index) -+isKeyword(name) -} -class MethodFilterParser { -+constructor(methodIncludePath, methodIgnorePath) -+shouldIncludeMethod(methodName, fileName) -} -class GitIngestFormatter { -+constructor(projectRoot, stats, analysisResults) -+generateDigest() -+saveToFile(outputPath) -} -TokenAnalyzer --> GitIgnoreParser : "kullanır" -TokenAnalyzer --> MethodAnalyzer : "kullanır" -TokenAnalyzer --> MethodFilterParser : "kullanır" -TokenAnalyzer --> GitIngestFormatter : "gitingest seçeneği için kullanır" -GitIngestFormatter --> MethodAnalyzer : "method çıkarma için kullanır" -GitIngestFormatter --> MethodFilterParser : "method filtreleme için kullanır" -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L14-L109) -- [context-manager.js](file://context-manager.js#L118-L223) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L223) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L13-L264) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## TokenAnalyzer Sınıfı - -TokenAnalyzer sınıfı, context-manager aracının programatik arayüzünün birincil giriş noktasıdır. Kod tabanlarını analiz etmek ve LLM tüketimi için optimize edilmiş context oluşturmak için basit ama güçlü bir API sağlar. - -### Constructor Parametreleri - -TokenAnalyzer constructor'ı iki parametre kabul eder: - -```javascript -const analyzer = new TokenAnalyzer(directoryPath, options); -``` - -- `directoryPath` (string): Analiz edilmesi gereken dizinin yolu. Bu genellikle projenizin kök dizini veya analiz etmek istediğiniz belirli bir alt dizindir. -- `options` (object): Analizin davranışını kontrol eden konfigürasyon seçenekleri. Detaylar için Konfigürasyon Seçenekleri bölümüne bakın. - -**Önemli Not**: TokenAnalyzer aslında TokenCalculator sınıfı için bir alias'tir. Kod tabanında, TokenAnalyzer geriye dönük uyumluluk için index.js dosyasında TokenCalculator'un bir alias'i olarak export edilir. Bu, TokenAnalyzer ve TokenCalculator'un iki farklı isimle aynı sınıf olduğu anlamına gelir. - -### run() Methodu - -`run()` methodu tam analiz sürecini yürütür ve sonuçları oluşturur. Çağrıldığında, aşağıdaki adımları gerçekleştirir: - -1. Belirtilen dizini ve alt dizinlerini tarar -2. .gitignore ve özel konfigürasyon dosyalarından ignore kurallarını uygular -3. Token sayılarını hesaplamak için her dosyayı analiz eder -4. Etkinleştirildiğinde isteğe bağlı olarak method seviyesinde analiz yapar -5. Kapsamlı raporlar ve export'lar oluşturur -6. Konfigürasyona göre sonuçları konsola ve/veya dosyalara çıktılar - -Method doğrudan bir Promise döndürmese de doğası gereği asenkrondur. Bunun yerine, özellikle dosya sistemi işlemleri ve pano entegrasyonu ile uğraşırken asenkron işlemleri dahili olarak ele alır. - -```mermaid -sequenceDiagram -participant Application -participant TokenAnalyzer -participant GitIgnoreParser -participant MethodAnalyzer -participant MethodFilterParser -participant GitIngestFormatter -Application->>TokenAnalyzer : new TokenAnalyzer(path, options) -TokenAnalyzer->>TokenAnalyzer : Bileşenleri başlat -Application->>TokenAnalyzer : run() -TokenAnalyzer->>GitIgnoreParser : Dosyanın göz ardı edilip edilmeyeceğini kontrol et -loop Her dosya için -TokenAnalyzer->>TokenAnalyzer : Dosya içeriğini oku -TokenAnalyzer->>TokenAnalyzer : Tokenleri hesapla -alt methodLevel etkin -TokenAnalyzer->>MethodAnalyzer : extractMethods(content) -loop Her method için -MethodAnalyzer->>MethodFilterParser : shouldIncludeMethod() -MethodFilterParser-->>MethodAnalyzer : Dahil et/Hariç tut kararı -end -end -TokenAnalyzer->>TokenAnalyzer : İstatistikleri güncelle -end -alt gitingest etkin -TokenAnalyzer->>GitIngestFormatter : Digest oluştur -GitIngestFormatter->>GitIngestFormatter : Method filtreleme uygula -GitIngestFormatter->>GitIngestFormatter : GitIngest digest olarak formatla -end -TokenAnalyzer->>TokenAnalyzer : Raporları oluştur -TokenAnalyzer->>Application : Sonuçları çıktıla -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L225-L790) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L225-L790) -- [index.js](file://index.js#L1-L8) - -## Konfigürasyon Seçenekleri - -TokenAnalyzer sınıfı, constructor'ındaki options object parametresi aracılığıyla çeşitli seçenekleri kabul eder. Bu seçenekler, analiz sürecinin davranışını kontrol eder ve belirli kullanım senaryolarına göre özelleştirmeye izin verir. - -### Kullanılabilir Seçenekler - -| Seçenek | Tip | Varsayılan | Açıklama | -|--------|------|---------|-------------| -| methodLevel | boolean | false | Method seviyesinde analizi etkinleştirir, kod dosyalarından bireysel methodları çıkarır | -| verbose | boolean | false | Analiz sırasında detaylı bilgilerin görüntülenip görüntülenmeyeceğini kontrol eder | -| saveReport | boolean | false | Analizin detaylı JSON raporunu token-analysis-report.json'a kaydeder | -| contextExport | boolean | false | Optimize edilmiş dosya listeleriyle bir LLM context dosyası (llm-context.json) oluşturur | -| contextClipboard | boolean | false | LLM context'ini doğrudan sistem panosuna kopyalar | - -### Seçenek Etkileşimleri - -Bu seçenekler farklı analiz iş akışları elde etmek için birleştirilebilir: - -- `methodLevel: true` kullanmak JavaScript/TypeScript dosyalarından bireysel methodların çıkarılmasını sağlar, daha granüler analiz sağlar -- `saveReport: true`'yu diğer seçeneklerle birleştirmek hem anında geri bildirim hem de analiz sonuçlarının kalıcı depolanmasına izin verir -- `contextExport: true` veya `contextClipboard: true` kullanmak LLM tüketimi için optimize edilmiş context oluşturur, ya bir dosyaya kaydeder ya da panoya kopyalar -- `verbose` seçeneği analiz sırasında görüntülenen bilgi miktarını kontrol eder, etkinleştirildiğinde daha fazla detay gösterilir - -Hiçbir export seçeneği belirtilmediğinde, araç analiz tamamlandıktan sonra kullanıcıdan bir export seçeneği seçmesini isteyecektir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L100-L300) -- [context-manager.js](file://context-manager.js#L225-L232) - -## Veri Modelleri - -context-manager aracı, analiz sırasında dosya ve methodları temsil etmek için özel veri modelleri kullanır. Bu modeller dahili olarak kullanılır ve oluşturulan raporların ve context export'larının yapısını oluşturur. - -### FileInfo Modeli - -FileInfo modeli, analiz edilmiş bir dosya hakkındaki bilgileri temsil eder: - -```typescript -interface FileInfo { - path: string; // Dosyaya mutlak yol - relativePath: string; // Proje köküne göre göreceli yol - sizeBytes: number; // Byte cinsinden dosya boyutu - tokens: number; // Hesaplanan token sayısı - lines: number; // Dosyadaki satır sayısı - extension: string; // Dosya uzantısı - methods?: MethodInfo[]; // Method dizisi (methodLevel etkinse) -} -``` - -### MethodInfo Modeli - -MethodInfo modeli, çıkarılmış bir method hakkındaki bilgileri temsil eder: - -```typescript -interface MethodInfo { - name: string; // Method adı - line: number; // Method'un tanımlandığı satır numarası - tokens: number; // Method içeriği için token sayısı - file: string; // Method'u içeren dosyaya göreceli yol -} -``` - -Bu modeller analiz sonuçlarını yapılandırmak için kullanılır ve oluşturulan JSON raporlarında serileştirilir. Method seviyesinde analiz etkinleştirildiğinde, araç dosyaların methodlarının dizilerini içerdiği hiyerarşik bir yapı oluşturur, hem dosya hem de method seviyelerinde kod karmaşıklığının detaylı analizine izin verir. - -Veri modelleri hafif olacak ve token analizi ve LLM context optimizasyonu için gereken temel bilgilere odaklanacak şekilde tasarlanmıştır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L400-L420) -- [context-manager.js](file://context-manager.js#L480-L500) - -## Kullanım Örnekleri - -context-manager aracı, otomatik analiz için Node.js uygulamalarına entegre edilebilir. Aşağıdaki örnekler yaygın kullanım desenlerini gösterir. - -### Temel Entegrasyon - -```javascript -const { TokenAnalyzer } = require('@hakkisagdic/context-manager'); - -// Temel dosya seviyesinde analiz -const analyzer = new TokenAnalyzer('./src', { - verbose: true, - saveReport: true -}); - -analyzer.run(); -``` - -### Method Seviyesinde Analiz - -```javascript -// Tüm çıktılarla method seviyesinde analiz -const methodAnalyzer = new TokenAnalyzer('./src', { - methodLevel: true, - saveReport: true, - contextExport: true, - verbose: true -}); - -methodAnalyzer.run(); -``` - -### LLM İçin Optimize Edilmiş Context Oluşturma - -```javascript -// LLM tüketimi için optimize edilmiş context oluştur -const llmAnalyzer = new TokenAnalyzer('./src', { - methodLevel: true, - contextClipboard: true -}); - -llmAnalyzer.run(); -``` - -### CI/CD Entegrasyonu - -```javascript -// CI/CD pipeline'ında entegrasyon -const ciAnalyzer = new TokenAnalyzer('./src', { - saveReport: true, - contextExport: true -}); - -ciAnalyzer.run(); -``` - -Bu örnekler TokenAnalyzer'ın temel analizden LLM'e optimize edilmiş context oluşturmaya kadar farklı kullanım senaryoları için nasıl yapılandırılabileceğini gösterir. Seçeneklerin esnekliği, geliştiricilerin analizi geliştirme, hata ayıklama veya otomatik iş akışları için olsun, kendi özel ihtiyaçlarına göre uyarlamalarına olanak tanır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L700-L800) - -## Hata Yönetimi - -context-manager aracı, çeşitli ortamlarda güçlü işlem sağlamak için kapsamlı hata yönetimi içerir. Analiz süreci, yürütme sırasında oluşabilecek dosya sistemi hatalarını ve diğer istisnaları zarif bir şekilde ele almak üzere tasarlanmıştır. - -Bir dosya okunamadığında veya analiz edilemediğinde, araç hata mesajıyla sonuçlarda bir hata girişi oluşturur, analizin diğer dosyalarla devam etmesine izin verir. Bu, tek bir sorunlu dosyanın tüm analiz sürecini durdurmasını önler. - -Araç ayrıca platforma özel sorunları, özellikle pano işlemlerini ele alır. Desteklenmeyen platformlarda, başarısız olacak pano işlemlerini denemek yerine context'i bir dosyaya kaydetmeye geri döner. - -Konfigürasyon sorunları için, araç hangi konfigürasyon dosyalarının kullanıldığı ve hangi modda (INCLUDE veya EXCLUDE) olduğu hakkında net geri bildirim sağlar. Bu, kullanıcıların belirli dosyaların neden analize dahil edildiğini veya hariç tutulduğunu anlamalarına yardımcı olur. - -Hata yönetim stratejisi, ilk hatada durmak yerine analizi tamamlamayı önceliklendirir, kullanıcıların sürecin bazı bölümleri sorunlarla karşılaşsa bile mümkün olduğunca fazla bilgi almasını sağlar. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L400-L415) -- [context-manager.js](file://context-manager.js#L700-L730) - -## Performans Değerlendirmeleri - -context-manager API'sini programatik olarak kullanırken, birkaç performans değerlendirmesi dikkate alınmalıdır: - -### Token Sayım Methodları - -Araç, token sayımı için iki methodu destekler: -- tiktoken kütüphanesini kullanarak **Kesin sayım** (yükleme gerektirir) -- Karakter tabanlı sezgisel yöntemler kullanarak **Tahmin** (tiktoken mevcut olmadığında fallback) - -Optimal doğruluk için tiktoken paketini yükleyin: -```bash -npm install tiktoken -``` - -### Analiz Kapsamı - -Analizin performansı, analiz edilen kod tabanının boyutuyla doğrudan ilgilidir. Performansı optimize etmek için: -- Mümkün olduğunda analizi belirli dizinlerle sınırlayın -- İlgisiz dosyaları hariç tutmak için konfigürasyon dosyalarını (.contextignore, .contextinclude) kullanın -- Analiz derinliği ile yürütme süresi arasındaki dengeyi göz önünde bulundurun - -### Method Seviyesinde Analiz - -Method seviyesinde analizi etkinleştirmek, kodu bireysel methodları tanımlamak için parse etmeyi gerektirdiğinden işlem süresini önemli ölçüde artırır. Bu özellik method seviyesinde içgörüler gerektiğinde kullanılmalı, ancak basit dosya seviyesinde analiz için devre dışı bırakılmalıdır. - -### Asenkron İşlemler - -`run()` methodu bir Promise döndürmese de, özellikle dosya sistemi erişimi ve pano işlemleri için dahili olarak birkaç asenkron işlem gerçekleştirir. Otomatik iş akışlarında, büyük kod tabanları için gereken yürütme süresini göz önünde bulundurun. - -Araç önbelleğe alma ve verimli dosya sistemi işlemleriyle performans için optimize edilmiştir, ancak çok büyük kod tabanları hala önemli işlem süresi gerektirebilir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L300-L350) -- [README.md](file://README.md#L500-L600) - -## Migrasyon Rehberi - -context-manager aracının daha yeni versiyonlarına yükseltme veya migrasyon yaparken, aşağıdaki rehberi göz önünde bulundurun: - -### Versiyon Uyumluluğu - -Araç, core API'si için geriye dönük uyumluluğu korur. TokenAnalyzer sınıfı arayüzü versiyonlar arasında istikrarlı kalmıştır, mevcut entegrasyonların çalışmaya devam etmesini sağlar. - -### Konfigürasyon Değişiklikleri - -Konfigürasyon dosyası formatlarında veya seçenek parametrelerinde herhangi bir değişiklik için sürüm notlarını kontrol edin. Core seçenekler tutarlı kalırken, daha yeni versiyonlarda yeni seçenekler eklenebilir. - -### Bağımlılık Yönetimi - -Gerekli bağımlılıkların, özellikle kesin token sayımı için tiktoken'ın düzgün şekilde yüklendiğinden emin olun. tiktoken mevcut değilse araç tahminine geri döner, ancak daha düşük doğrulukla. - -### Test - -Yükseltme yaptıktan sonra, beklenen davranışı sağlamak için analizi tipik kod tabanlarınızla test edin. Özellikle şunlara dikkat edin: -- Dosya dahil etme/hariç tutma desenleri -- Token sayısı doğruluğu -- Export fonksiyonelliği -- Method seviyesinde analiz (kullanılıyorsa) - -Aracın JSON raporları ve context export'ları için çıktı formatı istikrarlı olacak şekilde tasarlanmıştır, bu çıktıları tüketen downstream süreçler üzerindeki yükseltmelerin etkisini en aza indirir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L800-L891) diff --git a/docs/content-tr/Sorun-Giderme.md b/docs/content-tr/Sorun-Giderme.md deleted file mode 100644 index 4f97359..0000000 --- a/docs/content-tr/Sorun-Giderme.md +++ /dev/null @@ -1,186 +0,0 @@ -# Sorun Giderme - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [context-manager.js](file://context-manager.js) - *6f5fea32 commit'inde güncellendi* -- [README.md](file://README.md) - *6f5fea32 commit'inde güncellendi* -- [bin/cli.js](file://bin/cli.js) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *6f5fea32 commit'inde eklendi* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *6f5fea32 commit'inde eklendi* - - -## İçindekiler -1. [Include/Exclude Mod Karışıklığı](#includeexclude-mod-karışıklığı) -2. [Desen Eşleştirme Sorunları](#desen-eşleştirme-sorunları) -3. [Token Sayımı Tutarsızlıkları](#token-sayımı-tutarsızlıkları) -4. [Analizde Eksik Dosyalar](#analizde-eksik-dosyalar) -5. [Beklenmeyen Dosya Dahil Edilmeleri](#beklenmeyen-dosya-dahil-edilmeleri) -6. [Büyük Kod Tabanlarında Performans Sorunları](#büyük-kod-tabanlarında-performans-sorunları) -7. [Tanı Adımları](#tanı-adımları) -8. [Yaygın Ortam Sorunları](#yaygın-ortam-sorunları) -9. [GitIngest Digest Üretim Sorunları](#gitingest-digest-uretim-sorunları) -10. [Method Seviyesi Filtreleme Sorunları](#method-seviyesi-filtreleme-sorunları) - -## Include/Exclude Mod Karışıklığı - -context-manager aracı, dosya dahil etme ve hariç tutma için öncelik tabanlı bir sistem kullanır. Bir `.contextinclude` dosyasının varlığı `.contextignore` üzerinde öncelik alır, bu da kullanıcılar dosyaların dahil edilmesini beklediğinde ancak hariç tutulduğunda karışıklığa yol açabilir. - -`.contextinclude` mevcut olduğunda, araç INCLUDE modunda çalışır, yani yalnızca bu dosyadaki desenlere uyan dosyalar analize dahil edilecektir. Bu, tüm `.contextignore` kurallarını geçersiz kılar. Kullanıcılar `.contextignore` konfigürasyonlarına göre dosyaların dahil edilmesini bekleyebilirler, ancak bir `.contextinclude` dosyası mevcutsa, bu beklentiler karşılanmayacaktır. - -Araç, yürütme sırasında hangi modun aktif olduğunu açıkça gösterir. INCLUDE modunda "📅 Found calculator config - using INCLUDE mode" görüntülerken, EXCLUDE modunda "📅 Found calculator config - using EXCLUDE mode" gösterir. Bu görsel ipucu, mevcut filtreleme modunu belirlemeye yardımcı olur. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L134-L157) -- [context-manager.js](file://context-manager.js#L181-L217) -- [README.md](file://README.md#L121-L150) - -## Desen Eşleştirme Sorunları - -context-manager aracındaki desen eşleştirme, kullanıcıların `.contextignore` ve `.methodinclude` dosyalarını doğru yapılandırmaları için anlamaları gereken özel sözdizimi kurallarını takip eder. Yaygın sorunlar arasında yanlış sözdizimi, eksik negasyon desenleri ve wildcard davranışının yanlış anlaşılması yer alır. - -Araç, eşleştirme için desenleri regex'lere dönüştürür, belirli dönüşümlerle: -- `**`, `.*` olur (herhangi bir sayıda dizini eşleştirir) -- `*`, `[^/]*` olur (dizin ayırıcılar hariç herhangi bir karakteri eşleştirir) -- `?`, `[^/]` olur (dizin ayırıcılar hariç herhangi bir tek karakteri eşleştirir) - -Negasyon desenleri (`!` ile başlayan), INCLUDE ve EXCLUDE modlarında farklı şekilde çalışır. INCLUDE modunda, negasyon desenleri dahil edilen setten dosyaları hariç tutar, EXCLUDE modunda ise başka türlü hariç tutulacak dosyaları yeniden dahil ederler. Yaygın bir hata, negasyon desenlerini yanlış sıraya yerleştirmektir, çünkü araç desenleri sırayla işler. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L159-L179) -- [context-manager.js](file://context-manager.js#L219-L257) -- [README.md](file://README.md#L544-L610) - -## Token Sayımı Tutarsızlıkları - -context-manager aracı hem kesin hem de tahmini token sayıları sağlar, bu da kullanıcıların kafa karıştırıcı bulabileceği tutarsızlıklara yol açabilir. Araç önce kesin GPT-4 uyumlu token sayımı için tiktoken kütüphanesini kullanmayı dener. tiktoken mevcut değilse, bir tahmin algoritmasına geri döner. - -Tahmin algoritması, farklı dosya türleri için önceden tanımlanmış karakter başına token oranları kullanır: -- JavaScript/TypeScript: Token başına 3.2 karakter -- JSON: Token başına 2.5 karakter -- Markdown: Token başına 4.0 karakter -- HTML/XML: Token başına 2.8 karakter -- Varsayılan: Token başına 3.5 karakter - -Bu tahminler genellikle kesin sayımlara kıyasla yaklaşık %95 doğrudur. Kullanıcılar, tahmini sayımlar ile diğer araçlardan bekledikleri arasında farklılıklar fark edebilirler. Araç çıktıda hangi sayım methodunun kullanıldığını açıkça gösterir: kesin sayımlar için "🎯 Token calculation: ✅ Exact (using tiktoken)" veya tahminler için "🎯 Token calculation: ⚠️ Estimated". - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L259-L292) -- [context-manager.js](file://context-manager.js#L385-L400) -- [README.md](file://README.md#L801-L879) - -## Analizde Eksik Dosyalar - -Dosyalar, çok katmanlı filtreleme sistemi nedeniyle analizden eksik olabilir. Araç, öncelik sırasına göre üç seviye konfigürasyon dosyasına saygı gösterir: -1. `.gitignore` (her zaman saygı gösterilir) -2. `.contextinclude` (dahil etme için en yüksek öncelik) -3. `.contextignore` (include dosyası yoksa kullanılır) - -Bir dosya, bu mekanizmalardan herhangi biri tarafından hariç tutulmuşsa analizden eksik olabilir. Bir dosya `.contextignore`'da açıkça belirtilmemiş olsa bile, `**/*.md` veya `node_modules/**` gibi bir desen tarafından hariç tutulabilir. Kullanıcılar bir dosyanın neden eksik olduğunu anlamak için her üç konfigürasyon dosyasını da kontrol etmelidir. - -Ek olarak, araç yalnızca dosya uzantısı ve basename ile belirlenen metin dosyalarını analiz eder. Tanınan metin uzantıları listesinde olmayan uzantılara veya metin dosyaları listesinde olmayan basename'lere sahip dosyalar, açıkça göz ardı edilmemiş olsalar bile tamamen atlanacaktır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L181-L217) -- [context-manager.js](file://context-manager.js#L414-L453) -- [README.md](file://README.md#L294-L356) - -## Beklenmeyen Dosya Dahil Edilmeleri - -Beklenmeyen dosya dahil edilmeleri, kullanıcılar farklı konfigürasyon dosyaları arasındaki etkileşimi yanlış anladıklarında meydana gelebilir. En yaygın neden, kullanıcı EXCLUDE modu davranışı beklediğinde bir `.contextinclude` dosyasının varlığıdır. INCLUDE modunda, yalnızca `.contextinclude`'daki desenlere uyan dosyalar dahil edilir, bu da kullanıcının hariç tutulmasını beklediği dosyaları dahil edebilir. - -Başka bir neden, uygun negasyon olmadan `**/*.js` gibi geniş desenlerin kullanılmasıdır. Örneğin, bir kullanıcı test dizinlerindekiler hariç tüm JavaScript dosyalarını dahil etmek istiyorsa, `!**/*.test.js` veya `!test/**` gibi bir negasyon desenini açıkça eklemesi gerekir. - -Aracın verbose çıktısı, dosyaların neden dahil edildiğini belirlemeye yardımcı olabilir. `--verbose` flag'i ile çalıştırıldığında, araç hangi modun aktif olduğunu gösterir ve dahil etme mantığını izlemeye yardımcı olabilir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L134-L157) -- [context-manager.js](file://context-manager.js#L181-L217) -- [README.md](file://README.md#L544-L610) - -## Büyük Kod Tabanlarında Performans Sorunları - -Büyük kod tabanlarındaki performans sorunları genellikle aracın proje dizinindeki her dosyayı taraması ve analiz etmesi gereğinden kaynaklanır. Tarama işlemi dizinleri özyinelemeli olarak geçer, bu da çok sayıda dosya içeren derin iç içe yapılar için yavaş olabilir. - -Araç, performansı artırmak için `node_modules`, `.git`, `dist` ve `build` gibi belirli dizinleri otomatik olarak atlar. Ancak, bir kod tabanında analiz edilebilir kategorilerde (JavaScript, TypeScript, Markdown, vb.) çok sayıda dosya varsa, analiz hala zaman alabilir. - -Method seviyesinde analiz (`--method-level` flag'i), aracın her dosyayı method tanımlarını çıkarmak için parse etmesi ve her method için ayrı ayrı token hesaplaması gerektiğinden işleme süresini önemli ölçüde artırır. Çok büyük kod tabanları için, bu fark edilir gecikmelere neden olabilir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L455-L485) -- [context-manager.js](file://context-manager.js#L521-L545) -- [bin/cli.js](file://bin/cli.js#L20-L35) - -## Tanı Adımları - -context-manager aracı ile ilgili sorunları tanılamak için, kullanıcılar şu adımları izlemelidir: - -1. Hangi dosyaların işlendiği ve hangi kuralların uygulandığı hakkında detaylı çıktı görmek için aracı `--verbose` flag'i ile çalıştırın. - -2. Hangi modun aktif olduğunu (INCLUDE veya EXCLUDE) ve hangi konfigürasyon dosyasının kullanıldığını belirlemek için ilk çıktıyı kontrol edin. - -3. İşlenen tüm dosyalar, bunların token sayıları ve hangi kuralların uygulandığı hakkında bilgi içeren detaylı bir JSON raporu oluşturmak için `--save-report` seçeneğini kullanın. - -4. Çakışan veya yanlış desenler için konfigürasyon dosyalarını (`.gitignore`, `.contextignore`, `.contextinclude`) inceleyin. - -5. Kesin token sayıları gerekiyorsa tiktoken bağımlılığının yüklendiğini doğrulayın. - -Araç çıktısında tanıya yardımcı olan açık görsel göstergeler sağlar, örneğin `.gitignore` kuralları ile calculator kuralları nedeniyle göz ardı edilen dosyaların sayısı ve kesin veya tahmini token sayımının kullanılıp kullanılmadığı. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L609-L643) -- [context-manager.js](file://context-manager.js#L715-L743) -- [bin/cli.js](file://bin/cli.js#L41-L66) - -## Yaygın Ortam Sorunları - -Yaygın ortam sorunları arasında eksik bağımlılıklar ve izin hataları yer alır. En sık karşılaşılan bağımlılık sorunu, kesin token sayımı için gerekli olan tiktoken kütüphanesinin yokluğudur. tiktoken yüklü olmadığında, araç otomatik olarak tahmin moduna geri döner, ancak doğru sonuçlar için kullanıcılar `npm install tiktoken` ile yüklemelidir. - -İzin hataları, araç kod tabanındaki belirli dosya veya dizinlere okuma erişimine sahip olmadığında meydana gelebilir. Bu, aracı kısıtlı ortamlarda çalıştırırken veya dosya izinleri çok dar ayarlandığında olabilir. Kullanıcılar, aracın analiz etmek istedikleri tüm dosyalar için uygun okuma izinlerine sahip olduğundan emin olmalıdır. - -Diğer bir yaygın sorun, aracı yanlış dizinden çalıştırmaktır. Araç varsayılan olarak mevcut çalışma dizinini analiz eder, bu nedenle kullanıcılar komutu yürütürken doğru proje kök dizininde olduklarından emin olmalıdır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L259-L292) -- [context-manager.js](file://context-manager.js#L825-L840) -- [README.md](file://README.md#L294-L356) - -## GitIngest Digest Üretim Sorunları - -GitIngest-style digest formatlamasının uygulanmasıyla, digest üretimiyle ilgili yeni sorunlar ortaya çıkabilir. `--gitingest` flag'i LLM tüketimi için tek dosyalık bir digest oluşturur, ancak kullanıcılar bu özellikle ilgili sorunlarla karşılaşabilir. - -Yaygın sorunlar şunları içerir: -- `--gitingest` flag'i kullanıldığında digest.txt çıktısı eksik -- Oluşturulan digest'teki yanlış token tahminleri -- Dizin ağacı yapısı gerçek proje yapısını yansıtmıyor -- Digest çıktısında dosya içerikleri eksik - -GitIngestFormatter, `.methodinclude` veya `.methodignore` dosyaları mevcut olduğunda method seviyesi filtrelemeyi otomatik olarak algılar ve uygular. Method filtreleme aktifse, digest methodlar için INCLUDE veya EXCLUDE modunun aktif olup olmadığını belirten bir not içerecektir. - -`--gitingest-from-report` veya `--gitingest-from-context` kullanarak mevcut JSON raporlarından digest oluştururken, belirtilen JSON dosyasının var olduğundan ve doğru yapıya sahip olduğundan emin olun. Araç, dosya bulunamazsa veya geçersiz formata sahipse bir hata mesajı görüntüler. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L294-L382) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L1-L269) -- [README.md](file://README.md#L100-L150) - -## Method Seviyesi Filtreleme Sorunları - -Method seviyesi filtreleme, kullanıcıların `.methodinclude` ve `.methodignore` dosyalarını kullanarak belirli metodları analize dahil etmesine veya hariç tutmasına olanak tanır. Bu dosyalar doğru şekilde yapılandırılmadığında sorunlar ortaya çıkabilir. - -MethodFilterParser bu dosyaları işler ve desenleri düzgün ifadelere dönüştürür. Desenler, regex'te `.*`'a dönüştürülen wildcard'ları (`*`) destekler. Desenler büyük/küçük harfe duyarsızdır ve method adlarını veya dosya.method kombinasyonlarını eşleştirebilir. - -Yaygın sorunlar şunları içerir: -- Yanlış sözdizimi nedeniyle desenler beklenen metodlarla eşleşmiyor -- Negasyon desenleri beklenildiği gibi çalışmıyor -- Method filtreleme beklenildiğinde uygulanmıyor - -Araç, method filtre kuralları yüklendiginde mesajlar loglar: -- `.methodinclude` algılandığında "🔧 Method include rules loaded: X patterns" -- `.methodignore` algılandığında "🚫 Method ignore rules loaded: X patterns" - -Method filtreleme, digest oluştururken GitIngestFormatter tarafından otomatik olarak algılanır ve uygulanır, normal analiz ve digest üretimi arasında tutarlı davranış sağlar. - -**Bölüm kaynakları** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L1-L51) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js#L15-L25) -- [README.md](file://README.md#L200-L250) diff --git a/docs/content-tr/Temel-Ozellikler/Ana-Ozellikler.md b/docs/content-tr/Temel-Ozellikler/Ana-Ozellikler.md deleted file mode 100644 index 747da25..0000000 --- a/docs/content-tr/Temel-Ozellikler/Ana-Ozellikler.md +++ /dev/null @@ -1,82 +0,0 @@ -# Temel Özellikler - - -**Bu Belgedeki Referans Dosyalar** -- [context-manager.js](file://context-manager.js) - *Son commit'te güncellendi* -- [README.md](file://README.md) - *Son commit'te güncellendi* -- [index.js](file://index.js) -- [lib/formatters/gitingest-formatter.js](file://lib/formatters/gitingest-formatter.js) - *Son commit'te eklendi* - - -## İçindekiler -1. [Dosya Seviyesi Analiz](#dosya-seviyesi-analiz) -2. [Method Seviyesi Analiz](#method-seviyesi-analiz) -3. [Token Sayma](#token-sayma) -4. [Özellik Entegrasyonu](#özellik-entegrasyonu) -5. [Yaygın Sorunlar ve Performans](#yaygın-sorunlar-ve-performans) - -## Dosya Seviyesi Analiz - -context-manager aracı, hangi dosyaların token hesaplama sürecine dahil edilmesi gerektiğini belirlemek için birden fazla filtreleme mekanizmasını birleştiren kapsamlı bir dosya seviyesi analiz sistemi uygular. Araç, proje kökünden başlayarak tüm dizin yapısını tarayarak, hariç tutma kurallarına saygı göstererek özyinelemeli olarak dizinleri gezer. - -Dosya tarama işlemi, `TokenCalculator` sınıfının `scanDirectory` methodunda gerçekleştirilir ve projedeki her dosya ve dizini inceler. Bu işlem sırasında araç, hem `.gitignore` kalıplarına hem de özel yapılandırma dosyalarına saygı gösteren hiyerarşik bir filtreleme sistemi uygular. Dosyalar, yalnızca tüm filtreleme kriterlerinden geçerlerse ve `isTextFile` methodu aracılığıyla metin dosyaları olarak tanımlanırlarsa analize dahil edilir. Bu method, dosya uzantılarını ve temel adlarını önceden tanımlanmış metin tabanlı formatlar listesine karşı kontrol eder. - -Filtreleme sistemi, yapılandırma dosyalarını belirli bir sırayla önceliklendirir: `.gitignore` kurallarına her zaman saygı gösterilir, ardından `.contextinclude` gelir (INCLUDE modunda önceliğe sahiptir) ve sonra `.contextignore` gelir (include dosyası olmadığında EXCLUDE modunda kullanılır). Bu çok katmanlı yaklaşım, geliştiricilerin hangi dosyaların analiz edileceğini hassas bir şekilde kontrol etmelerini sağlayarak, dokümantasyon, yapılandırma ve test dosyalarını hariç tutarken temel uygulama mantığının odaklanmış incelemesine olanak tanır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L376-L406) -- [context-manager.js](file://context-manager.js#L288-L315) -- [README.md](file://README.md#L294-L356) - -## Method Seviyesi Analiz - -context-manager aracı, JavaScript ve TypeScript dosyalarında kod dosyalarındaki bireysel functionların granüler incelemesini sağlayan sofistike method seviyesi analiz yetenekleri sunar. Bu özellik, yapılandırılabilir kurallara göre methodları çıkarmak ve filtrelemek için birlikte çalışan `MethodAnalyzer` ve `MethodFilterParser` sınıfları aracılığıyla gerçekleştirilir. - -`MethodAnalyzer` sınıfı, geleneksel function bildirimleri, object method sözdizimi, arrow functionlar ve async functionlar dahil olmak üzere çeşitli JavaScript function kalıplarını tanımlamak için bir dizi regular expression kullanır. `--method-level` flag'i aracılığıyla method seviyesi analiz etkinleştirildiğinde, araç uygun kod dosyalarından tüm methodları çıkarır ve method adı ve satır numarası gibi metadata'yı yakalar. `extractMethodContent` methodu daha sonra bireysel token sayımı için tam method gövdesini izole eder. - -Method filtreleme, `.methodinclude` ve `.methodignore` yapılandırma dosyaları tarafından kontrol edilir ve geliştiricilerin pattern matching kullanarak belirli methodları dahil etmelerine veya hariç tutmalarına olanak tanır. `MethodFilterParser` sınıfı bu dosyaları işler ve glob kalıplarını verimli eşleştirme için regular expressionlara dönüştürür. Bir include dosyası mevcut olduğunda, yalnızca belirtilen kalıplarla eşleşen methodlar dahil edilir; aksi takdirde araç, ignore dosyasındaki kalıplarla eşleşen methodları hariç tutar. Bu sistem, tam eşleşmeler, wildcardlar, sınıfa özgü methodlar (`Class.*` sözdizimini kullanarak) ve dosyaya özgü methodlar (`file.method` sözdizimini kullanarak) dahil olmak üzere çeşitli pattern türlerini destekler. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L67) -- [context-manager.js](file://context-manager.js#L69-L109) -- [context-manager.js](file://context-manager.js#L357-L377) -- [README.md](file://README.md#L544-L610) - -## Token Sayma - -context-manager aracı, güvenilir bir yedek mekanizma sağlarken doğruluğa öncelik veren ikili bir token sayma yaklaşımı kullanır. Birincil method, GPT-4 uyumlu tam token sayımları sağlamak için `tiktoken` kütüphanesini kullanır; bu, bir LLM'nin context window'una ne kadar kodun sığabileceğini doğru bir şekilde tahmin etmek için önemlidir. `tiktoken` paketi yüklendiğinde, araç metni kodlamak ve tokenleri hassas bir şekilde saymak için `cl100k_base` encoding'ini (GPT-4, ChatGPT-4 ve text-embedding-ada-002 tarafından kullanılır) kullanır. - -Token sayma işlemi, `TokenCalculator` sınıfının `calculateTokens` methodunda gerçekleştirilir. Bu method önce `tiktoken` kullanmaya çalışır ve kütüphane mevcut değilse veya bir hata oluşursa tahmini hesaplamaya geçer. Tahmin mekanizması, farklı dosya türleri için farklı oranlar kullanarak karakter tabanlı bir yaklaşım kullanır, çünkü farklı dosya formatları token başına farklı ortalama karakterlere sahiptir. Örneğin, JavaScript ve TypeScript dosyaları token başına 3.2 karakter oranı kullanırken, Markdown dosyaları 4.0 ve JSON dosyaları 2.5 kullanır. Bu tahmin, tam sayıma kıyasla yaklaşık %95 doğruluk sağlar. - -Araç ayrıca dosya başına, uzantı başına ve dizin başına sayımlar dahil olmak üzere birden fazla seviyede token istatistiklerini izleyerek codebase bileşimi hakkında ayrıntılı bilgiler sağlar. Method seviyesi analiz etkinleştirildiğinde, araç ayrıca bireysel methodlar için tokenleri sayarak, geliştiricilerin yeniden düzenleme gerektirebilecek özellikle büyük veya karmaşık functionları belirlemelerine olanak tanır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L288-L315) -- [README.md](file://README.md#L356) - -## Özellik Entegrasyonu - -context-manager aracının temel özellikleri, dosya seviyesi analiz, method seviyesi analiz ve token sayımını uyumlu bir iş akışında entegre eden `TokenCalculator` sınıfı aracılığıyla düzenlenir. `run` methodu, dizin taramasından nihai raporlamaya kadar tüm analiz sürecini koordine eden ana giriş noktası olarak hizmet eder. - -Entegrasyon, çeşitli bileşenlerin başlatılmasıyla başlar: dosya filtreleme için `GitIgnoreParser`, method çıkarma için (etkinleştirildiğinde) `MethodAnalyzer` ve `MethodFilterParser` ve token sayma sistemi. Araç daha sonra dizin yapısını tarar ve hangi dosyaların analiz edileceğini belirlemek için filtreleme kurallarını uygular. Dahil edilen her dosya için içeriği okur ve tokenleri hesaplar, `methodLevel` seçeneği etkinleştirildiğinde isteğe bağlı olarak bireysel methodları çıkarır ve analiz eder. - -Sonuçlar, çeşitli ayrıntı düzeylerinde dosyaları, tokenleri, byte'ları ve satırları izleyen kapsamlı istatistiklerde toplanır. Araç, kullanım durumuna bağlı olarak farklı çıktı formatları oluşturabilir: LLM context optimizasyonu için kompakt format, istendiğinde ayrıntılı method seviyesi context veya analiz ve izleme için kapsamlı bir JSON raporu. `generateLLMContext` methodu, bir dosyaya dışa aktarılabilen veya panoya kopyalanabilen yapılandırılmış çıktı oluşturarak codebase context'ini AI asistanlarıyla paylaşmayı kolaylaştırır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L213-L251) -- [context-manager.js](file://context-manager.js#L498-L539) -- [context-manager.js](file://context-manager.js#L774-L813) - -## Yaygın Sorunlar ve Performans - -context-manager aracı, kod analizinde ortaya çıkan birkaç yaygın sorunu, özellikle pattern matching doğruluğu ve token sayma hassasiyeti etrafında ele alır. Yaygın sorunlardan biri, yapılandırma dosyalarında sözdizimi hataları olduğunda veya negation kalıpları (`!pattern`) düzgün anlaşılmadığında ortaya çıkabilen pattern matching hatalarıdır. Araç, bu sorunları teşhis etmeye yardımcı olmak için ayrıntılı çıktı sağlar ve hangi modun aktif olduğunu (INCLUDE veya EXCLUDE) ve her yapılandırma dosyasından kaç kuralın yüklendiğini gösterir. - -Büyük codebase'ler için performans, birkaç mekanizma aracılığıyla optimize edilir. Araç, dosya içeriğini işlemeden önce filtreleme kurallarını kontrol ederek gereksiz dosya okumalarından kaçınır. Ayrıca, başlatma sırasında kalıpları bir kez derleyerek method çıkarma ve pattern matching için verimli regular expressionlar kullanır. Dizin tarama işlemi, varsayılan olarak `node_modules`, `.git` ve `dist` gibi yaygın hariç tutma dizinlerini atlayarak dosya sistemi işlemlerinin sayısını azaltır. - -Yanlış token sayımları, `tiktoken` kütüphanesi yüklü olmadığında, aracı tahmini hesaplamaya güvenmeye zorladığında ortaya çıkabilir. Tahmin genellikle doğru olsa da (~%95 tam sayımlara kıyasla), kodun belirli özelliklerine bağlı olarak değişebilir. Sıkı token limitleriyle çalışan geliştiriciler, hassas sayım için `tiktoken` yüklemelidir. Araç ayrıca, token kullanımını dosya türüne ve dizine göre ayıran ayrıntılı raporlama sağlar ve genel sayımı çarpıtabilecek beklenmedik büyük dosyaları veya dizinleri belirlemeye yardımcı olur. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L253-L286) -- [context-manager.js](file://context-manager.js#L376-L406) -- [README.md](file://README.md#L544-L610) diff --git a/docs/content-tr/Temel-Ozellikler/Dosya-Seviyesi-Analiz.md b/docs/content-tr/Temel-Ozellikler/Dosya-Seviyesi-Analiz.md deleted file mode 100644 index 65f4372..0000000 --- a/docs/content-tr/Temel-Ozellikler/Dosya-Seviyesi-Analiz.md +++ /dev/null @@ -1,97 +0,0 @@ -# Dosya Seviyesi Analiz - - -**Bu Belgedeki Referans Dosyalar** -- [context-manager.js](file://context-manager.js) - - -## İçindekiler -1. [Dosya Seviyesi Analiz](#dosya-seviyesi-analiz) -2. [Dizin Tarama ve Filtreleme](#dizin-tarama-ve-filtreleme) -3. [GitIgnore İşleme](#gitignore-i̇şleme) -4. [Metin Dosyası Algılama](#metin-dosyası-algılama) -5. [Dosya Filtreleme ve Token Sayma İlişkisi](#dosya-filtreleme-ve-token-sayma-i̇lişkisi) -6. [İstatistik Takibi](#i̇statistik-takibi) -7. [Yaygın Sorunlar ve Optimizasyon](#yaygın-sorunlar-ve-optimizasyon) - -## Dizin Tarama ve Filtreleme - -TokenCalculator sınıfı, birden fazla ignore kuralına saygı göstererek özyinelemeli dizin taraması uygular. scanDirectory methodu, belirtilen bir dizinden başlayarak dosya sistemini gezer ve hangi dosyaların analize dahil edilmesi gerektiğini belirlemek için her seviyede filtreleme mantığını uygular. - -Tarama işlemi, mevcut dizindeki tüm öğeleri okuyarak ve bunları sırayla işleyerek başlar. Her öğe için sistem önce hem tam yolu hem de proje kökünden göreli yolu oluşturur. Daha sonra GitIgnoreParser instance'ının isIgnored methodunu çağırarak dosyanın veya dizinin ignore edilip edilmeyeceğini kontrol eder. Öğe ignore edilirse, istatistiklerde uygun sayacı artırır ve bir sonraki öğeye devam eder. - -Ignore edilmeyen öğeler için sistem, öğenin bir dosya mı yoksa dizin mi olduğunu belirler. Dizin gezinmesi, node_modules, .git, coverage, dist ve build gibi yaygın geliştirme dizinlerini hariç tutarak belirli dizinlerle sınırlıdır. Bu, analizin gereksiz dosyaları işlemesini önler ve performansı artırır. Bir dizin hariç tutulmadığında, scanDirectory methodu o dizinin içeriğini işlemek için kendisini özyinelemeli olarak çağırır. - -Ignore kontrollerinden geçen metin dosyaları, dizindeki tüm öğeler işlendikten sonra döndürülen sonuç dizisine eklenir. Bu özyinelemeli yaklaşım, dizin hiyerarşisinin her seviyesinde verimli filtrelemeyi korurken dosya sisteminin kapsamlı kapsanmasını sağlar. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L385-L412) - -## GitIgnore İşleme - -GitIgnoreParser sınıfı, kural değerlendirmesi için öncelik tabanlı bir sistem uygulayarak birden fazla kaynaktan ignore ve include kalıplarının işlenmesini yönetir. Sınıf üç tür yapılandırma dosyasını işler: .gitignore, .contextignore ve .contextinclude, .contextinclude en yüksek önceliğe sahiptir. - -Başlatma sırasında, GitIgnoreParser belirtilen yapılandırma dosyalarından kalıpları yükler. Hem .contextinclude hem de .contextignore mevcut olduğunda, include dosyası öncelik alır ve yalnızca include kalıplarıyla eşleşen dosyaların işlendiği "include-only" modunu uygular. Bu öncelik sistemi, kullanıcıların hariç tutma tabanlı filtreleme (çoğu dosyanın varsayılan olarak dahil edildiği) ile dahil etme tabanlı filtreleme (yalnızca açıkça belirtilen dosyaların dahil edildiği) arasında geçiş yapmalarına olanak tanır. - -Pattern işleme, verimli eşleştirme için glob tarzı kalıpları regular expressionlara dönüştürmeyi içerir. convertToRegex methodu, dizin işaretçileri (/), negation (!), wildcardlar (*) ve özyinelemeli wildcardlar (**) dahil olmak üzere çeşitli pattern özelliklerini ele alır. Dizin kalıpları özel olarak ele alınır ve hem dizinin kendisiyle hem de içindeki tüm dosyalarla eşleşir. Negation kalıpları, daha geniş ignore kurallarına belirli istisnalara izin vererek filtreleme işlemi üzerinde ince ayarlı kontrol sağlar. - -isIgnored methodu temel filtreleme mantığını uygular, önce .gitignore kurallarını kontrol eder, ardından include veya exclude modunun aktif olup olmadığına bağlı olarak calculator'a özgü kuralları uygular. Include modunda, bir dosya herhangi bir include kalıbıyla eşleşmiyorsa (negationlar hesaba katıldıktan sonra) ignore edilmiş olarak kabul edilirken, exclude modunda bir dosya herhangi bir exclude kalıbıyla eşleşirse ignore edilir. Bu iki katmanlı yaklaşım, gelişmiş filtreleme yetenekleri sağlarken mevcut .gitignore kurallarıyla uyumluluğu sağlar. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L124-L229) - -## Metin Dosyası Algılama - -isTextFile methodu, bir dosyanın uzantısına ve temel adına göre analiz edilip edilmeyeceğini belirler. Bu filtreleme mekanizması, yalnızca metin tabanlı dosyaların token sayımı için işlenmesini sağlar, binary dosyalardan ve LLM context oluşturma için uygun olmayacak diğer metin olmayan içerikten kaçınır. - -Method, metin dosyalarını tanımlamak için iki kriter kullanır: dosya uzantısı ve basename kalıpları. Uzantılar için, kaynak kod dosyaları (.js, .ts, .py, .java, vb.), markup dilleri (.html, .xml, .svg), yapılandırma formatları (.json, .yml, .toml) ve dokümantasyon formatları (.md, .txt) dahil olmak üzere yaygın metin tabanlı dosya türlerinin kapsamlı bir setini tutar. Bu uzantılara sahip dosyalar, adlarından bağımsız olarak otomatik olarak metin dosyaları olarak kabul edilir. - -Uzantı tabanlı algılamaya ek olarak, method geliştirme projelerinde yaygın olarak görünen belirli basename kalıplarını kontrol eder. Bunlar, standart uzantılara sahip olmayabilecek ancak önemli metinsel içerik içeren Dockerfile, Makefile, LICENSE, README ve CHANGELOG gibi dosyaları içerir. Method, dosya adı içinde bu kalıplar için büyük/küçük harf duyarsız bir arama yapar ve readme.md, LICENSE.txt veya CHANGELOG gibi varyasyonlara izin verir. - -Bu çift kriterli yaklaşım, hem geleneksel adlandırma kalıplarını hem de geliştirme iş akışlarındaki yaygın istisnaları barındıran esnek dosya algılama sağlar. Uzantı ve basename analizini birleştirerek sistem, çeşitli proje yapıları ve adlandırma kurallarında metin dosyalarını doğru bir şekilde tanımlayabilir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L306-L321) - -## Dosya Filtreleme ve Token Sayma İlişkisi - -Dosya filtreleme, analiz sürecine hangi dosyaların dahil edildiğini belirleyerek token sayımını doğrudan etkiler. Filtreleme hattı, dosyaların tokenleri sayılmadan önce geçmesi gereken bir dizi kapı olarak çalışır. Yalnızca tüm filtreleme aşamalarını atlatan dosyalar token hesaplaması için işlenir ve nihai token sayısının yalnızca codebase'in istenen alt kümesini yansıtmasını sağlar. - -Filtreleme işlemi belirli bir sırada gerçekleşir: önce .gitignore kuralları uygulanır, ardından calculator'a özgü kurallar (.contextinclude veya .contextignore) ve son olarak metin dosyası kontrolü yapılır. Bu dizi, açıkça alakasız dosyaların (node_modules içindekiler gibi) erken hariç tutulmasını sağlar ve gereksiz işlemlerden kaçınarak performansı artırır. Tüm filtreleri geçen dosyalar daha sonra tiktoken kütüphanesini kullanarak tam sayım için veya tiktoken mevcut olmadığında bir tahmin algoritması kullanarak token sayılarını belirlemek üzere analiz edilir. - -Filtreleme ve token sayımı arasındaki ilişki, hem dahil edilen hem de hariç tutulan dosyalar hakkında ayrıntılı istatistikler sağlayan aracın çıktısında yansıtılır. Bu şeffaflık, kullanıcıların filtreleme kararlarının nihai token sayısını tam olarak nasıl etkilediğini anlamalarına ve yapılandırma dosyalarını buna göre ayarlamalarına olanak tanır. Sistem ayrıca .gitignore kuralları nedeniyle ignore edilen dosyalarla calculator kuralları tarafından filtrelenen dosyaları ayırt eder ve hangi yapılandırma dosyalarının analiz kapsamını şekillendirmede en etkili olduğuna dair fikir verir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L385-L412) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L306-L321) - -## İstatistik Takibi - -TokenCalculator sınıfı, birden fazla boyutta hem dahil edilen hem de hariç tutulan dosyaları izleyerek analiz süreci hakkında kapsamlı istatistikler tutar. İstatistikler, toplam dosyalar, tokenler, byte'lar, satırlar ve çeşitli kategorizasyonlar için sayaçlarla başlatılan stats nesnesinde saklanır. - -Dosyalar işlenirken, updateStats methodu uygun sayaçları artırır ve uzantıya özgü ve dizine özgü istatistikleri günceller. Her dosya, genel toplamların yanı sıra byExtension ve byDirectory ayrımlarını da doldurarak codebase bileşiminin ayrıntılı analizine olanak tanır. largestFiles dizisi, token sayısına göre en önemli dosyaların kaydını tutar ve potansiyel optimizasyon hedeflerinin belirlenmesini sağlar. - -Sistem, ignore edilen dosyaları ayrı olarak izler ve .gitignore kuralları tarafından hariç tutulanlarla calculator kuralları tarafından filtrelenenler arasında ayrım yapar. Bu ayrım, farklı filtreleme stratejilerinin etkinliği hakkında değerli geri bildirim sağlar ve kullanıcıların yapılandırma seçimlerinin etkisini anlamalarına yardımcı olur. countIgnoredFiles methodu, ignore edilen dizinler içindeki dosyaları özyinelemeli olarak sayar ve tüm dizin ağaçları hariç tutulduğunda bile doğru istatistikler sağlar. - -Bu istatistikler, özet metrikler, uzantı ayrımları ve en büyük dosya ve dizinlerin sıralamasını içeren nihai analiz raporunu oluşturmak için kullanılır. Bu kapsamlı raporlama, kullanıcıların codebase yapıları ve filtreleme yapılandırmaları hakkında bilinçli kararlar almalarını sağlar. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L455-L489) -- [context-manager.js](file://context-manager.js#L715-L743) -- [context-manager.js](file://context-manager.js#L673-L696) - -## Yaygın Sorunlar ve Optimizasyon - -Dosya seviyesi analiz yapılandırılırken, öncelikle yanlış yapılandırılmış ignore kalıplarıyla veya büyük dizinlerle performans darboğazlarıyla ilgili birkaç yaygın sorun ortaya çıkabilir. Sık karşılaşılan sorunlardan biri, negation kalıplarının daha genel kalıplardan sonra yerleştirilmesi ve bunların etkisiz olmasına neden olması gibi include/exclude kurallarının yanlış sıralanmasıdır. Kullanıcılar, istenen filtreleme davranışını elde etmek için negation kalıplarının (! ile başlayanlar) yapılandırma dosyalarında uygun şekilde konumlandırıldığından emin olmalıdır. - -Bir diğer yaygın sorun, gerekli dosyaları hariç tutan veya çok fazla alakasız dosya içeren aşırı geniş kalıpların kullanılmasıdır. Örneğin, **/*.js kullanmak, LLM context'inden hariç tutulması gereken test dosyalarını veya oluşturulan kodu içerebilir. Tersine, aşırı spesifik kalıplar önemli dosyaları kaçırabilir. Kullanıcılar, kalıplarını dikkatlice gözden geçirmeli ve beklenen dosyaların dahil edildiğini veya hariç tutulduğunu doğrulamak için aracın ayrıntılı çıktısını kullanmalıdır. - -Performans darboğazları, çok büyük dizinler analiz edilirken veya filtreleme yapılandırması kapsamlı pattern matching gerektirdiğinde ortaya çıkabilir. Performansı optimize etmek için kullanıcılar, analiz kapsamını yalnızca temel dosyalarla sınırlamak için hassas include kuralları kullanmalıdır. Geniş hariç tutmalarla yalnızca .contextignore'a güvenmek yerine belirli kalıplarla .contextinclude kullanmak, işlenmesi gereken dosya sayısını azaltarak performansı önemli ölçüde artırabilir. - -Ek optimizasyon stratejileri, mümkün olduğunda özyinelemeli wildcardlardan (**/) kaçınmayı içerir, çünkü bunlar daha kapsamlı dosya sistemi geçişi gerektirir ve en sık eşleşen kalıpların yapılandırma dosyalarında ilk sırada listelenmesini sağlayarak gereken pattern karşılaştırmalarının sayısını en aza indirir. Aracın istatistiklerine dayalı olarak filtreleme yapılandırmasını düzenli olarak gözden geçirmek ve iyileştirmek, optimal performans ve doğruluğu korumaya yardımcı olabilir. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L385-L412) -- [context-manager.js](file://context-manager.js#L124-L229) -- [context-manager.js](file://context-manager.js#L306-L321) diff --git a/docs/content-tr/Temel-Ozellikler/Method-Seviyesi-Analiz.md b/docs/content-tr/Temel-Ozellikler/Method-Seviyesi-Analiz.md deleted file mode 100644 index bc892f0..0000000 --- a/docs/content-tr/Temel-Ozellikler/Method-Seviyesi-Analiz.md +++ /dev/null @@ -1,269 +0,0 @@ -# Method Seviyesi Analiz - - -**Bu Belgedeki Referans Dosyalar** -- [context-manager.js](file://context-manager.js) - *Son commit'te güncellendi* -- [README.md](file://README.md) - *Son commit'te güncellendi* -- [CLAUDE.md](file://CLAUDE.md) -- [index.js](file://index.js) -- [bin/cli.js](file://bin/cli.js) - *Son commit'te güncellendi* -- [lib/analyzers/method-analyzer.js](file://lib/analyzers/method-analyzer.js) - *Son commit'te eklendi* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Son commit'te eklendi* - - -## İçindekiler -1. [Giriş](#giriş) -2. [Method Çıkarma Süreci](#method-çıkarma-süreci) -3. [Method Analiz Entegrasyonu](#method-analiz-entegrasyonu) -4. [Method Filtreleme Mekanizması](#method-filtreleme-mekanizması) -5. [Method İstatistikleri ve Raporlama](#method-i̇statistikleri-ve-raporlama) -6. [LLM Context Oluşturma](#llm-context-oluşturma) -7. [Yaygın Sorunlar ve En İyi Uygulamalar](#yaygın-sorunlar-ve-en-i̇yi-uygulamalar) - -## Giriş - -context-manager aracı, JavaScript ve TypeScript codebase'lerinin granüler incelemesini sağlayan method seviyesi analiz yetenekleri sunar. Bu özellik, geliştiricilerin kaynak dosyalardan bireysel methodları çıkarmasına, analiz etmesine ve filtrelemesine olanak tanıyarak LLM context oluşturma için optimize edilmiş temsiller oluşturur. Method seviyesi analiz, `methodLevel` seçeneği aracılığıyla kontrol edilir ve method içeriğini işlemek ve ayrıntılı istatistikler oluşturmak için TokenCalculator ile entegre olur. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L234-L238) -- [bin/cli.js](file://bin/cli.js#L17-L18) - -## Method Çıkarma Süreci - -MethodAnalyzer sınıfı, regex kalıplarını kullanarak kaynak koddan JavaScript/TypeScript methodlarını çıkarmaktan sorumludur. Farklı function bildirimi stillerini eşleştiren birden fazla kalıp aracılığıyla methodları tanımlar: - -```mermaid -flowchart TD -Start([Method Çıkarmaya Başla]) --> Pattern1["Pattern 1: Named functions
(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\("] -Pattern1 --> Pattern2["Pattern 2: Object methods
(\w+)\s*:\s*(?:async\s+)?function\s*\("] -Pattern2 --> Pattern3["Pattern 3: Arrow functions
(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>"] -Pattern3 --> Pattern4["Pattern 4: Getters/Setters
(?:get|set)\s+(\w+)\s*\("] -Pattern4 --> Pattern5["Pattern 5: Method shorthand
(?:async\s+)?(\w+)\s*\([^)]*\)\s*\{"] -Pattern5 --> Extract["Method Adı ve Satır Numarasını Çıkar"] -Extract --> KeywordCheck["Adın Reserved Keyword Olup Olmadığını Kontrol Et"] -KeywordCheck --> |Hayır| Store["Method'u Map'te Sakla
(key: name:line)"] -KeywordCheck --> |Evet| Skip["Reserved Keyword'leri Atla"] -Store --> NextPattern["Sonraki Pattern'ı İşle"] -NextPattern --> End([Method Dizisini Döndür]) -``` - -Çıkarma işlemi, JavaScript/TypeScript kodundaki farklı method bildirimi stillerini tanımlamak için beş regex kalıbı uygulayan `extractMethods` fonksiyonuyla başlar. Her eşleşme için analyzer, method adını yakalar ve dosyanın başından eşleşme indeksine kadar yeni satırları sayarak satır numarasını hesaplar. Analyzer, yanlış pozitifleri önlemek için reserved JavaScript keywordlerini filtreler. - -Bir methodun tam içeriğini almak için `extractMethodContent` fonksiyonu, iç içe süslü parantezler dahil olmak üzere tam method gövdesiyle eşleşen dinamik olarak oluşturulmuş regex kalıplarını kullanır. Bu, aracın yalnızca method imzasını değil, token hesaplaması için tüm implementasyonu çıkarmasına olanak tanır. - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L15-L45) -- [context-manager.js](file://context-manager.js#L61-L72) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L14-L73) - -## Method Analiz Entegrasyonu - -analyzeFileMethods fonksiyonu, method içeriğini işlemek ve tokenleri hesaplamak için method çıkarımını TokenCalculator ile entegre eder. Bu entegrasyon, TokenCalculator constructor'ında `methodLevel` seçeneği etkinleştirildiğinde gerçekleşir. - -```mermaid -sequenceDiagram -participant TokenCalculator -participant MethodAnalyzer -participant TokenCalculator as TokenCalculator -participant MethodFilterParser -TokenCalculator->>TokenCalculator : analyzeFile(filePath) -TokenCalculator->>TokenCalculator : Dosya içeriğini oku -alt methodLevel etkin -TokenCalculator->>TokenCalculator : analyzeFileMethods(content, filePath) -TokenCalculator->>MethodAnalyzer : extractMethods(content, filePath) -MethodAnalyzer-->>TokenCalculator : Method dizisini döndür -TokenCalculator->>TokenCalculator : filteredMethods'u başlat -TokenCalculator->>TokenCalculator : methodStats.totalMethods'u artır -loop Her method için -TokenCalculator->>MethodFilterParser : shouldIncludeMethod(method.name, fileName) -alt Method filtreden geçer -TokenCalculator->>MethodAnalyzer : extractMethodContent(content, method.name) -MethodAnalyzer-->>TokenCalculator : Method içeriğini döndür -TokenCalculator->>TokenCalculator : calculateTokens(methodContent, filePath) -TokenCalculator->>TokenCalculator : methodInfo nesnesi oluştur -TokenCalculator->>TokenCalculator : filteredMethods'a ekle -TokenCalculator->>TokenCalculator : methodStats.includedMethods'u artır -TokenCalculator->>TokenCalculator : methodTokens'ı sakla -end -end -TokenCalculator-->>TokenCalculator : filteredMethods döndür -end -TokenCalculator-->>TokenCalculator : methodlar ile fileInfo döndür -``` - -Entegrasyon işlemi, method seviyesi analizin etkin olup olmadığını kontrol eden TokenCalculator'ın `analyzeFile` methodunda başlar. Etkinse, dosya içeriğini işlemek için `analyzeFileMethods`'u çağırır. Bu fonksiyon önce MethodAnalyzer'ı kullanarak tüm methodları çıkarır, ardından filtreleme kurallarına göre dahil edilip edilmeyeceğini belirlemek için her method üzerinde iterasyon yapar. - -Dahil edilen her method için sistem, method içeriğini çıkarır ve tüm dosyalar için kullanılan mekanizmanın aynısını kullanarak tokenleri hesaplar. Token hesaplaması, mevcut olduğunda GPT-4 uyumlu tam sayımlar için tiktoken kütüphanesini kullanır, tiktoken yüklü olmadığında dosya türü başına karakter sayısına dayalı tahmini hesaplamaya geçer. - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L323-L383) -- [context-manager.js](file://context-manager.js#L234-L238) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L323-L383) - -## Method Filtreleme Mekanizması - -Method filtreleme mekanizması, `.methodinclude` ve `.methodignore` dosyalarında tanımlanan kurallara göre hangi methodların analize dahil edilmesi gerektiğini belirlemek için MethodFilterParser sınıfını kullanır. Bu filtreleme sistemi, method seçimi üzerinde ince ayarlı kontrol sağlar. - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : boolean --methodIncludePath : string --methodIgnorePath : string -+constructor(methodIncludePath, methodIgnorePath) -+parseMethodFile(filePath) Array -+shouldIncludeMethod(methodName, fileName) boolean -} -class MethodAnalyzer { -+extractMethods(content, filePath) Array -+extractMethodContent(content, methodName) string -+getLineNumber(content, index) number -+isKeyword(name) boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+methodStats : Object -+analyzeFileMethods(content, filePath) Array -+generateMethodContext(analysisResults) Object -} -TokenCalculator --> MethodFilterParser : "filtreleme için kullanır" -TokenCalculator --> MethodAnalyzer : "çıkarma için kullanır" -MethodFilterParser --> "methodinclude file" : "okur" -MethodFilterParser --> "methodignore file" : "okur" -``` - -MethodFilterParser, `.methodinclude` ve `.methodignore` dosyalarından kalıpları okur ve her satırı büyük/küçük harf duyarsız bir regex kalıbına dönüştürür. Filtreleme davranışı, bir include dosyasının var olup olmamasına bağlıdır: - -- `.methodinclude` mevcut olduğunda: Yalnızca include kalıplarıyla eşleşen methodlar dahil edilir (INCLUDE modu) -- Yalnızca `.methodignore` mevcut olduğunda: Ignore kalıplarıyla eşleşen methodlar hariç tutulur (EXCLUDE modu) - -`shouldIncludeMethod` fonksiyonu, hem method adını hem de tam nitelikli adı (filename.method) kalıplara karşı değerlendirir. Bu, hem genel pattern matching (örneğin, "Handler" ile biten tüm methodları eşleştirmek için `*Handler`) hem de spesifik method hedeflemeye (örneğin, `server.handleRequest`) izin verir. - -Sistem, bu yapılandırma dosyalarını iki konumda arar: script dizini ve proje kökü, proje kökü öncelik alır. Bu, hem global hem de projeye özgü yapılandırmaya izin verir. - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L75-L115) -- [context-manager.js](file://context-manager.js#L14-L73) -- [context-manager.js](file://context-manager.js#L231-L800) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L75-L115) -- [README.md](file://README.md#L481-L500) - -## Method İstatistikleri ve Raporlama - -Method analiz özelliği, analiz sırasında işlenen methodlar hakkında temel metrikleri izleyen methodStats nesnesinde istatistikleri toplar. Bu istatistikler, codebase yapısı hakkında bilgi sağlamak için nihai rapora dahil edilir. - -```mermaid -erDiagram -METHOD_STATS { -integer totalMethods -integer includedMethods -object methodTokens -} -METHOD_TOKENS { -string methodKey -integer tokenCount -} -ANALYSIS_RESULTS { -string relativePath -array methods -} -METHOD_STATS ||--o{ METHOD_TOKENS : "içerir" -ANALYSIS_RESULTS ||--o{ METHOD_STATS : "referans verir" -``` - -methodStats nesnesi üç özellik içerir: -- `totalMethods`: Tüm analiz edilen dosyalarda bulunan toplam method sayısı -- `includedMethods`: Filtreleme kriterlerinden geçen method sayısı -- `methodTokens`: Method tanımlayıcılarını (filename.methodname) token sayılarına eşleyen bir nesne - -Bu istatistikler, method analiz süreci sırasında güncellenir. `totalMethods` sayacı, her dosyadan çıkarılan method sayısıyla artırılırken, `includedMethods` filtreyi geçen her method için artırılır. `methodTokens` nesnesi, her dahil edilen method için token sayısını saklar ve method karmaşıklığının ayrıntılı analizini sağlar. - -İstatistikler, method seviyesi analiz etkinleştirildiğinde nihai LLM context'ine dahil edilir ve ayrıntılı method bilgilerinin yanı sıra method analiz sonuçlarının bir özetini sağlar. - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L239-L239) -- [context-manager.js](file://context-manager.js#L491-L519) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L239-L239) -- [context-manager.js](file://context-manager.js#L491-L519) - -## LLM Context Oluşturma - -Method seviyesi analiz, dil modelleri tarafından verimli bir şekilde tüketilebilecek methodların kompakt temsillerini oluşturarak LLM context oluşturmayı doğrudan destekler. Method seviyesi analiz etkinleştirildiğinde, generateLLMContext fonksiyonu farklı bir çıktı yapısı üretir. - -```mermaid -flowchart TD -Start([generateLLMContext]) --> CheckMethodLevel{"methodLevel etkin mi?"} -CheckMethodLevel --> |Evet| GenerateMethodContext["generateMethodContext(analysisResults)"] -GenerateMethodContext --> CreateMethodsObject["Methods nesnesi oluştur:
- relativePath
- method adı
- satır numarası
- token sayısı"] -CreateMethodsObject --> AddMethodStats["methodStats'ı context'e ekle"] -AddMethodStats --> ReturnContext["methodlar ve methodStats ile context döndür"] -CheckMethodLevel --> |Hayır| GenerateCompactPaths["generateCompactPaths(analysisResults)"] -GenerateCompactPaths --> ReturnPaths["paths ile context döndür"] -ReturnContext --> End([Context döndür]) -ReturnPaths --> End -``` - -Method seviyesi analiz etkinleştirildiğinde, oluşturulan context methodları göreli dosya yollarına göre düzenleyen bir `methods` özelliği içerir. Her method, adı, satır numarası ve token sayısı ile temsil edilir ve tam method içeriğini içermeden temel bilgileri sağlar. Bu, codebase'in yapısını ve göreli karmaşıklığını koruyan kompakt bir temsil oluşturur. - -Context ayrıca, bulunan toplam methodlar, dahil edilen methodlar ve toplam method tokenleri hakkında toplu bilgiler içeren `methodStats`'ı içerir. Bu özet, kullanıcıların analizin kapsamını ve nihai context'e dahil edilen methodların oranını anlamalarına yardımcı olur. - -Kompakt temsil, önemli yapısal bilgileri korurken context'in token sayısını önemli ölçüde azaltır ve context window boyutunun sınırlı olduğu LLM tüketimi için ideal hale getirir. - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L491-L519) -- [context-manager.js](file://context-manager.js#L614-L643) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L491-L519) - -## Yaygın Sorunlar ve En İyi Uygulamalar - -### Yaygın Sorunlar - -**Yanlış Method Çıkarımı**: Regex tabanlı çıkarım, aşağıdaki gibi karmaşık sözdiziminde başarısız olabilir: -- Parametrelerde template literalleri olan methodlar -- Karmaşık destructuring kalıpları olan methodlar -- Minified veya obfuscated kod -- Pattern matching'i bozan alışılmadık formatlama - -**Pattern Matching Sorunları**: Kullanıcılar, aşağıdaki nedenlerle filter kalıplarıyla ilgili sorunlarla karşılaşabilir: -- Büyük/küçük harf duyarlılığı (kalıplar büyük/küçük harf duyarsızdır ancak tam eşleşme gerekli olabilir) -- Method adlarındaki özel karakterler -- Çakışan include/exclude kuralları -- Tam nitelikli method adlarında yanlış dosya yolları - -### Method Filter Kalıpları için En İyi Uygulamalar - -**Etkili Include Kalıpları**: -- Kritik business logic için spesifik method adları kullanın: `calculateTokens`, `handleRequest` -- Method kategorileri için wildcardlar kullanın: `*Handler`, `*Validator`, `*Manager` -- Class tabanlı kalıplar kullanın: Bir class'taki tüm methodları dahil etmek için `TokenCalculator.*` -- İlgili işlevselliği yakalamak için `.methodinclude`'da birden fazla kalıbı birleştirin - -**Etkili Ignore Kalıpları**: -- Test methodlarını hariç tutun: `*test*`, `*spec*` -- Debug methodlarını hariç tutun: `*debug*`, `console`, `logger` -- Utility methodlarını hariç tutun: `*helper*`, `*util*` -- Gerekli değilse lifecycle methodlarını hariç tutun: `componentDidMount`, `ngOnInit` - -**Yapılandırma Yönetimi**: -- Projeye özgü kurallar için `.methodinclude` ve `.methodignore`'ı proje kökünde yerleştirin -- Pattern amaçlarını belgelemek için yorumları (# ile başlayan satırlar) kullanın -- Büyük projelere uygulamadan önce küçük bir codebase ile kalıpları test edin -- Hangi methodların dahil edildiğini/hariç tutulduğunu doğrulamak için verbose modunu kullanın - -Method seviyesi analiz özelliği, LLM context oluşturmayı optimize etmek için güçlü yetenekler sağlar, ancak doğru ve yararlı sonuçlar elde etmek için dikkatli yapılandırma gerektirir. Bu en iyi uygulamaları izleyerek kullanıcılar, gürültü ve boilerplate kodu hariç tutarken en önemli methodları yakalayan etkili filter kalıpları oluşturabilir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L481-L500) -- [CLAUDE.md](file://CLAUDE.md#L101-L127) diff --git a/docs/content-tr/Temel-Ozellikler/Token-Sayma.md b/docs/content-tr/Temel-Ozellikler/Token-Sayma.md deleted file mode 100644 index b670b22..0000000 --- a/docs/content-tr/Temel-Ozellikler/Token-Sayma.md +++ /dev/null @@ -1,267 +0,0 @@ -# Token Sayma - - -**Bu Belgedeki Referans Dosyalar** -- [context-manager.js](file://context-manager.js) - *Son commit'te güncellendi* -- [package.json](file://package.json) -- [README.md](file://README.md) - *Son commit'te güncellendi* -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Son commit'te eklendi* - - -## İçindekiler -1. [Giriş](#giriş) -2. [Token Hesaplama Yöntemleri](#token-hesaplama-yöntemleri) -3. [tiktoken ile Tam Token Sayımı](#tiktoken-ile-tam-token-sayımı) -4. [Tahmini Token Sayımı Implementasyonu](#tahmini-token-sayımı-implementasyonu) -5. [Dosya Türüne Özgü Örnekler](#dosya-türüne-özgü-örnekler) -6. [Dosya ve Proje İstatistikleriyle Entegrasyon](#dosya-ve-proje-i̇statistikleriyle-entegrasyon) -7. [LLM Context Oluşturma](#llm-context-oluşturma) -8. [Performans Etkileri](#performans-etkileri) -9. [Yaygın Sorunlar ve Sorun Giderme](#yaygın-sorunlar-ve-sorun-giderme) -10. [Kurulum ve Yapılandırma](#kurulum-ve-yapılandırma) - -## Giriş - -context-manager aracı, LLM context yönetimi ve kod analizini desteklemek için sofistike token sayma işlevselliği sağlar. Sistem, tam GPT-4 uyumlu hesaplamaları akıllı tahmin yöntemleriyle birleştirerek token sayımına ikili bir yaklaşım uygular. Bu dokümantasyon, context-manager aracı içindeki token sayma sisteminin implementasyonunu, kullanımını ve entegrasyonunu detaylandırır. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L7-L8) -- [README.md](file://README.md#L294-L356) - -## Token Hesaplama Yöntemleri - -context-manager'daki token sayma sistemi, token sayılarını belirlemek için iki tamamlayıcı method uygular: tiktoken kütüphanesini kullanarak tam sayım ve karakter-başına-token oranlarını kullanarak tahmini sayım. Sistem, kütüphane kullanılabilirliğine ve performans gereksinimlerine göre uygun methodu otomatik olarak seçer. - -Token hesaplaması için birincil giriş noktası, tam ve tahmini sayım methodları arasında dağıtıcı olarak hizmet eden `TokenCalculator` sınıfındaki `calculateTokens` methodudur. tiktoken mevcut olduğunda, sistem tam sayım kullanır; aksi takdirde, tahmini hesaplamaya geçer. - -```mermaid -flowchart TD -Start([calculateTokens]) --> CheckTiktoken{"tiktoken mevcut mu?"} -CheckTiktoken --> |Evet| ExactCounting["tiktoken.encode() kullan"] -CheckTiktoken --> |Hayır| EstimateCounting["estimateTokens() kullan"] -ExactCounting --> ReturnExact["Tam token sayısını döndür"] -EstimateCounting --> ReturnEstimate["Tahmini token sayısını döndür"] -ReturnExact --> End([Method tamamlandı]) -ReturnEstimate --> End -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L280-L292) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L280-L292) - -## tiktoken ile Tam Token Sayımı - -context-manager aracı, mevcut olduğunda tam GPT-4 uyumlu token sayımları sağlamak için tiktoken kütüphanesini kullanır. Implementasyon, başlatma sırasında tiktoken'ı yüklemeye çalışan ve kütüphane mevcut değilse tahmini hesaplamaya geçen zarif bir bozulma modeli izler. - -Tam token sayma işlemi, GPT-4, GPT-3.5-Turbo ve diğer modeller tarafından kullanılan tokenizer olan cl100k_base encoding'ini kullanır. Bu, token sayılarının bu modellerin metni nasıl işleyeceğinin doğru temsilleri olmasını sağlar. - -```mermaid -sequenceDiagram -participant Calculator as TokenCalculator -participant Tiktoken as tiktoken Library -participant Encoding as cl100k_base Encoding -Calculator->>Calculator : calculateTokens(content, filePath) -Calculator->>Tiktoken : tiktoken'ın mevcut olup olmadığını kontrol et -alt tiktoken mevcut -Calculator->>Encoding : get_encoding('cl100k_base') -Encoding-->>Calculator : Encoding instance döndür -Calculator->>Encoding : encode(content) -Encoding-->>Calculator : Token dizisi döndür -Calculator->>Encoding : free() bellek -Calculator->>Calculator : Token sayısını döndür -else tiktoken mevcut değil -Calculator->>Calculator : estimateTokens() çağır -end -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L280-L292) -- [package.json](file://package.json#L35-L38) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L280-L292) -- [package.json](file://package.json#L35-L38) - -## Tahmini Token Sayımı Implementasyonu - -tiktoken kütüphanesi mevcut olmadığında, context-manager aracı uzantıya özgü karakter-başına-token oranları kullanan bir tahmin methoduna geri döner. Bu yaklaşım, performansı korurken ve bağımlılıkları azaltırken makul derecede doğru tahminler (~%95 doğruluk) sağlar. - -Tahmin algoritması şu adımları izler: -1. filePath parametresinden dosya uzantısını belirle -2. Uzantıya dayalı uygun karakter-başına-token oranını ara -3. Whitespace'i normalize ederek metni temizle -4. Karakter oranını kullanarak tahmini token sayısını hesapla - -```mermaid -flowchart TD -Start([estimateTokens]) --> ExtractExt["Dosya uzantısını çıkar"] -ExtractExt --> LookupRatio["charsPerToken oranını ara"] -LookupRatio --> CleanText["Metni temizle: \\s+ yerine tek space"] -CleanText --> Calculate["Hesapla: Math.ceil(cleanText.length / charsPerToken)"] -Calculate --> Return["Tahmini token sayısını döndür"] -``` - -Implementasyon, yaygın dosya türleri için spesifik karakter-başına-token oranlarını içerir: -- JavaScript/TypeScript: Token başına 3.2 karakter -- JSON: Token başına 2.5 karakter -- Markdown/Text: Token başına 4.0 karakter -- YAML: Token başına 3.5 karakter -- HTML/XML: Token başına 2.8 karakter - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L294-L304) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L294-L304) - -## Dosya Türüne Özgü Örnekler - -Token sayma sistemi, tahmin methodundaki uzantıya özgü karakter-başına-token oranları aracılığıyla farklı dosya türlerini uygun şekilde işler. tiktoken aracılığıyla tam sayım mevcut olduğunda, sistem dosya türünden bağımsız olarak doğru sayımlar sağlar. - -JavaScript dosyaları (.js, .ts, .jsx, .tsx) için sistem, bu dillerdeki kodun tipik yoğunluğunu yansıtan token başına 3.2 karakter oranı kullanır. Markdown ve düz metin dosyaları, dokümantasyondaki daha yüksek boşluk ve formatlama oranını hesaba katarak daha cömert token başına 4.0 karakter kullanır. - -JSON, YAML ve XML gibi yapılandırma dosyaları, yapısal özelliklerini yansıtan kendilerine özgü oranlara sahiptir. JSON, süslü parantezler, köşeli parantezler ve tırnak işaretleriyle kompakt sözdizimi nedeniyle token başına 2.5 karakter kullanırken, XML ve HTML tag ayrıntılılığını hesaba katmak için token başına 2.8 karakter kullanır. - -Sistem, bir dosyanın metin dosyası olarak analiz edilip edilmeyeceğini, hem dosya uzantılarını hem de "readme", "license" ve "changelog" gibi yaygın metin dosyası adlarını kontrol eden `isTextFile` methodu aracılığıyla belirler. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L294-L304) -- [context-manager.js](file://context-manager.js#L306-L321) - -## Dosya ve Proje İstatistikleriyle Entegrasyon - -Token sayıları, codebase boyutu ve karmaşıklığının kapsamlı analizini sağlayan dosya ve proje istatistik sistemi boyunca entegre edilir. `analyzeFile` methodu, her dosya için `calculateTokens`'ı çağırır ve sonuçları ayrıntılı istatistiklere dahil eder. - -Sistem, birden fazla istatistiksel toplama seviyesini tutar: -- Token sayısı, byte cinsinden boyut ve satır sayısı dahil dosya başına istatistikler -- Aynı türdeki tüm dosyalarda sayıları toplayan uzantı seviyesi istatistikler -- Üst düzey dizine göre token dağılımını gösteren dizin seviyesi istatistikler -- Proje seviyesi özet istatistikler - -Bu istatistikler, dosya bilgilerini işleyen ve tüm proje için toplamları biriktiren `updateStats` methodunda güncellenir. İstatistikler, hem ham sayıları hem de dosya başına ortalama tokenler gibi türetilmiş metrikleri içerir. - -```mermaid -classDiagram -class TokenCalculator { -+stats : StatsObject -+analyzeFile(filePath) : FileInfo -+updateStats(fileInfo) : void -+calculateTokens(content, filePath) : number -+estimateTokens(content, filePath) : number -} -class FileInfo { -+path : string -+relativePath : string -+sizeBytes : number -+tokens : number -+lines : number -+extension : string -} -class StatsObject { -+totalFiles : number -+totalTokens : number -+totalBytes : number -+totalLines : number -+byExtension : Map[string, ExtStats] -+byDirectory : Map[string, DirStats] -+largestFiles : FileInfo[] -} -class ExtStats { -+count : number -+tokens : number -+bytes : number -+lines : number -} -class DirStats { -+count : number -+tokens : number -+bytes : number -+lines : number -} -TokenCalculator --> FileInfo : "üretir" -TokenCalculator --> StatsObject : "günceller" -StatsObject --> ExtStats : "içerir" -StatsObject --> DirStats : "içerir" -``` - -**Diyagram kaynakları** -- [context-manager.js](file://context-manager.js#L323-L351) -- [context-manager.js](file://context-manager.js#L455-L480) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L323-L351) -- [context-manager.js](file://context-manager.js#L455-L480) - -## LLM Context Oluşturma - -Token sayıları, AI tüketimi için optimize edilmiş dosya listeleri oluşturan `generateLLMContext` methodu aracılığıyla LLM context oluşturmayı doğrudan etkiler. Context oluşturma süreci, LLM işleme için en alakalı dosyaları ve methodları önceliklendirmek için token istatistiklerini kullanır. - -Method seviyesi analiz etkinleştirildiğinde, sistem bireysel methodlar için token sayıları dahil olmak üzere ayrıntılı method context'i oluşturur. Bu, hangi kod öğelerinin LLM context'ine dahil edileceği üzerinde ince ayarlı kontrol sağlar. - -Context oluşturma iki formatı destekler: -- Kompakt format: Token sayıları olmadan düzenlenmiş dosya yolları (~2.3k karakter) -- Detaylı format: Token sayılarıyla tam method seviyesi bilgisi (~8.6k karakter) - -Format seçimi, kompakt format dosya organizasyonuna odaklanırken ve detaylı format her method için kapsamlı token bilgisi sağlarken, token sayılarının çıktıda nasıl sunulduğunu etkiler. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L482-L503) - -## Performans Etkileri - -Token sayma sistemi, ikili method yaklaşımı aracılığıyla doğruluk ve performansı dengeler. tiktoken ile tam sayım, kesin GPT-4 uyumlu sonuçlar sağlar ancak kütüphane yükleme ve encoding işlemlerinden ek yük getirir. Tahmini sayım daha hızlıdır ve harici bağımlılığı yoktur ancak yaklaşık sonuçlar sağlar. - -Her methodun performans etkileri şunlardır: -- **Tam sayım**: Daha yüksek doğruluk (%100), daha yavaş performans, tiktoken bağımlılığı gerektirir -- **Tahmini sayım**: Daha düşük doğruluk (~%95), daha hızlı performans, harici bağımlılık gerektirmez - -Sistem, mevcut olduğunda tam sayımı tercih edecek şekilde tasarlanmıştır; bu, kütüphane başarıyla yüklendiğinde "✅ Exact (using tiktoken)" gösteren başlangıç mesajıyla belirtilir. tiktoken mevcut olmadığında, sistem "⚠️ Estimated" göstergesiyle tahmini hesaplamaya geçer. - -Büyük codebase'ler için performans farkı daha önemli hale gelir ve mutlak hassasiyet gerekli olmadığında tahmini sayımı tercih edilir kılar. Tahmin methodunun metin temizleme ve basit bölme için O(n) karmaşıklığı, büyük dosyalar için bile oldukça verimli olmasını sağlar. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L659-L659) -- [README.md](file://README.md#L294-L356) - -## Yaygın Sorunlar ve Sorun Giderme - -context-manager aracındaki token sayımıyla ilgili yaygın sorunlar genellikle standart olmayan dosya türleri için yanlış tahminler veya tiktoken kurulum sorunlarıyla ilgilidir. En sık karşılaşılan sorunlar şunlardır: - -1. **Standart olmayan dosya türleri için yanlış tahminler**: Bir dosya, önceden tanımlanmış eşlemede yer almayan alışılmadık bir uzantıya sahip olduğunda, sistem varsayılan olarak token başına 3.5 karakter oranı kullanır. Bu, özel dosya formatları için yanlış tahminlere yol açabilir. - -2. **tiktoken yüklü değil**: tiktoken kütüphanesi düzgün şekilde yüklenmemişse, sistem tahmini moduna geri döner. Bu, yürütme sırasında "⚠️ Estimated" mesajıyla tanımlanabilir. - -3. **İzin sorunları**: Bazı sistemlerde, tiktoken gibi native bağımlılıkları yüklemek yükseltilmiş izinler veya belirli build araçları gerektirebilir. - -4. **Versiyon uyumluluğu**: package.json, tiktoken version ^1.0.0 belirtir ve versiyon uyumsuzlukları yükleme hatalarına neden olabilir. - -Token sayma sorunlarını gidermek için kullanıcılar önce tiktoken kurulumunu doğrulamalı ve tam veya tahmini sayımın kullanılıp kullanılmadığını onaylamak için başlangıç mesajını kontrol etmelidir. - -**Bölüm kaynakları** -- [package.json](file://package.json#L35-L38) -- [README.md](file://README.md#L294-L356) - -## Kurulum ve Yapılandırma - -Tam token sayımını sağlamak için tiktoken kütüphanesinin düzgün şekilde yüklenmesi gerekir. context-manager aracı, tiktoken'ı package.json'da hem dependency hem de optionalDependency olarak listeler; bu, tam sayım için kurulumu teşvik ederken aracın onsuz çalışmasına izin verir. - -Kurulum npm aracılığıyla gerçekleştirilir: -```bash -npm install tiktoken -``` - -Implementasyon, tiktoken'ı yüklemek için bir try-catch bloğu kullanır ve kütüphane mevcut olmadığında zarif bir bozulmaya izin verir: - -```javascript -let tiktoken = null; -try { tiktoken = require('tiktoken'); } catch {} -``` - -Bu kalıp, aracın tiktoken kurulumu başarısız olsa veya gerçekleştirilmese bile işlevsel kalmasını sağlarken, istendiğinde tam sayım seçeneğini hala sağlar. Başlangıç dizisi, kullanılan token hesaplama methodunu görüntüleyerek kullanıcıların kurulum durumlarını doğrulamalarına yardımcı olur. - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L7-L9) -- [package.json](file://package.json#L35-L38) -- [README.md](file://README.md#L294-L356) diff --git a/docs/content-tr/Yapilandirma/Dosya-Filtreleme.md b/docs/content-tr/Yapilandirma/Dosya-Filtreleme.md deleted file mode 100644 index 69f47f9..0000000 --- a/docs/content-tr/Yapilandirma/Dosya-Filtreleme.md +++ /dev/null @@ -1,268 +0,0 @@ -# Dosya Filtreleme - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [context-manager.js](file://context-manager.js) -- [README.md](file://README.md) - - -## İçindekiler -1. [Giriş](#giriş) -2. [Çift Modlu Filtreleme Sistemi](#çift-modlu-filtreleme-sistemi) -3. [Pattern Sözdizimi ve Örnekler](#pattern-sözdizimi-ve-örnekler) -4. [Öncelik Kuralları ve Yapilandirma Önceliği](#öncelik-kuralları-ve-yapilandirma-önceliği) -5. [Implementasyon Detayları](#implementasyon-detayları) -6. [Yaygın Sorunlar ve Sorun Giderme](#yaygın-sorunlar-ve-sorun-giderme) -7. [En İyi Uygulamalar](#en-iyi-uygulamalar) - -## Giriş - -context-manager aracı, LLM (Large Language Model) context oluşturma için kod analizini optimize etmek üzere tasarlanmış gelişmiş bir dosya filtreleme mekanizması uygular. Bu sistem, `.contextignore` ve `.contextinclude` yapilandirma dosyalarını kullanan çift modlu bir yaklaşım aracılığıyla hangi dosyaların analize dahil edildiği veya hariç tutulduğu üzerinde hassas kontrol sağlar. Filtreleme sistemi, mevcut `.gitignore` kurallarına saygı gösterirken, belirli kod bileşenlerinin odaklanmış analizi için ek kontrol katmanları sağlar. Bu dokümantasyon, kod analizi ve token hesaplamasında optimal sonuçlar elde etmek için dosya filtreleme sistemini yapılandırmanın implementasyonunu, kullanımını ve en iyi uygulamalarını detaylandırır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L610) -- [context-manager.js](file://context-manager.js#L124-L270) - -## Çift Modlu Filtreleme Sistemi - -context-manager aracı, iki tamamlayıcı yapilandirma dosyası aracılığıyla çalışan çift modlu bir filtreleme sistemi kullanır: EXCLUDE modu için `.contextignore` ve INCLUDE modu için `.contextinclude`. Bu modlar, proje gereksinimlerine göre dosya seçimi için esnek yaklaşımlar sağlar. - -### EXCLUDE Modu (.contextignore) - -EXCLUDE modu, geleneksel bir ignore sistemi olarak çalışır; burada tüm dosyalar varsayılan olarak dahil edilir, `.contextignore` dosyasında belirtilen pattern'lerle eşleşenler hariç. Bu mod, çoğu dosyanın analiz edilmesi gereken ancak belirli türlerin veya dizinlerin hariç tutulması gereken projeler için idealdir. Yapilandirma, gitignore tarzı sözdizimi takip eder ve kullanıcıların analizden filtrelenmesi gereken dosyalarla eşleşen pattern'leri belirtmesine olanak tanır. - -### INCLUDE Modu (.contextinclude) - -INCLUDE modu, belirtim yoluyla dahil etme prensibi üzerine çalışır; burada yalnızca `.contextinclude` dosyasındaki pattern'lerle eşleşen dosyalar işlenir. Bu mod, analiz kapsamı üzerinde hassas kontrol sağlar ve yalnızca açıkça tanımlanan dosyaların dahil edilmesini garanti eder. Dokümantasyon, testler veya yapilandirma dosyaları gibi çevresel dosyaları hariç tutarken core uygulama bileşenlerine analizi odaklamak için özellikle yararlıdır. - -Sistem, yapilandirma dosyalarının varlığına göre hangi modun kullanılacağını otomatik olarak belirler. Hem `.contextinclude` hem de `.contextignore` mevcut olduğunda, INCLUDE modu önceliğe sahiptir ve daha kısıtlayıcı dahil etme kurallarının uygulanmasını sağlar. - -```mermaid -graph TD -A[Start Analysis] --> B{.contextinclude exists?} -B --> |Yes| C[Activate INCLUDE Mode] -B --> |No| D{.contextignore exists?} -D --> |Yes| E[Activate EXCLUDE Mode] -D --> |No| F[Include All Files
Respect .gitignore Only] -C --> G[Process Only Files Matching
.contextinclude Patterns] -E --> H[Process All Files Except Those Matching
.contextignore Patterns] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L134-L149) -- [README.md](file://README.md#L544-L610) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L134-L149) -- [README.md](file://README.md#L544-L610) - -## Pattern Sözdizimi ve Örnekler - -Filtreleme sistemi, esnek ve hassas dosya seçimini sağlayan kapsamlı bir pattern sözdizimini destekler. Pattern'ler, negasyon ve dizin geçişi için ek özelliklerle glob tarzı eşleştirme kullanılarak işlenir. - -### Desteklenen Pattern Sözdizimi - -Sistem, birkaç temel pattern öğesini tanır: - -- `**` - Herhangi bir sayıda dizin ve alt dizini eşleştirir (recursive) -- `*` - Tek bir dizin seviyesi içindeki herhangi bir karakter dizisini eşleştirir -- `?` - Herhangi bir tek karakteri eşleştirir -- `!` - Sonraki pattern ile eşleşen dosyaları hariç tutan negasyon operatörü -- `/` - Pattern'leri belirli dizin seviyelerine sabitleyen dizin ayırıcı - -Pattern'ler, proje kökünden göreceli yollar olarak veya tüm kod tabanında eşleşecek dosya uzantıları olarak belirtilebilir. - -### Pratik Yapilandirma Örnekleri - -README, etkili yapilandirma pattern'lerinin somut örneklerini sağlar: - -Test ve workflow bileşenlerini hariç tutarken core JavaScript dosyalarına odaklanan INCLUDE modu için: -```bash -# Yalnızca core JavaScript dosyalarını dahil et -utility-mcp/src/**/*.js -!utility-mcp/src/testing/** -!utility-mcp/src/workflows/** -``` - -Dokümantasyon, yapilandirma ve test dosyalarını filtrelemek için EXCLUDE modu: -```bash -# Dokümantasyon ve config'i hariç tut -**/*.md -**/*.json -node_modules/** -test/ -**/*.test.js -**/*.spec.js -``` - -Bu örnekler, seçimi iyileştirmek için dahil etme pattern'lerini negasyon kuralları ile birleştirerek nasıl odaklanmış analiz kapsamları oluşturulacağını gösterir. - -```mermaid -flowchart TD -Start([Pattern Processing]) --> Parse["Parse Pattern String"] -Parse --> CheckNegation{"Starts with '!'?"} -CheckNegation --> |Yes| SetNegation["Set isNegation = true"] -CheckNegation --> |No| Continue["Keep isNegation = false"] -SetNegation --> RemoveNegation["Remove '!' prefix"] -Continue --> RemoveTrailing["Remove trailing '/'"] -RemoveNegation --> RemoveTrailing -RemoveTrailing --> Escape["Escape Special Regex Characters"] -Escape --> ReplaceWildcards["Replace Wildcards:
**→.*, *→[^/]*, ?→[^/]"] -ReplaceWildcards --> Anchor["Anchor Pattern:
^ if starts with /,
(^|/) otherwise"] -Anchor --> DirectoryCheck{"Ends with '/'?"} -DirectoryCheck --> |Yes| AddDirectory["Add (/.*?)? suffix"] -DirectoryCheck --> |No| AddEnd["Add $ suffix"] -AddDirectory --> CreateRegex["Create RegExp Object"] -AddEnd --> CreateRegex -CreateRegex --> Output["Return {regex, isNegation,
original, isDirectory}"] -Output --> End([Pattern Ready for Matching]) -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L159-L179) -- [README.md](file://README.md#L544-L610) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L159-L179) -- [README.md](file://README.md#L544-L610) - -## Öncelik Kuralları ve Yapilandirma Önceliği - -Dosya filtreleme sistemi, farklı yapilandirma kaynakları arasındaki potansiyel çakışmaları çözmek için net bir öncelik hiyerarşisi uygular. Bu, birden fazla filtreleme kuralı tanımlandığında öngörülebilir davranış sağlar. - -### Öncelik Sırası - -Sistem, dosya dahil edilmesini değerlendirirken katı bir öncelik sırası takip eder: - -1. **`.gitignore`** - Standart git hariç tutmaları her zaman saygı gösterilir ve dosya filtreleme için temel oluşturur -2. **`.contextinclude`** - INCLUDE modu kuralları dosya seçimi için en yüksek önceliğe sahiptir -3. **`.contextignore`** - EXCLUDE modu kuralları, INCLUDE modu yapılandırması olmadığında uygulanır - -Bu hiyerarşi, git tarafından ignore edilen dosyaların analize asla dahil edilmemesini sağlarken, yalnızca belirli dosyaları dahil etme (`.contextinclude` ile) veya belirli dosyaları hariç tutma (`.contextignore` ile) esnekliği sağlar. - -### Öncelik Mantığının Implementasyonu - -Öncelik kuralları, `GitIgnoreParser` class'ının `loadPatterns` methodunda uygulanır. Hem `.contextinclude` hem de `.contextignore` dosyaları mevcut olduğunda, sistem INCLUDE modu yapılandırmasını önceliklendirir. `hasIncludeFile` flag'i, bir `.contextinclude` dosyası tespit edildiğinde true olarak ayarlanır ve bu, `isIgnored` methodunda filtreleme davranışını etkiler. - -Implementasyon, INCLUDE modu kurallarının EXCLUDE modu kurallarını tamamen geçersiz kılmasını sağlayarak dosya seçiminde herhangi bir belirsizliği önler. Bu tasarım seçimi, genişlik üzerinde hassasiyeti vurgular ve kullanıcıların gerektiğinde sıkı odaklanmış analiz kapsamları oluşturmasına olanak tanır. - -```mermaid -graph TD -A[File Path] --> B[Check .gitignore] -B --> |Matched| C[Exclude File] -B --> |Not Matched| D{hasIncludeFile?} -D --> |True| E[Check .contextinclude] -D --> |False| F[Check .contextignore] -E --> |Matched & Not Negated| G[Include File] -E --> |Not Matched or Negated| H[Exclude File] -F --> |Matched & Not Negated| H[Exclude File] -F --> |Not Matched or Negated| I[Include File] -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L181-L206) -- [context-manager.js](file://context-manager.js#L134-L149) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L134-L149) -- [context-manager.js](file://context-manager.js#L181-L206) - -## Implementasyon Detayları - -Dosya filtreleme mekanizması, pattern yükleme, ayrıştırma ve dosya hariç tutma mantığını yöneten `GitIgnoreParser` class'ı aracılığıyla uygulanır. Sistem, kod analizi sırasında sorunsuz filtreleme sağlamak için ana `TokenCalculator` class'ı ile entegre olur. - -### Pattern Yükleme ve Başlatma - -Filtreleme sistemi, uygun yapilandirma dosyalarını bulan ve yükleyen `TokenCalculator` class'ındaki `initGitIgnore` methodu aracılığıyla başlatılır. Sistem, esnek yapilandirma yerleşimine olanak tanıyarak hem araç dizininde hem de proje kökünde `.contextignore` ve `.contextinclude` dosyalarını arar. - -Yapilandirma dosyaları bulunduğunda, pattern'leri verimli eşleştirme için regular expression'lara ayrıştırılır. `parsePatternFile` methodu, yapilandirma dosyasının her satırını işler, yorumları ve boş satırları ignore eder, ardından her pattern'i `convertToRegex` methodunu kullanarak bir regex nesnesine dönüştürür. - -### Dosya Hariç Tutma Mantığı - -Core filtreleme mantığı, belirli bir dosyanın analizden hariç tutulup tutulmayacağını belirleyen `isIgnored` methodunda bulunur. INCLUDE modu için, method önce dosyanın `.contextinclude` dosyasındaki herhangi bir pattern ile eşleşip eşleşmediğini kontrol eder. Eşleşen pattern bulunamazsa (veya bir negasyon pattern'i eşleşirse), dosya hariç tutulur. EXCLUDE modu için, dosyalar `.contextignore` dosyasındaki herhangi bir pattern ile eşleşirlerse hariç tutulur. - -Sistem ayrıca, INCLUDE modu pattern'lerine göre dizinlerin geçilip geçilmemesi gerektiğini kontrol ederek dizin geçişini verimli bir şekilde yönetir ve gereksiz dosya sistemi keşfini önler. - -```mermaid -classDiagram -class GitIgnoreParser { -+patterns : Array -+calculatorPatterns : Array -+hasIncludeFile : boolean -+_lastIgnoreReason : string -+constructor(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+loadPatterns(gitignorePath, calculatorIgnorePath, calculatorIncludePath) -+parsePatternFile(filePath) -+convertToRegex(pattern) -+isIgnored(filePath, relativePath) -+testPatterns(patterns, relativePath, reason) -+testPatternsWithNegation(patterns, relativePath) -} -class TokenCalculator { -+projectRoot : string -+options : Object -+stats : Object -+gitIgnore : GitIgnoreParser -+methodAnalyzer : MethodAnalyzer -+methodFilter : MethodFilterParser -+methodStats : Object -+constructor(projectRoot, options) -+initGitIgnore() -+scanDirectory(dir) -+countIgnoredFiles(filePath) -} -TokenCalculator --> GitIgnoreParser : "uses for file filtering" -TokenCalculator --> MethodAnalyzer : "uses for method extraction" -TokenCalculator --> MethodFilterParser : "uses for method filtering" -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L124-L270) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L124-L270) - -## Yaygın Sorunlar ve Sorun Giderme - -Kullanıcılar, dosya filtreleme sistemini yapılandırırken birkaç yaygın sorunla karşılaşabilir. Bu sorunları ve çözümlerini anlamak, etkili yapilandirma sağlamaya yardımcı olur. - -### Yanlış Pattern Sözdizimi - -Sık karşılaşılan bir sorun, özellikle wildcard'lar ve negasyon ile ilgili yanlış pattern sözdizimitir. Kullanıcılar, pattern'lerin doğru glob sözdizimini kullandığından ve negasyon pattern'lerinin ünlem işareti (`!`) ile başladığından emin olmalıdır. Pattern dosyaları içindeki satır içi yorumlar da sorunlara neden olabilir, çünkü yalnızca satır yorumları (bir satırın başında başlayan) düzgün şekilde ignore edilir. - -### Beklenmeyen Dosya Dahil Edilmeleri - -Beklenmeyen dosya dahil edilmeleri genellikle öncelik kuralı yanlış anlamalarından kaynaklanır. Hem `.contextinclude` hem de `.contextignore` dosyaları mevcut olduğunda, yalnızca INCLUDE modu kuralları uygulanır. EXCLUDE modu davranışı bekleyen kullanıcılar, dosyaların `.contextignore` kurallarının aksine dahil edildiğini veya hariç tutulduğunu görünce şaşırabilir. Konsol çıktısının etkin mod için kontrol edilmesi bu sorunu teşhis etmeye yardımcı olabilir. - -### Performans Etkileri - -Geniş pattern'ler, özellikle recursive wildcard'lar (`**`), kapsamlı dosya sistemi geçişi gerektirerek performansı etkileyebilir. Kullanıcılar pattern'leri ile özel olmalı ve sistemin kod tabanının büyük bölümlerini gereksiz yere incelemesini zorlayan aşırı geniş kurallardan kaçınmalıdır. - -## En İyi Uygulamalar - -Verimli ve sürdürülebilir filtre yapılandırmaları oluşturmak için şu en iyi uygulamaları takip edin: - -### Özel Pattern'ler Kullanın - -Mümkün olduğunda geniş wildcard'lar yerine özel pattern'leri tercih edin. Tüm JavaScript dosyalarını dahil etmek için `**/*.js` kullanmak yerine, `src/**/*.js` veya `lib/**/*.js` gibi ilgili kodu içeren tam dizinleri belirtin. Bu, işleme süresini azaltır ve analizi ilgili bileşenlere odaklar. - -### Negasyonu Etkili Kullanın - -Geniş dahil etme kurallarını iyileştirmek için negasyon pattern'lerini kullanın. Örneğin, bir kaynak dizindeki tüm JavaScript dosyalarını dahil edin ancak test dosyalarını hariç tutun: -```bash -src/**/*.js -!src/**/*.test.js -!src/**/*.spec.js -``` - -### Yapilandirma Amacını Belgelendirin - -Yapilandirma dosyalarına her pattern'in amacını açıklayan yorumlar ekleyin. Bu, ekip üyelerinin filtreleme stratejisini anlamasına ve proje genelinde tutarlılığı sürdürmesine yardımcı olur. - -### Yapılandırmaları Test Edin - -Hangi dosyaların dahil edildiğini veya hariç tutulduğunu görmek için aracı verbose modda çalıştırarak yapılandırmaları doğrulayın. Bu anında geri bildirim, pattern eşleştirme ile ilgili sorunları belirlemeye yardımcı olur ve amaçlanan dosyaların işlendiğinden emin olur. - -### Dahil Etme ve Hariç Tutma Arasında Denge Kurun - -Proje ihtiyaçlarına göre INCLUDE ve EXCLUDE modları arasında seçim yapın. Core bileşenlerin odaklanmış analizi için INCLUDE modunu ve seçici hariç tutmalarla kapsamlı analiz için EXCLUDE modunu kullanın. diff --git a/docs/content-tr/Yapilandirma/Method-Filtreleme.md b/docs/content-tr/Yapilandirma/Method-Filtreleme.md deleted file mode 100644 index e8fb3cd..0000000 --- a/docs/content-tr/Yapilandirma/Method-Filtreleme.md +++ /dev/null @@ -1,236 +0,0 @@ -# Method Filtreleme - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *Son commit'te güncellendi* -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js) - *Son commit'te güncellendi* -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js) - *Son commit'te güncellendi* -- [README.md](file://README.md) - *Son commit'te güncellendi* - - -## Güncelleme Özeti -**Yapılan Değişiklikler** -- Tüm bölümler method filtreleme sisteminin gerçek uygulamasını yansıtacak şekilde güncellendi -- Kod analizine dayalı olarak tüm bölümler için doğru kaynak referansları eklendi -- Yapılandırma dosyası yükleme mekanizması, ConfigUtils aracılığıyla doğru başlatmayı gösterecek şekilde düzeltildi -- Filtreleme mantığı bölümü koddan doğru uygulama detayları ile güncellendi -- Entegrasyon bölümü TokenCalculator'un method analizi hakkında kesin detaylarla geliştirildi -- Gerçek uygulamayla eşleşmesi için eski pattern sözdizimi bilgileri düzeltildi -- Pratik örnekler mevcut README içeriğiyle uyumlu hale getirildi - -## İçindekiler -1. [Giriş](#giriş) -2. [Yapilandirma Dosyaları](#yapilandirma-dosyaları) -3. [Pattern Sözdizimi](#pattern-sözdizimi) -4. [Filtreleme Mantığı](#filtreleme-mantığı) -5. [TokenCalculator ile Entegrasyon](#tokencalculator-ile-entegrasyon) -6. [Pratik Örnekler](#pratik-örnekler) -7. [Yapilandirma Tuzakları](#yapilandirma-tuzakları) -8. [En İyi Uygulamalar](#en-iyi-uygulamalar) - -## Giriş - -context-manager aracı, LLM context oluşturmasına hangi methodların dahil edileceği üzerinde ayrıntılı kontrol sağlayan gelişmiş bir method seviyesinde filtreleme sistemi sunar. Bu sistem, hangi methodların analiz edilip nihai context çıktısına dahil edileceğini belirlemek için `MethodFilterParser` class'ı ile birlikte çalışan iki yapilandirma dosyası aracılığıyla çalışır: `.methodinclude` ve `.methodignore`. Filtreleme sistemi, geliştiricilerin LLM context'ine gürültü ekleyen utility, test ve debugging methodlarını hariç tutarken core business logic'e odaklanarak token kullanımını optimize etmelerine yardımcı olmak için tasarlanmıştır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L610) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - -## Yapilandirma Dosyaları - -Method filtreleme sistemi, proje kökünde veya araç dizininde yerleştirilebilen iki isteğe bağlı yapilandirma dosyasına dayanır: - -- **`.methodinclude`**: Mevcut olduğunda, bu dosya INCLUDE modunu etkinleştirir; burada yalnızca belirtilen pattern'lerle eşleşen methodlar analize dahil edilir -- **`.methodignore`**: `.methodinclude` olmadığında, bu dosya EXCLUDE modunu etkinleştirir; burada belirtilen pattern'lerle eşleşen methodlar analizden hariç tutulur - -Sistem net bir öncelik hiyerarşisi takip eder: `.methodinclude` mevcutsa, `.methodignore` üzerinde önceliğe sahiptir ve geliştiricilerin method seçimi üzerinde hassas kontrole sahip olmasını sağlar. Bu çift modlu yaklaşım, farklı kullanım durumları için esneklik sağlar ve geliştiricilerin ya ilgi çekici belirli methodları whitelist'e almalarına ya da LLM context'inden hariç tutulması gereken methodları blacklist'e almalarına olanak tanır. - -`MethodFilterParser`, standart konumlarda (paket kökü ve proje kökü) yapılandırma dosyalarını otomatik olarak algılayan `ConfigUtils.initMethodFilter` methodu aracılığıyla başlatılır. Bu merkezi yapılandırma yönetimi, farklı proje kurulumlarında tutarlı davranış sağlar. - -```mermaid -graph TD -A[Method Filtering System] --> B{.methodinclude exists?} -B --> |Yes| C[INCLUDE Mode] -B --> |No| D{.methodignore exists?} -D --> |Yes| E[EXCLUDE Mode] -D --> |No| F[Include All Methods] -C --> G[Only include matching methods] -E --> H[Exclude matching methods] -F --> I[Include all methods] -``` - -**Diagram kaynakları** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L28-L41) - -**Bölüm kaynakları** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L28-L41) - -## Pattern Sözdizimi - -Method filtreleme sistemi, esnek eşleştirme yetenekleri sağlayan birkaç pattern türünü destekler: - -| Pattern Türü | Sözdizimi | Açıklama | Örnek | -|--------------|--------|-------------|---------| -| Tam Eşleşme | `methodName` | Tam adla eşleşen methodları eşleştirir | `calculateTokens` yalnızca "calculateTokens" adlı methodu eşleştirir | -| Wildcard | `*pattern*` | Pattern içeren methodları eşleştirir | `*Handler`, "requestHandler", "responseHandler" eşleştirir | -| Class Methodları | `Class.*` | Belirli bir class içindeki tüm methodları eşleştirir | `TokenCalculator.*`, TokenCalculator class'ındaki tüm methodları eşleştirir | -| File Methodları | `filename.methodName` | Belirli dosyalardaki belirli methodları eşleştirir | `server.handleRequest` yalnızca server.js'deki handleRequest methodunu eşleştirir | - -Pattern eşleştirme büyük/küçük harf duyarsızdır ve herhangi bir karakter dizisini eşleştirmek için `*` wildcard karakterinin kullanımını destekler. Bu, test, debug veya utility methodlarını öngörülebilir adlandırma pattern'lerini takip eden kategorilere göre hedefleyebilen güçlü filtreleme kurallarına olanak tanır ve özellikle bu tür methodları hariç tutmak için yararlıdır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L588-L610) - -## Filtreleme Mantığı - -Core filtreleme mantığı, yapilandirma dosyalarını işleyen ve etkin moda göre method dahil edilmesini belirleyen `MethodFilterParser` class'ında uygulanır. Class iki aşamalı bir süreç takip eder: - -1. **Yapilandirma Yükleme**: Constructor, `.methodinclude` ve `.methodignore` dosyalarının varlığını kontrol eder ve pattern'lerini ayrı dizilere yükler. `.methodinclude`'un varlığı, parser'ı INCLUDE moduna ayarlar. - -2. **Pattern Eşleştirme**: Analiz sırasında karşılaşılan her method için, `shouldIncludeMethod` function'ı methodun etkin moda göre dahil edilip edilmemesi gerektiğini değerlendirir: - - INCLUDE modunda: Bir method, `.methodinclude`'daki herhangi bir pattern ile eşleşirse dahil edilir - - EXCLUDE modunda: Bir method, `.methodignore`'daki herhangi bir pattern ile eşleşmiyorsa dahil edilir - -Pattern eşleştirme, wildcard pattern'lerinden dinamik olarak oluşturulan regular expression'lar kullanılarak gerçekleştirilir; `*` karakterleri `.*` regex pattern'lerine dönüştürülür. Eşleştirme, hem çıplak method adına hem de tam nitelikli `filename.methodName` formatına karşı gerçekleştirilir ve hem genel hem de dosyaya özel filtreleme kurallarına olanak tanır. - -```mermaid -classDiagram -class MethodFilterParser { -+includePatterns : Array -+ignorePatterns : Array -+hasIncludeFile : Boolean -+constructor(methodIncludePath, methodIgnorePath) -+parseMethodFile(filePath) : Array -+shouldIncludeMethod(methodName, fileName) : Boolean -} -class TokenCalculator { -+methodFilter : MethodFilterParser -+analyzeFileMethods(content, filePath) : Array -} -TokenCalculator --> MethodFilterParser : "uses" -``` - -**Diagram kaynakları** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/analyzers/token-calculator.js](file://lib/analyzers/token-calculator.js#L82-L107) - -**Bölüm kaynakları** -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) - -## TokenCalculator ile Entegrasyon - -Method filtreleme sistemi, genel analiz sürecini yöneten `TokenCalculator` class'ı ile sıkı bir şekilde entegre edilmiştir. `--method-level` flag'i ile method seviyesinde analiz etkinleştirildiğinde, `TokenCalculator` constructor sırasında `initMethodFilter()` çağrısı yaparak bir `MethodFilterParser` instance'ı başlatır. - -Filtreleme, `analyzeFileMethods` method yürütme sırasında gerçekleşir; burada çıkarılan her method, analiz sonuçlarına dahil edilmeden önce `shouldIncludeMethod` kontrolünden geçirilir. Bu entegrasyon, yalnızca ilgili methodların token sayısına katkıda bulunmasını ve nihai LLM context çıktısında görünmesini sağlar, kritik business logic'i korurken genel token ayak izini önemli ölçüde azaltır. - -Sistem ayrıca method filtreleme hakkında detaylı istatistikler tutar, bulunan toplam methodlar ile dahil edilenler arasındaki farkı izler; bu, geliştiricilerin filtreleme kurallarının etkinliğini anlamalarına ve daha iyi context kalitesi için optimize etmelerine yardımcı olur. - -```mermaid -sequenceDiagram -participant TC as TokenCalculator -participant MF as MethodFilterParser -participant MA as MethodAnalyzer -TC->>TC : run() -TC->>TC : scanDirectory() -TC->>TC : analyzeFile(filePath) -TC->>MA : extractMethods(content, filePath) -MA-->>TC : methods[] -loop For each method -TC->>MF : shouldIncludeMethod(name, fileName) -MF-->>TC : Boolean -alt Include method -TC->>MA : extractMethodContent() -MA-->>TC : methodContent -TC->>TC : calculateTokens() -TC->>TC : update methodStats -end -end -TC->>TC : generateLLMContext() -``` - -**Diagram kaynakları** -- [context-manager.js](file://context-manager.js#L231-L800) -- [context-manager.js](file://context-manager.js#L358-L383) - -**Bölüm kaynakları** -- [context-manager.js](file://context-manager.js#L231-L800) -- [context-manager.js](file://context-manager.js#L358-L383) - -## Pratik Örnekler - -README, method filtrelemenin farklı senaryolar için nasıl kullanılacağını gösteren birkaç pratik örnek sağlar: - -**Core Business Logic'i Dahil Etme:** -```bash -# .methodinclude -calculateTokens -generateLLMContext -analyzeFile -handleRequest -validateInput -processData -*Handler -*Validator -*Manager -TokenCalculator.* -``` - -Bu yapilandirma, belirli business methodlarını ve genellikle önemli business bileşenlerini gösteren "Handler", "Validator" ve "Manager" gibi yaygın son eklerle biten tüm methodları dahil ederek core uygulama mantığına odaklanır. - -**Utility Methodlarını Hariç Tutma:** -```bash -# .methodignore -console -*test* -*debug* -*helper* -print* -main -server.printStatus -utils.debugLog -``` - -Bu yapilandirma, anlamlı business logic katkısı sağlamayan yaygın utility, test ve debugging methodlarını hariç tutarak LLM context'inden gürültüyü kaldırır. `server.printStatus` gibi dosyaya özel hariç tutmalar, bireysel methodlar üzerinde hassas kontrol sağlar. - -Bu örnekler, geliştiricilerin kod tabanlarının en önemli kısımlarını vurgularken token kullanımını en aza indiren odaklanmış context'ler oluşturarak LLM etkileşimlerini daha verimli ve etkili hale getirme yollarını gösterir. - -**Bölüm kaynakları** -- [README.md](file://README.md#L577-L587) - -## Yapilandirma Tuzakları - -Method filtrelemeyi yapılandırırken, geliştiriciler birkaç yaygın tuzağın farkında olmalıdır: - -**Pattern Önceliği**: Sistem, `.methodinclude`'un her zaman `.methodignore` üzerinde önceliğe sahip olduğu katı bir öncelik takip eder. Bu, her iki dosya da mevcutsa, yalnızca include kurallarının uygulanacağı anlamına gelir; bu da geliştiriciler her iki kural setinin de birleştirileceğini varsayıyorsa beklenmeyen sonuçlara yol açabilir. - -**Büyük/Küçük Harf Duyarlılığı**: Pattern eşleştirme büyük/küçük harf duyarsız olsa da, geliştiriciler pattern'lerinin yaygın adlandırma varyasyonlarını hesaba kattığından emin olmalıdır. Örneğin, `*test*` kullanımı "testMethod", "TestMethod" ve "isTesting" gibi methodları eşleştirir. - -**Dosya Seviyesi Filtreleme ile Etkileşim**: Method filtreleme, dosya seviyesi filtrelemeyi geçmiş dosyalar üzerinde çalışır. Bir dosya `.contextignore` veya `.contextinclude` kuralları tarafından hariç tutulmuşsa, methodları method seviyesi kurallardan bağımsız olarak analiz edilmez. Bu hiyerarşik filtreleme, method kurallarının yalnızca analiz kapsamına zaten dahil edilmiş dosyalara uygulandığı anlamına gelir. - -**Aşırı Geniş Pattern'ler**: `*` veya `*.*` gibi pattern'leri kullanmak istenmeyen eşleşmelere yol açabilir. Geliştiriciler, amaçlanan filtreleme hedefleriyle uyumlu olmayan methodları dahil etmekten kaçınmak için pattern'leri ile özel olmalıdır. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L576) - -## En İyi Uygulamalar - -LLM context oluşturma için method filtrelemeyi optimize etmek amacıyla şu en iyi uygulamaları göz önünde bulundurun: - -**Business Logic'e Odaklanın**: Core business kurallarını, veri işlemeyi ve kritik uygulama iş akışlarını uygulayan methodları dahil etmeye öncelik verin. Bu methodlar tipik olarak geliştirme görevlerinde yardımcı olan LLM'ler için en değerli context'i sağlar. - -**Gürültü Methodlarını Hariç Tutun**: Anlamlı business context katkısı sağlamadan token yükü ekleyen utility, test, logging ve debugging methodlarını sistematik olarak hariç tutun. `*test*`, `*debug*` ve `console` gibi yaygın pattern'ler hariç tutma için iyi adaylardır. - -**Kritik Yollar için Include Modu Kullanın**: Belirli özellikler üzerinde çalışırken veya derin analiz yaparken, yalnızca en ilgili methodların bir whitelist'ini oluşturmak için `.methodinclude` kullanın. Bu, sinyal-gürültü oranını maksimize eden son derece odaklanmış bir context oluşturur. - -**Adlandırma Konvansiyonlarından Yararlanın**: Kod tabanınızdaki tutarlı adlandırma pattern'lerinden yararlanın. Ekibiniz business logic class'ları için "Service", "Manager" veya "Handler" gibi son ekler kullanıyorsa, bu class'lardaki tüm methodları dahil etmek için `*Service.*` gibi pattern'ler kullanın. - -**Token Azaltmasını İzleyin**: Filtreleme kurallarınızın token sayısını ne kadar etkili bir şekilde azalttığını anlamak için analiz çıktısındaki method istatistiklerini düzenli olarak kontrol edin. "Bulunan toplam methodlar" ile "Dahil edilen methodlar" arasındaki fark, filtreleme verimliliği hakkında içgörü sağlar. - -**Yineleyin ve İyileştirin**: Geniş filtreleme kuralları ile başlayın ve LLM yanıtlarının kalitesine göre kademeli olarak iyileştirin. LLM önemli context'i kaçırıyorsa, ek method kategorilerini dahil etmek için kurallarınızı ayarlayın. - -Bu uygulamaları takip ederek, geliştiriciler kapsamlılık ile verimliliği dengeleyen optimize edilmiş LLM context'leri oluşturabilir; AI asistanlarının token sınırlamaları içinde çalışırken en ilgili koda erişime sahip olmasını sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L610) diff --git a/docs/content-tr/Yapilandirma/Yapilandirma.md b/docs/content-tr/Yapilandirma/Yapilandirma.md deleted file mode 100644 index 16ea939..0000000 --- a/docs/content-tr/Yapilandirma/Yapilandirma.md +++ /dev/null @@ -1,179 +0,0 @@ -# Yapilandirma - - -**Bu Dokümanda Referans Verilen Dosyalar** -- [README.md](file://README.md) - *Method filtreleme örnekleri ile güncellendi* -- [context-manager.js](file://context-manager.js) - *Method seviyesi analiz desteği ile ana orkestratör* -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js) - *6f5fea3204f18ec9d0802a00b400af1bb823e411 commit'inde eklendi* -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js) - *Method filtre başlatmasını desteklemek için değiştirildi* - - -## Güncelleme Özeti -**Yapılan Değişiklikler** -- Method Filtreleme Sistemi bölümü yeni dosyalardan uygulama detayları ile güncellendi -- Pattern Syntax Rehberi, gerçek kod uygulamasına dayanarak güncellendi -- Yapılandırma Örnekleri, doğru method filtreleme senaryoları ile geliştirildi -- Method filtreleme mantığı hakkında eski bilgiler düzeltildi -- Gerçek analiz edilen kod dosyalarını yansıtan yeni bölüm kaynakları eklendi - -## İçindekiler -1. [Dosya Filtreleme Sistemi](#dosya-filtreleme-sistemi) -2. [Method Filtreleme Sistemi](#method-filtreleme-sistemi) -3. [Pattern Syntax Rehberi](#pattern-syntax-rehberi) -4. [Yapilandirma Örnekleri](#yapilandirma-örnekleri) -5. [Yaygın Yapilandirma Sorunları](#yaygın-yapilandirma-sorunları) -6. [En İyi Uygulamalar](#en-iyi-uygulamalar) - -## Dosya Filtreleme Sistemi - -context-manager aracı, token analizine hangi dosyaların dahil edileceği üzerinde hassas kontrol sağlayan çift modlu bir dosya filtreleme sistemi uygular. Bu sistem iki tamamlayıcı yapilandirma dosyası üzerinden çalışır: EXCLUDE modu için `.contextignore` ve INCLUDE modu için `.contextinclude`. - -Filtreleme sistemi, `.contextinclude`'un `.contextignore` üzerinde önceliğe sahip olduğu katı bir öncelik hiyerarşisini takip eder. Her iki dosya da mevcut olduğunda, araç INCLUDE modunda çalışır ve `.contextignore` dosyasını tamamen göz ardı eder. Bu öncelik, kullanıcıların hassas dosya seçimi ile odaklanmış analiz setleri oluşturabilmesini sağlarken, hariç tutma tabanlı filtrelemeye geri dönebilme yeteneğini korur. - -EXCLUDE modunda (yalnızca `.contextignore` mevcut olduğunda), araç `.contextignore` dosyasındaki pattern'lerle eşleşenler dışındaki tüm dosyaları dahil eder. Bu, geleneksel gitignore tarzı hariç tutma mantığını takip eder ve `.contextinclude` dosyası mevcut olmadığında varsayılan moddur. `.contextignore` dosyası, dokümantasyon dosyalarını (`.md`, `.txt`), yapilandirma dosyalarını (`.json`, `.yml`), altyapı ve dağıtım dosyalarını, test dizinlerini, build artifact'lerini ve `utility-mcp/src/workflows/**` ve `utility-mcp/src/testing/**` gibi belirli kod yollarını hariç tutacak şekilde önceden yapılandırılmıştır. - -INCLUDE modunda (`.contextinclude` mevcut olduğunda), araç yalnızca `.contextinclude` dosyasındaki pattern'lerle eşleşen dosyaları dahil eder, `.contextignore`'daki herhangi bir kuraldan bağımsız olarak. Bu mod, belirli dosya seçimi için daha hassas kontrol sağlar ve odaklanmış analiz setleri oluşturmak için idealdir. Varsayılan `.contextinclude` yapılandırması, `utility-mcp/src/**/*.js`'den core JavaScript dosyalarını dahil ederken, workflows ve testing utilities gibi belirli alt dizinleri hariç tutmak için negasyon pattern'leri kullanır. - -Tam yapilandirma dosyası öncelik sırası şöyledir: 1) `.gitignore` (her zaman saygı gösterilir), 2) `.contextinclude` (en yüksek öncelik), 3) `.contextignore` (include dosyası olmadığında fallback). Bu katmanlı yaklaşım, standart git hariç tutmalarının her zaman uygulanmasını sağlarken, esnek, projeye özel filtreleme seçenekleri sunar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L121-L150) -- [README.md](file://README.md#L294-L356) -- [context-manager.js](file://context-manager.js#L128-L151) - -## Method Filtreleme Sistemi - -context-manager aracı, `.methodinclude` ve `.methodignore` yapilandirma dosyaları aracılığıyla gelişmiş method seviyesinde filtreleme yetenekleri sağlar. Bu dosyalar, hangi methodların analiz edileceği ve çıktıya dahil edileceği üzerinde ayrıntılı kontrol sağlamak için `--method-level` komut satırı seçeneği ile birlikte çalışır. - -Method filtreleme, dosya filtrelemeye benzer bir prensiple çalışır, ancak kod yapısına özgü ek pattern eşleştirme yetenekleri ile. Method seviyesinde analiz etkinleştirildiğinde, araç JavaScript dosyalarını ayrıştırarak function declaration'ları, method assignment'ları ve arrow function'ları eşleştiren regular expression pattern'leri kullanarak methodları tanımlar. Tanımlanan methodlar daha sonra method yapilandirma dosyalarında tanımlanan kurallara göre filtrelenir. - -`.methodinclude` dosyası, analize hangi methodların dahil edilmesi gerektiğini belirtir. Bu dosya mevcut olduğunda, araç methodlar için INCLUDE modunda çalışır, yani yalnızca belirtilen pattern'lerle eşleşen methodlar dahil edilir. `.methodignore` dosyası, EXCLUDE modunda (`.methodinclude` dosyası olmadığında) çalışırken analizden hangi methodların hariç tutulması gerektiğini belirtir. - -Method filtreleme sistemi birkaç pattern türünü destekler: tam method isimleri (örn. `calculateTokens`), `*` kullanan wildcard pattern'ler (örn. "Handler" ile biten tüm methodları eşleştirmek için `*Handler`), `Class.*` sözdizimini kullanan class'a özgü methodlar (örn. TokenCalculator class'ındaki tüm methodları dahil etmek için `TokenCalculator.*`), ve `file.method` sözdizimini kullanan dosyaya özgü methodlar (örn. belirli bir dosyadaki belirli bir methodu hedeflemek için `server.handleRequest`). - -Filtreleme mantığı, yapilandirma dosyalarını yükleyen, pattern'leri regular expression'lara ayrıştıran ve her methodu bu pattern'lere karşı değerlendiren `MethodFilterParser` class'ında uygulanır. INCLUDE modu için, bir method `.methodinclude` dosyasındaki herhangi bir pattern ile eşleşirse dahil edilir. EXCLUDE modu için, bir method yalnızca `.methodignore` dosyasındaki herhangi bir pattern ile eşleşmiyorsa dahil edilir. Sistem ayrıca, daha geniş dahil etme kurallarından belirli methodları hariç tutmak için `!` ile öneklenmiş negasyon pattern'lerini destekler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L610) -- [context-manager.js](file://context-manager.js#L69-L96) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) -- [lib/utils/config-utils.js](file://lib/utils/config-utils.js#L29-L50) - -## Pattern Syntax Rehberi - -context-manager aracı, hem dosya hem de method filtreleme için kapsamlı bir pattern sözdizimi destekler ve esnek ve hassas yapilandirma sağlar. Pattern sistemi, kullanıcıların gelişmiş filtreleme kuralları oluşturmasına olanak tanıyan wildcard'lar, negasyon ve özel hedefleme mekanizmalarını içerir. - -Dosya pattern'leri için, araç şu sözdizimi öğelerini destekler: dizinler arası recursive eşleştirme için `**`, tek seviye wildcard eşleştirme için `*` ve negasyon için `!`. `**` wildcard'ı, sıfır veya daha fazla dizini eşleştirir ve `**/*.md` gibi pattern'lerin herhangi bir dizindeki markdown dosyalarını eşleştirmesine olanak tanır. `*` wildcard'ı, tek bir dizin seviyesindeki herhangi bir karakter dizisini eşleştirir, örneğin mevcut dizindeki tüm JavaScript dosyalarını eşleştirmek için `*.js`. Dizin pattern'leri, dizinleri özellikle hedeflemek için sondaki slash ile bitmelidir (örn. `docs/`). - -Method pattern'leri, koda özgü filtreleme için ek sözdizimini destekler. Standart wildcard'lar ve negasyona ek olarak, method pattern'leri belirli bir class içindeki tüm methodları içeren `Class.*` sözdizimini kullanarak class seviyesinde filtrelemeyi destekler. Dosyaya özgü method hedefleme, `file.method` sözdizimi ile elde edilir ve belirli dosyalardaki bireysel methodlar üzerinde hassas kontrol sağlar. Pattern eşleştirme varsayılan olarak büyük/küçük harf duyarsızdır ve yapilandirma dosyalarına `#` karakteri ile başlayan satırlarda yorumlar dahil edilebilir. - -Pattern değerlendirme belirli kurallara uyar: pattern'ler sırayla işlenir ve özellikle negasyon kullanılırken sonraki pattern'ler önceki pattern'leri geçersiz kılabilir. Daha geniş bir dahil etme pattern'inden sonra bir negasyon pattern'i (`!` ile öneklenmiş) göründüğünde, aksi takdirde dahil edilecek dosyaları veya methodları hariç tutar. Örneğin, `src/**/*.js` pattern dizisi ve ardından `!src/**/*.test.js`, src dizinindeki `.test.js` uzantılı olanlar hariç tüm JavaScript dosyalarını dahil eder. - -Pattern satırları içinde satır içi yorumların desteklenmediğini unutmamak önemlidir; yorumlar ayrı satırlarda olmalıdır. Pattern sözdizimi dikkatle doğrulanmalıdır, çünkü yanlış pattern'ler beklenmedik dosya dahil edilmelerine veya hariç tutulmalara yol açabilir. Araç, hangi modun etkin olduğunu gösteren ve pattern eşleştirme sorunlarını teşhis etmeye yardımcı olabilecek verbose çıktı sağlar. - -**Bölüm kaynakları** -- [README.md](file://README.md#L544-L610) -- [README.md](file://README.md#L418) -- [context-manager.js](file://context-manager.js#L153-L173) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L25-L35) - -## Yapilandirma Örnekleri - -context-manager aracı, core uygulama mantığına nasıl odaklanılacağını veya test dosyalarının etkili bir şekilde nasıl hariç tutulacağını gösteren pratik yapilandirma örnekleri sağlar. Bu örnekler, farklı kullanım durumları için hem EXCLUDE hem de INCLUDE modu yapılandırmalarını gösterir. - -EXCLUDE modu için, kullanıcılar analiz kapsamını genişletmek veya kısıtlamak için `.contextignore` dosyasını değiştirebilir. Normalde hariç tutulan dokümantasyon dosyalarını dahil etmek için, kullanıcılar `.contextignore` dosyasından `**/*.md` satırını yorumlayabilir veya kaldırabilir. Belirli büyük dosyaları veya dizinleri hariç tutmak için, `your-large-file.js` veya `specific-directory/**` gibi ek pattern'ler eklenebilir. Varsayılan `.contextignore` yapılandırması, dokümantasyon, yapilandirma dosyaları, altyapı kodu, workflow'lar ve testing utilities'i hariç tutarak core uygulama mantığına odaklanır. - -INCLUDE modu için, kullanıcılar tam olarak hangi dosyaların analiz edilmesi gerektiğini belirtmek için bir `.contextinclude` dosyası oluşturur. Yaygın bir pattern, bir kaynak dizinindeki tüm JavaScript dosyalarını dahil ederken negasyon kullanarak belirli alt dizinleri hariç tutmaktır. Örneğin: -``` -# src'deki tüm JS dosyalarını dahil et -src/**/*.js -# Legacy kodu hariç tut -!src/legacy/** -# Test dosyalarını hariç tut -!src/**/*.test.js -``` -Bu yapilandirma, legacy alt dizinindeki veya `.test.js` uzantılı olanlar hariç src dizinindeki tüm JavaScript dosyalarını dahil eder. Başka bir örnek, belirli giriş noktalarını ve kaynak dosyalarını dahil ederek core business logic'e odaklanır: -``` -# Ana giriş noktasını dahil et -utility-mcp/index.js -# workflows ve testing hariç tüm src JavaScript dosyalarını dahil et -utility-mcp/src/**/*.js -!utility-mcp/src/workflows/** -!utility-mcp/src/testing/** -``` - -Method seviyesinde filtreleme için, `.methodinclude` dosyası core business logic methodlarına odaklanacak şekilde yapılandırılabilir. Örnekler: -``` -# Core business logic methodları -calculateTokens -generateLLMContext -analyzeFile -handleRequest -validateInput -processData - -# Method kategorileri için pattern eşleştirme -*Handler # 'Handler' ile biten tüm methodlar -*Validator # 'Validator' ile biten tüm methodlar -*Manager # 'Manager' ile biten tüm methodlar -TokenCalculator.* # TokenCalculator class'ındaki tüm methodlar -``` - -Tersine, `.methodignore` dosyası utility ve debug methodlarını hariç tutabilir: -``` -# Utility ve debug methodlarını hariç tut -console -*test* -*debug* -*helper* -print* -main - -# Dosyaya özgü hariç tutmalar -server.printStatus -utils.debugLog -``` - -**Bölüm kaynakları** -- [README.md](file://README.md#L294-L356) -- [README.md](file://README.md#L544-L610) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L37-L45) - -## Yaygın Yapilandirma Sorunları - -context-manager aracı kullanıcıları, pattern sözdizimi, dosya dahil etme/hariç tutma davranışı ve farklı filtre dosyaları arasındaki etkileşimle ilgili birkaç yaygın yapilandirma sorunuyla karşılaşabilir. Bu sorunları ve çözümlerini anlamak etkili yapilandirma için gereklidir. - -Sık karşılaşılan bir sorun, özellikle wildcard kullanımı ile ilgili pattern sözdizimi hatalarıdır. Kullanıcılar bazen `*` (tek seviye wildcard) ile `**` (recursive wildcard) arasında karışıklık yaşar ve beklenmeyen sonuçlara yol açar. Örneğin, `docs/*.md` kullanımı yalnızca docs dizinindeki markdown dosyalarını eşleştirirken, `docs/**/*.md` docs ve tüm alt dizinlerindeki markdown dosyalarını eşleştirir. Başka bir yaygın sözdizimi sorunu, negasyon pattern'lerinin yerleşimidir; negasyon pattern'leri etkili olabilmeleri için değiştirdikleri pattern'lerden sonra gelmelidir. - -Beklenmeyen dosya dahil edilmeleri veya hariç tutmaları genellikle yapilandirma dosyaları arasındaki öncelik hiyerarşisinden kaynaklanır. `.contextinclude` `.contextignore` üzerinde önceliğe sahip olduğundan, kullanıcılar `.contextignore`'dan pattern'leri kaldırmanın analiz sonuçlarını değiştirmediğinde şaşırabilirler. Bu gibi durumlarda, `.contextinclude` dosyası muhtemelen aktiftir ve filtreleme davranışını kontrol ediyor demektir. Kullanıcılar `.contextinclude`'un varlığını kontrol etmeli ve ya onu değiştirmeli ya da EXCLUDE moduna dönmek için kaldırmalıdır. - -Farklı filtre dosyaları arasındaki etkileşim de karışıklığa neden olabilir. Araç, kendi yapilandirma dosyalarına ek olarak `.gitignore` kurallarına saygı gösterir, yani `.gitignore` tarafından hariç tutulan dosyalar calculator kurallarından bağımsız olarak analiz edilmez. Bu katmanlı hariç tutma, belirli dosyaların analizden neden eksik olduğunu anlamayı zorlaştırabilir. Verbose mod kullanımı, hangi modun etkin olduğunu göstererek ve filtreleme sürecine içgörü sağlayarak bu sorunları teşhis etmeye yardımcı olabilir. - -Diğer yaygın sorunlar arasında dizin pattern'lerini uygun sözdizimi olmadan kullanma (pattern'ler `docs/` yerine `docs/**` kullanmalıdır), pattern dosyalarında satır içi yorumlar bulundurma (yorumlar `#` ile başlayan ayrı satırlarda olmalıdır) ve method pattern'lerinde dosya uzantılarını hesaba katmama sayılabilir. Kullanıcılar ayrıca escape edilmesi gereken özel regex karakterleri içeren pattern'lerle karşılaşabilirler, ancak araç pattern dönüşümünde çoğu özel karakteri otomatik olarak işler. - -**Bölüm kaynakları** -- [README.md](file://README.md#L418) -- [README.md](file://README.md#L378-L408) -- [context-manager.js](file://context-manager.js#L175-L211) - -## En İyi Uygulamalar - -Farklı kullanım durumları için etkili filtre yapılandırmaları oluşturmak amacıyla, kullanıcılar context-manager aracının filtreleme sisteminin tüm yeteneklerinden yararlanan birkaç en iyi uygulamayı takip etmelidir. - -Genel geliştirme iş akışları için, maksimum hassasiyet için `.contextinclude` ile INCLUDE modunu kullanın. Geniş dahil etme pattern'leri ile başlayın ve belirli dosyaları veya dizinleri hariç tutmak için negasyon kullanın. Örneğin, kaynak dizinindeki tüm JavaScript dosyalarını `src/**/*.js` ile dahil edin ve ardından test dosyalarını `!src/**/*.test.js` ve legacy kodu `!src/legacy/**` ile hariç tutun. Bu yaklaşım, neyin hariç tutulduğu üzerinde kontrolü korurken kapsamlı kapsam sağlar. - -Core uygulama mantığına odaklanırken, özellikle giriş noktalarını ve core modülleri hedefleyen bir `.contextinclude` dosyası oluşturun. Ana uygulama dosyalarını açıkça dahil edin ve ilgili bileşenleri yakalamak için pattern eşleştirme kullanın. Method seviyesinde analiz için, temel işlevselliğin kapsamlı kapsanmasını sağlamak amacıyla kritik business logic için tam method isimleri ile method kategorileri için pattern eşleştirme (örn. `*Handler`, `*Validator`) birleştirin. - -Test ve debugging senaryoları için, belirli bileşenleri izole etmek için method seviyesinde filtreleme kullanın. Debug edilen methodlara odaklanan bir `.methodinclude` dosyası oluşturun, ilgili işlevselliği yakalamak için hem tam isimler hem de pattern eşleştirme kullanarak. Tersine, analizi kirletebilecek utility methodlarından, logging'den ve debugging function'larından gürültüyü hariç tutmak için `.methodignore` kullanın. - -Her zaman verbose mod kullanarak yapılandırmaları doğrulayın, bu hangi filtreleme modunun etkin olduğunu gösterir ve dahil edilen ve hariç tutulan dosyalar hakkında ayrıntılı bilgi sağlar. Bu şeffaflık, yapilandirma sorunlarını belirlemeye yardımcı olur ve analiz kapsamının beklentilerle eşleşmesini sağlar. Sorun giderme sırasında, sorunları izole etmek için yapılandırmaları geçici olarak basitleştirin, temel pattern'lerle başlayın ve kademeli olarak karmaşıklık ekleyin. - -Yapilandirma dosyalarını her pattern'in amacını açıklayan net yorumlarla düzenleyin. İlgili pattern'leri birlikte gruplandırın ve dahil etme ve hariç tutmaların ardındaki mantığı belgelemek için yorumlar kullanın. Bu dokümantasyon, yapılandırmaları zaman içinde sürdürmeye yardımcı olur ve diğer ekip üyeleri için anlaşılmasını kolaylaştırır. - -Son olarak, farklı filtreleme yaklaşımlarının performans etkilerini göz önünde bulundurun. INCLUDE modu hassas kontrol sağlarken, kod tabanı geliştikçe dikkatli bakım gerektirir. EXCLUDE modu, istikrarlı proje yapıları için daha sürdürülebilir olabilir ancak yeni dizinler eklendikçe istenmeyen dosyaları dahil etme riski taşır. Projenin analiz ihtiyaçlarını karşılamaya devam ettiklerinden emin olmak için filtre yapılandırmalarını düzenli olarak gözden geçirin ve güncelleyin. - -**Bölüm kaynakları** -- [README.md](file://README.md#L30-L103) -- [README.md](file://README.md#L253-L293) -- [context-manager.js](file://context-manager.js#L408-L447) -- [lib/parsers/method-filter-parser.js](file://lib/parsers/method-filter-parser.js#L7-L47) diff --git a/docs/PLUGIN_REFACTOR.md b/docs/internal/PLUGIN_REFACTOR.md similarity index 100% rename from docs/PLUGIN_REFACTOR.md rename to docs/internal/PLUGIN_REFACTOR.md diff --git a/docs/RAG_DESIGN.md b/docs/internal/RAG_DESIGN.md similarity index 100% rename from docs/RAG_DESIGN.md rename to docs/internal/RAG_DESIGN.md diff --git a/docs/UNBLOCKED_ANALYSIS.md b/docs/internal/UNBLOCKED_ANALYSIS.md similarity index 100% rename from docs/UNBLOCKED_ANALYSIS.md rename to docs/internal/UNBLOCKED_ANALYSIS.md