diff --git a/.claude/commands/audit.md b/.claude/commands/audit.md new file mode 100644 index 00000000..ecb8ffbb --- /dev/null +++ b/.claude/commands/audit.md @@ -0,0 +1,100 @@ + +# /audit Custom Command Documentation + +## Overview + +The `/audit` command is a custom tool designed for use in Claude Code (based on Anthropic's Claude AI coding assistant). It enables developers to perform automated audits on selected code snippets or entire files, focusing on three key areas: + +- **Security Issues**: Identification of potential vulnerabilities, unsafe practices, and security risks. +- **Optimizations**: Suggestions for improving code efficiency, performance, and resource usage. +- **Incomplete Logic**: Detection of missing edge cases, unfinished implementations, or logical gaps. + +This command leverages the `mcp_code-audit_audit_code` tool to conduct thorough analyses and generates reports that can be logged directly into the project's knowledge base (kb/) for tracking and resolution. + +## Purpose + +The primary goal of `/audit` is to enhance code quality by providing actionable insights during development. It helps maintain high standards in the Script language project by: +- Ensuring secure coding practices in async operations, closures, and FFI interactions. +- Optimizing runtime performance, especially in areas like async transformations and garbage collection. +- Verifying complete and robust logic in parsers, semantic analyzers, and code generators. + +By integrating with the knowledge base, it facilitates team collaboration on issue resolution and maintains a historical record of audits. + +## Usage + +1. **Invocation**: + - In the Cursor editor (or compatible IDE with Claude integration), select the code you want to audit. + - Type `/audit` in the chat interface to invoke the command. + - Optionally, specify parameters like audit type (e.g., "security", "performance", "all"). + +2. **Parameters**: + - **code**: The selected code snippet (automatically provided). + - **language**: Automatically detected, but can be specified (e.g., "rust" for Script's backend). + - **auditType**: Optional; defaults to "all". Options: "security", "performance", "quality", "completeness", etc. + - **includeFixSuggestions**: Boolean; defaults to true for solution proposals. + +3. **Process**: + - Claude will call the `mcp_code-audit_audit_code` tool with the provided code and parameters. + - The tool performs a comprehensive audit using AI models. + - Results are analyzed, and if issues are found, they are formatted and logged to the knowledge base. + +4. **Output**: + - A summary of findings in the chat. + - If issues are detected, a new Markdown file is created in `kb/active/` using the `mcp_kb_update` tool. + - Notification of the new KB entry for tracking. + +## Integration with Tools + +- **Audit Tool**: Uses `mcp_code-audit_audit_code` for the core auditing logic. This tool supports various audit types and provides detailed reports with fix suggestions. +- **Knowledge Base Integration**: Issues are stored in `kb/active/[ISSUE_NAME].md` with a structured format for easy reference. +- **Error Handling**: If the audit tool fails or access is denied, fallback to manual review prompts. + +## Example Workflow + +1. Select code in `src/runtime/async_ffi.rs`. +2. Invoke `/audit`. +3. Claude runs the audit and finds a security issue. +4. A new file `kb/active/ASYNC_FFI_SECURITY_ISSUE.md` is created with details. + +## Issue Format in Knowledge Base + +Each issue file in `kb/active/` follows this structure: + +``` +# [Issue Title] + +## File Path +[path/to/file.rs] + +## Issue Description +[Detailed description of the issue, including type (security/optimization/incomplete logic)] + +## Severity +[Low/Medium/High/Critical] + +## Solutions +- [Solution 1] +- [Solution 2] +- ... + +## Additional Notes +[Any extra context or references] +``` + +## Best Practices + +- Run `/audit` frequently during development, especially after major changes. +- Use specific audit types for focused reviews (e.g., "security" for async code). +- Review and verify AI-generated suggestions before implementation. +- Update the KB entry to "completed/" once resolved. + +## Limitations + +- Dependent on the accuracy of the underlying AI audit models. +- May not catch all issues; combine with manual code reviews. +- Requires proper configuration of MCP tools and access permissions. + +For more details on Claude Code, refer to: https://docs.anthropic.com/en/docs/claude-code/overview + +This documentation ensures the `/audit` command is used effectively to maintain high-quality code in the Script project. + diff --git a/.claude/commands/clean.md b/.claude/commands/clean.md new file mode 100644 index 00000000..cb95468e --- /dev/null +++ b/.claude/commands/clean.md @@ -0,0 +1,712 @@ +# /clean Command Documentation + +## Overview + +The `/clean` command provides comprehensive project maintenance and cleanup functionality for the Script programming language project. It safely removes temporary files, organizes project structure, updates dependencies, and performs general housekeeping tasks to maintain a clean and efficient development environment. + +## Purpose + +This command enhances development efficiency and project health by: +- Removing build artifacts, caches, and temporary files +- Organizing and archiving knowledge base entries +- Cleaning up backup files and obsolete code +- Updating and auditing project dependencies +- Optimizing project structure and reducing disk usage +- Maintaining consistent file organization across the project + +## Usage + +### Basic Syntax +```bash +/clean # Interactive cleanup with recommendations +/clean # Clean specific category of files +/clean --preview # Show what would be cleaned without doing it +/clean --aggressive # More thorough cleanup (use with caution) +``` + +### Cleanup Categories +```bash +/clean build # Build artifacts and compilation outputs +/clean cache # Various caches (cargo, node, etc.) +/clean temp # Temporary files and swap files +/clean backup # Backup files and version control artifacts +/clean deps # Dependency cleanup and updates +/clean kb # Knowledge base organization and archival +/clean logs # Log files and debug outputs +/clean assets # Unused assets and resources +``` + +### Cleanup Scope +```bash +/clean --target # Clean specific directory or file +/clean --recursive # Clean recursively through subdirectories +/clean --project-wide # Clean entire project (default) +/clean --safe-only # Only perform safe, non-destructive cleanup +/clean --force # Skip confirmations for safe operations +``` + +### Advanced Options +```bash +/clean --dry-run # Show cleanup plan without executing +/clean --report # Generate cleanup report for knowledge base +/clean --schedule # Set up automated cleanup schedules +/clean --analyze # Analyze disk usage and cleanup opportunities +``` + +## Cleanup Categories + +### 1. Build Artifacts Cleanup +**Command**: `/clean build` + +#### Build System Cleanup +```bash +/clean build --preview +``` + +**Cleanup Targets**: +``` +๐Ÿ”ง Build Artifacts Analysis +=========================== +Scan Complete: 2.3 seconds + +Build Artifacts Found: +โ”œโ”€โ”€ Rust build outputs +โ”‚ โ”œโ”€โ”€ target/ directory: 1.2GB +โ”‚ โ”‚ โ”œโ”€โ”€ debug/ builds: 523MB +โ”‚ โ”‚ โ”œโ”€โ”€ release/ builds: 445MB +โ”‚ โ”‚ โ”œโ”€โ”€ incremental/ cache: 234MB +โ”‚ โ”‚ โ””โ”€โ”€ deps/ artifacts: 98MB +โ”‚ โ””โ”€โ”€ Cargo.lock artifacts: 234KB +โ”œโ”€โ”€ LLVM compilation cache +โ”‚ โ”œโ”€โ”€ .llvm-cache/: 89MB +โ”‚ โ””โ”€โ”€ Temporary IR files: 12MB +โ”œโ”€โ”€ WebAssembly outputs +โ”‚ โ”œโ”€โ”€ pkg/ directory: 34MB +โ”‚ โ””โ”€โ”€ wasm build artifacts: 23MB +โ””โ”€โ”€ IDE artifacts + โ”œโ”€โ”€ .vscode/ temporary: 5MB + โ”œโ”€โ”€ Language server cache: 15MB + โ””โ”€โ”€ IntelliJ artifacts: 8MB + +Total Space: 1.47GB + +Safe to Remove: +โœ… Debug builds (523MB) - Easily rebuilt +โœ… Incremental cache (234MB) - Will regenerate +โœ… Temporary IR files (12MB) - Compilation artifacts +โœ… IDE temporary files (28MB) - Editor-specific +โœ… Old WebAssembly builds (23MB) - Outdated + +Keep (Important): +โš  Release builds (445MB) - Time-consuming to rebuild +โš  Core dependencies cache (98MB) - Slow to download +โš  LLVM cache (89MB) - Expensive to regenerate + +Recommended Cleanup: +โ”œโ”€โ”€ Space to reclaim: 820MB (56% of total) +โ”œโ”€โ”€ Rebuild time impact: ~3 minutes +โ”œโ”€โ”€ Download time saved: ~45MB cache preserved +โ””โ”€โ”€ Risk level: Very Low + +Would you like to proceed with recommended cleanup? [Y/n]: +``` + +#### Advanced Build Cleanup +```bash +/clean build --aggressive +``` + +**Aggressive Cleanup Options**: +- Remove all build artifacts including release builds +- Clear all dependency caches (forces fresh downloads) +- Remove compiler caches and optimization data +- Clean generated documentation artifacts + +### 2. Cache Cleanup +**Command**: `/clean cache` + +#### Multi-System Cache Cleanup +```bash +/clean cache +``` + +**Cache Analysis**: +``` +๐Ÿ’พ Cache Analysis Report +======================== +Total Cache Usage: 453MB across 8 cache types + +Cache Categories: +โ”œโ”€โ”€ Cargo Registry Cache: 156MB +โ”‚ โ”œโ”€โ”€ Downloaded crates: 134MB +โ”‚ โ”œโ”€โ”€ Registry index: 22MB +โ”‚ โ””โ”€โ”€ Last cleanup: 15 days ago โš  +โ”œโ”€โ”€ Node.js Cache: 89MB +โ”‚ โ”œโ”€โ”€ npm cache: 67MB +โ”‚ โ”œโ”€โ”€ yarn cache: 22MB +โ”‚ โ””โ”€โ”€ Package-lock artifacts: <1MB +โ”œโ”€โ”€ Rust Compiler Cache: 78MB +โ”‚ โ”œโ”€โ”€ rustc incremental: 45MB +โ”‚ โ”œโ”€โ”€ procedural macro cache: 23MB +โ”‚ โ””โ”€โ”€ Target cache: 10MB +โ”œโ”€โ”€ MCP Tools Cache: 34MB +โ”‚ โ”œโ”€โ”€ Downloaded tools: 28MB +โ”‚ โ”œโ”€โ”€ Configuration cache: 4MB +โ”‚ โ””โ”€โ”€ Runtime cache: 2MB +โ”œโ”€โ”€ Language Server Cache: 28MB +โ”‚ โ”œโ”€โ”€ Index files: 18MB +โ”‚ โ”œโ”€โ”€ Symbol cache: 7MB +โ”‚ โ””โ”€โ”€ Completion cache: 3MB +โ”œโ”€โ”€ Git Object Cache: 23MB +โ”‚ โ”œโ”€โ”€ Packed objects: 18MB +โ”‚ โ”œโ”€โ”€ Loose objects: 3MB +โ”‚ โ””โ”€โ”€ Refs cache: 2MB +โ”œโ”€โ”€ Documentation Cache: 15MB +โ”‚ โ”œโ”€โ”€ Generated docs: 12MB +โ”‚ โ””โ”€โ”€ Asset cache: 3MB +โ””โ”€โ”€ Browser Cache (Dev Tools): 30MB + โ”œโ”€โ”€ Source maps: 18MB + โ”œโ”€โ”€ DevTools workspace: 8MB + โ””โ”€โ”€ Extensions data: 4MB + +Cleanup Recommendations: +โœ… Old cargo registry (>30 days): 45MB +โœ… Stale npm cache: 23MB +โœ… Outdated compiler cache: 12MB +โœ… Unused MCP tool cache: 15MB +โœ… Old documentation cache: 8MB + +Conservative Cleanup: 103MB (safe, no rebuild required) +Aggressive Cleanup: 298MB (faster, requires some rebuilding) +``` + +### 3. Temporary Files Cleanup +**Command**: `/clean temp` + +#### Temporary File Detection +```bash +/clean temp --analyze +``` + +**Temporary Files Report**: +``` +๐Ÿ—‚๏ธ Temporary Files Analysis +============================ +Scan Coverage: Entire project + system temp + +Temporary Files Found: +โ”œโ”€โ”€ System Temporary Files +โ”‚ โ”œโ”€โ”€ /tmp/script-compile-*: 23 files (45MB) +โ”‚ โ”œโ”€โ”€ /tmp/cargo-*: 8 directories (12MB) +โ”‚ โ””โ”€โ”€ /tmp/node-*: 15 files (8MB) +โ”œโ”€โ”€ Editor Temporary Files +โ”‚ โ”œโ”€โ”€ .swp files (Vim): 3 files (24KB) +โ”‚ โ”œโ”€โ”€ .tmp files (VSCode): 7 files (156KB) +โ”‚ โ”œโ”€โ”€ ~$* files (Word): 0 files +โ”‚ โ””โ”€โ”€ .DS_Store (macOS): 12 files (48KB) +โ”œโ”€โ”€ Build Temporary Files +โ”‚ โ”œโ”€โ”€ *.o object files: 45 files (67MB) +โ”‚ โ”œโ”€โ”€ *.tmp compilation temps: 23 files (34MB) +โ”‚ โ””โ”€โ”€ *.lock temporary locks: 5 files (20KB) +โ”œโ”€โ”€ Debug/Log Temporary Files +โ”‚ โ”œโ”€โ”€ debug-*.log: 18 files (15MB) +โ”‚ โ”œโ”€โ”€ trace-*.json: 5 files (23MB) +โ”‚ โ””โ”€โ”€ core dumps: 0 files โœ… +โ””โ”€โ”€ Backup/Recovery Files + โ”œโ”€โ”€ *.backup files: 34 files (89MB) + โ”œโ”€โ”€ *~ backup files: 12 files (23KB) + โ”œโ”€โ”€ .orig merge files: 8 files (45KB) + โ””โ”€โ”€ auto-save files: 15 files (234KB) + +Total Temporary Files: 234 files (317MB) + +Age Analysis: +โ”œโ”€โ”€ < 1 hour: 23 files (45MB) โš  May be in use +โ”œโ”€โ”€ 1-24 hours: 67 files (123MB) โœ… Safe to clean +โ”œโ”€โ”€ 1-7 days: 89 files (98MB) โœ… Definitely safe +โ”œโ”€โ”€ > 7 days: 55 files (51MB) โœ… Should be cleaned +โ””โ”€โ”€ > 30 days: 12 files (8MB) โœ… Overdue for cleanup + +Safe Cleanup Candidates: 223 files (280MB) +Risk Assessment: Very Low (no active files) +``` + +### 4. Backup Files Cleanup +**Command**: `/clean backup` + +#### Backup File Management +```bash +/clean backup --organize +``` + +**Backup Organization**: +``` +๐Ÿ“š Backup Files Management +========================== +Backup Strategy: Organize by age and importance + +Backup Files Inventory: +โ”œโ”€โ”€ Source Code Backups +โ”‚ โ”œโ”€โ”€ *.rs.backup: 45 files (234KB) +โ”‚ โ”œโ”€โ”€ *.backup.rs: 23 files (123KB) +โ”‚ โ”œโ”€โ”€ *.orig: 12 files (67KB) +โ”‚ โ””โ”€โ”€ Version control artifacts: 34 files (456KB) +โ”œโ”€โ”€ Configuration Backups +โ”‚ โ”œโ”€โ”€ *.toml.backup: 8 files (23KB) +โ”‚ โ”œโ”€โ”€ *.json.backup: 15 files (45KB) +โ”‚ โ”œโ”€โ”€ *.yaml.backup: 5 files (12KB) +โ”‚ โ””โ”€โ”€ Environment backups: 3 files (8KB) +โ”œโ”€โ”€ Documentation Backups +โ”‚ โ”œโ”€โ”€ *.md.backup: 67 files (345KB) +โ”‚ โ”œโ”€โ”€ Draft documents: 23 files (123KB) +โ”‚ โ””โ”€โ”€ Auto-saved versions: 45 files (234KB) +โ””โ”€โ”€ Build Script Backups + โ”œโ”€โ”€ Cargo.toml versions: 12 files (34KB) + โ”œโ”€โ”€ Build.rs backups: 5 files (23KB) + โ””โ”€โ”€ CI configuration: 8 files (45KB) + +Organization Plan: +โ”œโ”€โ”€ Archive Recent (< 7 days): Move to .archive/recent/ +โ”œโ”€โ”€ Archive Old (7-30 days): Move to .archive/monthly/ +โ”œโ”€โ”€ Remove Ancient (> 90 days): 15 files for deletion +โ”œโ”€โ”€ Keep Important: Version control and CI configs +โ””โ”€โ”€ Compress Large: Backup files > 10KB + +Actions: +โœ… Create organized backup structure +โœ… Move 156 files to appropriate archives +โœ… Remove 15 obsolete backup files (8MB) +โœ… Compress 23 large backup files (saving 67MB) +โœ… Update backup retention policy documentation + +Space Savings: 75MB organized, 8MB reclaimed +Organization Benefit: Easy to find specific backups +``` + +### 5. Dependency Cleanup +**Command**: `/clean deps` + +#### Dependency Audit and Cleanup +```bash +/clean deps --audit +``` + +**Dependency Analysis**: +``` +๐Ÿ“ฆ Dependency Cleanup Analysis +============================== +Analysis Date: 2025-07-15T16:30:00Z + +Rust Dependencies (Cargo): +โ”œโ”€โ”€ Total dependencies: 234 (direct: 23, transitive: 211) +โ”œโ”€โ”€ Outdated packages: 12 โš  +โ”œโ”€โ”€ Unused dependencies: 3 โŒ +โ”œโ”€โ”€ Security advisories: 0 โœ… +โ”œโ”€โ”€ License issues: 0 โœ… +โ””โ”€โ”€ Cache size: 156MB + +Node.js Dependencies (npm): +โ”œโ”€โ”€ Total packages: 145 (direct: 15, transitive: 130) +โ”œโ”€โ”€ Outdated packages: 8 โš  +โ”œโ”€โ”€ Vulnerabilities: 0 โœ… +โ”œโ”€โ”€ Unused packages: 2 โŒ +โ”œโ”€โ”€ Cache size: 89MB +โ””โ”€โ”€ node_modules size: 234MB + +System Dependencies: +โ”œโ”€โ”€ LLVM tools: Current โœ… +โ”œโ”€โ”€ Platform libraries: Current โœ… +โ”œโ”€โ”€ Development tools: 2 updates available โš  +โ””โ”€โ”€ Documentation tools: Current โœ… + +Cleanup Opportunities: +1. ๐Ÿ—‘๏ธ Remove unused Rust dependencies + โ”œโ”€โ”€ lazy_static (not used): Remove from Cargo.toml + โ”œโ”€โ”€ regex (redundant): Covered by other deps + โ””โ”€โ”€ old_version_crate: Replace with updated alternative + +2. ๐Ÿ—‘๏ธ Remove unused Node.js packages + โ”œโ”€โ”€ @types/unused: Leftover from old feature + โ””โ”€โ”€ old-tool: Replaced by new implementation + +3. ๐Ÿ“ฆ Update outdated dependencies + โ”œโ”€โ”€ High priority: 5 packages (security/performance) + โ”œโ”€โ”€ Medium priority: 8 packages (features/bug fixes) + โ””โ”€โ”€ Low priority: 7 packages (minor improvements) + +4. ๐Ÿงน Clean dependency caches + โ”œโ”€โ”€ Old cargo registry entries: 45MB + โ”œโ”€โ”€ Stale npm cache: 23MB + โ””โ”€โ”€ Unused target artifacts: 67MB + +Estimated Cleanup: +โ”œโ”€โ”€ Dependencies removed: 5 packages +โ”œโ”€โ”€ Disk space reclaimed: 234MB +โ”œโ”€โ”€ Build time improvement: 8-12% +โ”œโ”€โ”€ Security posture: Maintained โœ… +โ””โ”€โ”€ Functionality: No impact โœ… + +Update Plan: +Phase 1: Remove unused dependencies (low risk) +Phase 2: Update non-breaking changes (medium risk) +Phase 3: Major version updates (high risk, requires testing) +``` + +### 6. Knowledge Base Organization +**Command**: `/clean kb` + +#### Knowledge Base Maintenance +```bash +/clean kb --organize +``` + +**KB Organization Plan**: +``` +๐Ÿ“‹ Knowledge Base Organization +============================== +Current KB Status: 234 files across 12 directories + +Directory Analysis: +โ”œโ”€โ”€ kb/active/: 27 files โœ… (current issues) +โ”œโ”€โ”€ kb/completed/: 156 files โš  (many old entries) +โ”œโ”€โ”€ kb/archived/: 23 files โœ… (properly archived) +โ”œโ”€โ”€ kb/status/: 12 files โœ… (current status) +โ”œโ”€โ”€ kb/reports/: 34 files โš  (some outdated) +โ”œโ”€โ”€ kb/planning/: 15 files โš  (mix of current/old) +โ”œโ”€โ”€ kb/documentation/: 45 files โœ… (well organized) +โ”œโ”€โ”€ kb/security/: 18 files โœ… (current) +โ”œโ”€โ”€ kb/legacy/: 67 files โŒ (needs cleanup) +โ”œโ”€โ”€ kb/temp/: 8 files โŒ (should not exist) +โ”œโ”€โ”€ kb/development/: 23 files โš  (needs review) +โ””โ”€โ”€ kb/compliance/: 6 files โœ… (current) + +Organization Issues Detected: +1. โŒ Temporary files in kb/temp/ + โ”œโ”€โ”€ Should be moved to appropriate directories + โ”œโ”€โ”€ Or removed if obsolete + โ””โ”€โ”€ 8 files requiring action + +2. โš  Outdated completed items + โ”œโ”€โ”€ 67 files older than 6 months in kb/completed/ + โ”œโ”€โ”€ Should be archived or deleted + โ””โ”€โ”€ Many superseded by newer implementations + +3. โš  Mixed planning content + โ”œโ”€โ”€ kb/planning/ contains both active and completed plans + โ”œโ”€โ”€ Need to separate active from historical + โ””โ”€โ”€ 8 files need categorization + +4. โŒ Legacy folder bloat + โ”œโ”€โ”€ kb/legacy/ has grown to 67 files + โ”œโ”€โ”€ Many files are duplicates or superseded + โ”œโ”€โ”€ Needs aggressive cleanup + โ””โ”€โ”€ Estimated reduction: 70% of content + +5. โš  Report retention + โ”œโ”€โ”€ kb/reports/ has reports from 8 months ago + โ”œโ”€โ”€ Old reports should be archived + โ””โ”€โ”€ Keep only last 3 months of reports + +Organization Actions: +โ”œโ”€โ”€ Move 8 temp files to proper locations +โ”œโ”€โ”€ Archive 67 old completed items +โ”œโ”€โ”€ Clean up 47 legacy files (keeping 20 important ones) +โ”œโ”€โ”€ Archive 18 old reports +โ”œโ”€โ”€ Reorganize 8 planning files +โ”œโ”€โ”€ Create missing index files +โ”œโ”€โ”€ Update cross-references +โ””โ”€โ”€ Validate all remaining links + +Estimated Results: +โ”œโ”€โ”€ Files removed: 89 (no information loss) +โ”œโ”€โ”€ Files moved: 34 (better organization) +โ”œโ”€โ”€ Disk space saved: 23MB +โ”œโ”€โ”€ Navigation improved: Significantly better +โ””โ”€โ”€ Maintenance reduced: Easier to find content +``` + +### 7. Log Files Cleanup +**Command**: `/clean logs` + +#### Log Management +```bash +/clean logs --retention-policy +``` + +**Log Cleanup Strategy**: +``` +๐Ÿ“‹ Log Files Management +======================= +Log Retention Policy: Keep 30 days detailed, 90 days summary + +Log Categories: +โ”œโ”€โ”€ Compilation Logs +โ”‚ โ”œโ”€โ”€ cargo-build-*.log: 45 files (234MB) +โ”‚ โ”œโ”€โ”€ rustc-*.log: 23 files (89MB) +โ”‚ โ””โ”€โ”€ llvm-*.log: 12 files (45MB) +โ”œโ”€โ”€ Runtime Logs +โ”‚ โ”œโ”€โ”€ script-runtime-*.log: 67 files (345MB) +โ”‚ โ”œโ”€โ”€ async-executor-*.log: 34 files (123MB) +โ”‚ โ””โ”€โ”€ gc-debug-*.log: 23 files (67MB) +โ”œโ”€โ”€ Test Logs +โ”‚ โ”œโ”€โ”€ test-results-*.log: 89 files (456MB) +โ”‚ โ”œโ”€โ”€ benchmark-*.log: 23 files (234MB) +โ”‚ โ””โ”€โ”€ integration-*.log: 15 files (89MB) +โ”œโ”€โ”€ Development Logs +โ”‚ โ”œโ”€โ”€ debug-session-*.log: 34 files (123MB) +โ”‚ โ”œโ”€โ”€ repl-history-*.log: 56 files (234MB) +โ”‚ โ””โ”€โ”€ language-server-*.log: 23 files (89MB) +โ””โ”€โ”€ System Logs + โ”œโ”€โ”€ error-reports-*.log: 12 files (67MB) + โ”œโ”€โ”€ crash-dumps-*.log: 3 files (234MB) + โ””โ”€โ”€ performance-*.log: 45 files (345MB) + +Retention Analysis: +โ”œโ”€โ”€ Current (< 7 days): 145 files (1.2GB) โœ… Keep all +โ”œโ”€โ”€ Recent (7-30 days): 89 files (897MB) โœ… Keep detailed +โ”œโ”€โ”€ Medium (30-90 days): 67 files (456MB) โš  Keep summaries only +โ”œโ”€โ”€ Old (90+ days): 123 files (1.1GB) โŒ Archive or remove +โ””โ”€โ”€ Ancient (180+ days): 45 files (678MB) โŒ Remove + +Cleanup Plan: +1. Compress old detailed logs (30-90 days) +2. Create summary reports for medium-age logs +3. Archive important diagnostic logs (>90 days) +4. Remove routine logs (>180 days) +5. Set up automatic log rotation + +Space Savings: 1.4GB reclaimed, 456MB compressed +Performance Impact: Faster log searches, reduced I/O +``` + +## Interactive Cleanup Workflows + +### 1. Guided Cleanup Session +```bash +/clean +``` + +**Interactive Cleanup Process**: +``` +๐Ÿงน Interactive Cleanup Session +============================== +Welcome to the Script Language project cleanup wizard! + +Step 1/6: Quick Analysis +โ”œโ”€โ”€ Scanning project structure... โœ… +โ”œโ”€โ”€ Analyzing disk usage... โœ… +โ”œโ”€โ”€ Identifying cleanup opportunities... โœ… +โ””โ”€โ”€ Generating recommendations... โœ… + +Analysis Complete! Found 1.7GB of cleanup opportunities. + +๐Ÿ“Š Cleanup Summary: +โ”œโ”€โ”€ ๐Ÿ—๏ธ Build artifacts: 820MB (low risk) +โ”œโ”€โ”€ ๐Ÿ’พ Cache files: 298MB (medium risk) +โ”œโ”€โ”€ ๐Ÿ“„ Temporary files: 280MB (very low risk) +โ”œโ”€โ”€ ๐Ÿ—‚๏ธ Backup files: 75MB (low risk) +โ”œโ”€โ”€ ๐Ÿ“ฆ Dependencies: 234MB (medium risk) +โ””โ”€โ”€ ๐Ÿ“‹ Knowledge base: 23MB (low risk) + +Step 2/6: Prioritized Recommendations + +๐ŸŽฏ High Impact, Low Risk (Recommended): +โ”œโ”€โ”€ โœ… Clean temporary files (280MB, 30 seconds) +โ”œโ”€โ”€ โœ… Remove old build artifacts (345MB, 1 minute) +โ”œโ”€โ”€ โœ… Organize backup files (75MB, 2 minutes) +โ””โ”€โ”€ โœ… Clean stale caches (123MB, 30 seconds) + +Total: 823MB in ~4 minutes, virtually no risk + +Would you like to proceed with recommended cleanup? [Y/n]: Y + +Step 3/6: Execution +โ”œโ”€โ”€ Cleaning temporary files... โœ… (280MB freed) +โ”œโ”€โ”€ Removing old build artifacts... โœ… (345MB freed) +โ”œโ”€โ”€ Organizing backup files... โœ… (75MB freed) +โ””โ”€โ”€ Cleaning stale caches... โœ… (123MB freed) + +Step 4/6: Additional Opportunities + +๐Ÿค” Medium Impact Options: +โ”œโ”€โ”€ โš ๏ธ Update dependencies (may require testing) +โ”œโ”€โ”€ โš ๏ธ Aggressive cache cleanup (may slow next build) +โ”œโ”€โ”€ โš ๏ธ Archive old knowledge base entries +โ””โ”€โ”€ โš ๏ธ Remove development logs older than 30 days + +Would you like to explore these options? [y/N]: n + +Step 5/6: Cleanup Report +โ”œโ”€โ”€ ๐Ÿ“Š Space reclaimed: 823MB +โ”œโ”€โ”€ โฑ๏ธ Time taken: 3m 45s +โ”œโ”€โ”€ ๐Ÿ›ก๏ธ Risk level: Very low +โ”œโ”€โ”€ ๐ŸŽฏ Next build impact: Minimal (~3 minute rebuild) +โ””โ”€โ”€ ๐Ÿ“ Report saved: kb/reports/cleanup-2025-07-15.md + +Step 6/6: Maintenance Recommendations +โ”œโ”€โ”€ ๐Ÿ”„ Set up weekly automated cleanup +โ”œโ”€โ”€ ๐Ÿ“‹ Enable build artifact rotation +โ”œโ”€โ”€ ๐Ÿ—“๏ธ Schedule monthly dependency audits +โ””โ”€โ”€ ๐Ÿ“Š Monitor disk usage trends + +Cleanup session complete! โœจ +``` + +### 2. Cleanup Preview Mode +```bash +/clean --preview --detailed +``` + +**Detailed Preview Output**: +``` +๐Ÿ” Cleanup Preview (Detailed Mode) +=================================== +Showing exactly what would be cleaned without executing. + +Build Artifacts Cleanup: +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ DELETE: target/debug/ โ”‚ +โ”‚ โ”œโ”€โ”€ Size: 523MB โ”‚ +โ”‚ โ”œโ”€โ”€ Last modified: 2 days ago โ”‚ +โ”‚ โ”œโ”€โ”€ Rebuild time: ~3 minutes โ”‚ +โ”‚ โ””โ”€โ”€ Risk: Very low (easily rebuilt) โ”‚ +โ”‚ โ”‚ +โ”‚ DELETE: target/incremental/ โ”‚ +โ”‚ โ”œโ”€โ”€ Size: 234MB โ”‚ +โ”‚ โ”œโ”€โ”€ Contents: 1,247 cache files โ”‚ +โ”‚ โ”œโ”€โ”€ Regeneration: Automatic on next build โ”‚ +โ”‚ โ””โ”€โ”€ Risk: None (performance cache only) โ”‚ +โ”‚ โ”‚ +โ”‚ KEEP: target/release/ (445MB) โ”‚ +โ”‚ โ””โ”€โ”€ Reason: Expensive to rebuild (15+ min) โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +Temporary Files Cleanup: +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ DELETE: 67 .swp files (24KB) โ”‚ +โ”‚ โ”œโ”€โ”€ Locations: Scattered across src/ โ”‚ +โ”‚ โ”œโ”€โ”€ Age: 1-30 days old โ”‚ +โ”‚ โ””โ”€โ”€ Risk: None (editor artifacts) โ”‚ +โ”‚ โ”‚ +โ”‚ DELETE: 23 *.tmp files (156KB) โ”‚ +โ”‚ โ”œโ”€โ”€ Locations: /tmp/, target/tmp/ โ”‚ +โ”‚ โ”œโ”€โ”€ Age: 2-15 days old โ”‚ +โ”‚ โ””โ”€โ”€ Risk: None (build artifacts) โ”‚ +โ”‚ โ”‚ +โ”‚ DELETE: debug-*.log (15MB) โ”‚ +โ”‚ โ”œโ”€โ”€ Count: 18 log files โ”‚ +โ”‚ โ”œโ”€โ”€ Age: > 7 days old โ”‚ +โ”‚ โ””โ”€โ”€ Risk: Very low (debug information) โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +Knowledge Base Organization: +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ MOVE: kb/temp/* โ†’ appropriate directories โ”‚ +โ”‚ โ”œโ”€โ”€ Files: 8 temporary entries โ”‚ +โ”‚ โ”œโ”€โ”€ Action: Categorize and move โ”‚ +โ”‚ โ””โ”€โ”€ Risk: None (organization only) โ”‚ +โ”‚ โ”‚ +โ”‚ ARCHIVE: kb/completed/ (67 old files) โ”‚ +โ”‚ โ”œโ”€โ”€ Criteria: > 6 months old โ”‚ +โ”‚ โ”œโ”€โ”€ Destination: kb/archived/2024/ โ”‚ +โ”‚ โ””โ”€โ”€ Risk: None (preserved, just organized) โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + +Summary: +โ”œโ”€โ”€ Total files affected: 1,247 +โ”œโ”€โ”€ Total space reclaimed: 823MB +โ”œโ”€โ”€ Estimated execution time: ~4 minutes +โ”œโ”€โ”€ Overall risk level: Very Low +โ”œโ”€โ”€ Rebuild impact: ~3 minutes on next build +โ””โ”€โ”€ No data loss: All important files preserved + +Execute this cleanup plan? [Y/n/details]: +``` + +## Safety Features and Safeguards + +### 1. Confirmation and Preview +All potentially destructive operations require confirmation: +- **Preview Mode**: Show what would be cleaned before execution +- **Interactive Confirmation**: Ask before removing large amounts of data +- **Selective Cleaning**: Allow users to choose what to clean +- **Risk Assessment**: Clearly communicate risk levels + +### 2. Backup and Recovery +```bash +/clean --create-backup +``` + +**Backup Strategy**: +- Create snapshots before major cleanup operations +- Preserve important development state +- Enable quick recovery if cleanup causes issues +- Maintain cleanup history for audit purposes + +### 3. Rollback Capability +```bash +/clean --rollback +``` + +**Rollback Features**: +- Undo recent cleanup operations +- Restore from automatic backups +- Selective restoration of specific files +- Recovery from cleanup mistakes + +## Integration with Other Commands + +### Command Synergy +- `/clean` โ†’ `/test` (ensure cleanup doesn't break tests) +- `/clean` โ†’ `/status` (verify project health after cleanup) +- `/clean deps` โ†’ `/audit` (security audit after dependency updates) +- `/clean kb` โ†’ `/docs` (update documentation after KB organization) + +### Automated Integration +- Run cleanup before major builds +- Integrate with CI/CD for regular maintenance +- Schedule periodic cleanup tasks +- Monitor disk usage and trigger cleanup automatically + +## Maintenance Scheduling + +### Automated Cleanup Schedules +```bash +/clean --schedule daily --safe-only +/clean --schedule weekly --comprehensive +/clean --schedule monthly --aggressive +``` + +**Schedule Options**: +- **Daily**: Temporary files, small caches (very safe) +- **Weekly**: Build artifacts, larger caches (safe) +- **Monthly**: Dependencies, comprehensive cleanup (requires review) +- **On-demand**: Full cleanup with user oversight + +### Monitoring and Alerts +- Disk usage monitoring with automatic alerts +- Cleanup effectiveness reporting +- Performance impact assessment +- Recommendations for cleanup schedule optimization + +## Best Practices + +### Regular Maintenance +- Run safe cleanup operations regularly (daily/weekly) +- Review cleanup reports for optimization opportunities +- Monitor disk usage trends to anticipate cleanup needs +- Keep cleanup schedules aligned with development cycles + +### Safety Guidelines +- Always use preview mode for unfamiliar cleanup operations +- Create backups before aggressive cleanup sessions +- Test builds after dependency cleanup +- Review knowledge base organization periodically + +### Performance Optimization +- Schedule cleanup during low-activity periods +- Parallelize safe cleanup operations +- Monitor cleanup performance and optimize accordingly +- Balance cleanup frequency with rebuild costs + +This `/clean` command provides comprehensive project maintenance capabilities that keep the Script language development environment clean, organized, and efficient while maintaining safety and preserving important development artifacts. \ No newline at end of file diff --git a/.claude/commands/debug.md b/.claude/commands/debug.md new file mode 100644 index 00000000..d9c4ea52 --- /dev/null +++ b/.claude/commands/debug.md @@ -0,0 +1,593 @@ +# /debug Command Documentation + +## Overview + +The `/debug` command provides comprehensive debugging and troubleshooting assistance for Script language development. It helps developers diagnose compilation errors, runtime issues, type system problems, and performance bottlenecks through intelligent analysis and automated debugging workflows. + +## Purpose + +This command accelerates development and problem resolution by: +- Providing intelligent compilation error diagnosis and fix suggestions +- Debugging REPL issues and interactive development problems +- Investigating runtime errors and memory management issues +- Analyzing type system problems and constraint solver failures +- Detecting performance bottlenecks and optimization opportunities +- Offering guided debugging workflows for complex issues + +## Usage + +### Basic Syntax +```bash +/debug # Interactive debugging session +/debug # Debug specific error category +/debug # Debug specific file +/debug --trace # Trace execution for specific issue +``` + +### Error Category Debugging +```bash +/debug compilation # Compilation pipeline issues +/debug lexer # Lexical analysis problems +/debug parser # Parsing and syntax errors +/debug semantic # Type checking and analysis issues +/debug codegen # Code generation problems +/debug runtime # Runtime execution issues +/debug memory # Memory management debugging +/debug performance # Performance analysis and optimization +/debug repl # REPL-specific debugging +/debug mcp # MCP integration issues +``` + +### Advanced Debugging Options +```bash +/debug --interactive # Launch interactive debugging session +/debug --trace-execution # Trace program execution step-by-step +/debug --memory-analysis # Deep memory usage analysis +/debug --performance-profile # Performance profiling and hotspot detection +/debug --type-inference # Type inference debugging +/debug --constraint-solver # Constraint solver debugging +/debug --ast-dump # AST visualization and analysis +/debug --ir-dump # IR analysis and optimization debugging +``` + +### File-Specific Debugging +```bash +/debug src/parser/expression.rs # Debug specific source file +/debug tests/failing_test.rs # Debug failing test cases +/debug examples/problematic.script # Debug Script language files +``` + +## Debugging Categories + +### 1. Compilation Debugging +**Purpose**: Diagnose and resolve compilation pipeline issues +**Command**: `/debug compilation` + +#### Common Issues Handled: +- **Lexer Errors**: Invalid tokens, character encoding issues +- **Parser Errors**: Syntax errors, grammar conflicts, precedence issues +- **Semantic Errors**: Type mismatches, undefined symbols, scope resolution +- **Codegen Errors**: IR generation failures, optimization problems + +#### Example Workflow: +```bash +# User reports compilation failure +/debug compilation + +# System analyzes error and provides: +๐Ÿ” Compilation Error Analysis +============================ +Error: Type mismatch in function call +Location: src/examples/test.script:15:8 + +Detailed Analysis: +โ”œโ”€โ”€ Expected type: int +โ”œโ”€โ”€ Actual type: string +โ”œโ”€โ”€ Function: calculate(value) +โ””โ”€โ”€ Call site: calculate("hello") + +Root Cause: +Function `calculate` expects numeric input but received string literal. + +Suggested Fixes: +1. Change call to: calculate(42) +2. Overload function for string input +3. Add type conversion: calculate(int("hello")) + +Related Issues: +โ”œโ”€โ”€ Similar error in line 23 +โ””โ”€โ”€ Type system documentation: kb/docs/type-system.md + +Would you like me to: +[A] Apply suggested fix #1 +[B] Show more context around error +[C] Explain type conversion options +[D] Create comprehensive fix plan +``` + +### 2. Type System Debugging +**Purpose**: Debug complex type inference and constraint solving issues +**Command**: `/debug semantic` + +#### Advanced Type Debugging: +```bash +/debug --type-inference +``` + +**Output Example**: +``` +๐Ÿงฉ Type Inference Debug Session +=============================== +Function: complex_generic_function +Location: src/semantic/test_case.rs:45 + +Type Variable Assignments: +โ”œโ”€โ”€ T = ?0 (unresolved) +โ”œโ”€โ”€ U = int (resolved) +โ””โ”€โ”€ Return = Result + +Constraint Set: +โ”œโ”€โ”€ ?0 implements Display โœ“ +โ”œโ”€โ”€ ?0 implements Clone โœ“ +โ”œโ”€โ”€ ?0: Send + Sync โš  (unverified) +โ””โ”€โ”€ ?0 != () โœ“ + +Inference Steps: +1. T assigned fresh type variable ?0 +2. U unified with int from context +3. Display constraint added from format! usage +4. Clone constraint from .clone() call +5. Send+Sync required by async boundary + +Blocking Constraint: +โ””โ”€โ”€ Cannot verify Send+Sync for ?0 + +Suggestions: +1. Add explicit bound: +2. Remove async requirement +3. Use Arc for shared ownership + +Debug Commands: +[constraints] Show all active constraints +[unify ?0 SomeType] Test unification +[trace] Step through inference +``` + +### 3. Runtime Debugging +**Purpose**: Debug runtime execution issues and memory problems +**Command**: `/debug runtime` + +#### Runtime Issue Categories: +- **Memory Leaks**: Garbage collection failures, reference cycles +- **Panic Recovery**: Stack unwinding issues, error propagation +- **Async Runtime**: Deadlocks, task scheduling, resource contention +- **FFI Issues**: Foreign function interface safety and errors +- **Performance**: Slow execution, excessive allocations + +#### Memory Debugging Example: +```bash +/debug --memory-analysis +``` + +**Output**: +``` +๐Ÿง  Memory Analysis Report +========================= +Execution: test_complex_algorithm() +Duration: 2.4 seconds + +Memory Usage Timeline: +โ”œโ”€โ”€ 0.0s: 12MB (baseline) +โ”œโ”€โ”€ 0.5s: 45MB (+33MB) - Large allocation in vector.rs:234 +โ”œโ”€โ”€ 1.2s: 89MB (+44MB) - String concatenation loop +โ”œโ”€โ”€ 2.0s: 127MB (+38MB) - HashMap growth +โ””โ”€โ”€ 2.4s: 15MB (-112MB) - GC sweep + +Potential Issues: +โŒ Memory leak detected in closure captures +โš  Excessive string allocations (1,247 calls) +โš  HashMap resize overhead (23% of execution time) + +Memory Hotspots: +1. src/algorithms/string_ops.rs:67 (45MB allocated) +2. src/collections/dynamic_array.rs:123 (23MB allocated) +3. src/closure/capture.rs:89 (12MB never freed) + +Recommendations: +โ”œโ”€โ”€ Use string builders instead of concatenation +โ”œโ”€โ”€ Pre-size HashMap with capacity +โ””โ”€โ”€ Fix closure capture leak (add Drop impl) + +Commands: +[leak] Focus on memory leak analysis +[alloc] Show allocation patterns +[gc] Analyze garbage collection efficiency +``` + +### 4. REPL Debugging +**Purpose**: Debug interactive development environment issues +**Command**: `/debug repl` + +#### REPL-Specific Issues: +- **Session State**: Variable persistence, import resolution +- **Error Recovery**: Graceful handling of malformed input +- **Performance**: Slow evaluation, memory accumulation +- **Display Issues**: Output formatting, unicode handling + +#### REPL Debug Session: +```bash +/debug repl + +# Interactive REPL debugging +๐ŸŽฏ REPL Debug Mode +================== +Current Session State: +โ”œโ”€โ”€ Variables: 7 defined +โ”œโ”€โ”€ Imports: 3 modules loaded +โ”œโ”€โ”€ Memory: 4.2MB used +โ””โ”€โ”€ History: 23 commands + +Last Error: +โ””โ”€โ”€ Parse error: Unexpected token 'async' at position 15 + +Debug Options: +[state] Show complete session state +[parse "input"] Test parsing specific input +[eval "expression"] Test evaluation +[reset] Reset REPL session +[trace] Enable execution tracing + +Enter debug command or 'exit': +> parse "async fn test() { }" +โœ“ Parsed successfully: AsyncFunctionDecl { name: "test", ... } + +> eval "undefined_variable" +โŒ Error: Undefined variable 'undefined_variable' + Available in scope: [x, y, result, calculate, ...] + +> state +Session Variables: +โ”œโ”€โ”€ x: int = 42 +โ”œโ”€โ”€ y: string = "hello" +โ”œโ”€โ”€ result: Option = Some(15) +โ””โ”€โ”€ calculate: fn(int) -> int +``` + +### 5. Performance Debugging +**Purpose**: Identify and resolve performance bottlenecks +**Command**: `/debug performance` + +#### Performance Analysis Features: +- **Hotspot Detection**: CPU-intensive code paths +- **Memory Profiling**: Allocation patterns and lifetimes +- **Compilation Speed**: Slow compile times and optimizations +- **Runtime Efficiency**: Execution speed analysis + +#### Performance Debug Example: +```bash +/debug --performance-profile +``` + +**Output**: +``` +โšก Performance Profile Analysis +============================== +Target: compilation of large_project.script +Total Time: 8.7 seconds + +Compilation Phases: +โ”œโ”€โ”€ Lexing: 0.8s (9.2%) โœ“ Normal +โ”œโ”€โ”€ Parsing: 2.1s (24.1%) โš  Slow +โ”œโ”€โ”€ Semantic: 4.2s (48.3%) โŒ Very Slow +โ”œโ”€โ”€ Codegen: 1.1s (12.6%) โœ“ Normal +โ””โ”€โ”€ Linking: 0.5s (5.8%) โœ“ Fast + +Hotspots Detected: +1. Type inference: 3.1s (35.6% of total) + โ””โ”€โ”€ Location: src/semantic/type_inference.rs:234-567 + โ””โ”€โ”€ Issue: O(nยณ) constraint solving algorithm + +2. AST traversal: 1.8s (20.7% of total) + โ””โ”€โ”€ Location: src/semantic/visitor.rs:89-156 + โ””โ”€โ”€ Issue: Redundant tree walks + +3. Symbol resolution: 0.9s (10.3% of total) + โ””โ”€โ”€ Location: src/semantic/scope.rs:45-78 + โ””โ”€โ”€ Issue: Linear search in symbol table + +Optimization Suggestions: +โ”œโ”€โ”€ Implement incremental type inference +โ”œโ”€โ”€ Cache AST traversal results +โ”œโ”€โ”€ Use HashMap for symbol lookup +โ””โ”€โ”€ Enable parallel semantic analysis + +Estimated Improvement: 65% faster compilation +``` + +## Interactive Debugging Features + +### Step-by-Step Execution Tracing +```bash +/debug --trace-execution +``` + +**Interactive Trace Session**: +``` +๐Ÿ” Execution Trace Debug +======================== +Program: fibonacci(10) + +Step 1: Function call fibonacci(10) +โ”œโ”€โ”€ Entering function at src/examples/fib.script:5 +โ”œโ”€โ”€ Parameters: n = 10 +โ””โ”€โ”€ Local variables: none + +Step 2: Conditional check n <= 1 +โ”œโ”€โ”€ Evaluating: 10 <= 1 +โ”œโ”€โ”€ Result: false +โ””โ”€โ”€ Taking else branch + +Step 3: Recursive call fibonacci(9) +โ”œโ”€โ”€ Stack depth: 2 +โ”œโ”€โ”€ Memory usage: +24 bytes +โ””โ”€โ”€ Entering nested call... + +[Continue] [Step Into] [Step Over] [Show Stack] [Show Memory] +> Show Stack + +Call Stack: +โ”œโ”€โ”€ fibonacci(10) @ src/examples/fib.script:5 +โ””โ”€โ”€ fibonacci(9) @ src/examples/fib.script:7 (tail call) + +> Show Memory +Memory State: +โ”œโ”€โ”€ Stack: 156 bytes (2 frames) +โ”œโ”€โ”€ Heap: 0 bytes (no allocations) +โ””โ”€โ”€ Registers: n=9, return_addr=0x7fff... +``` + +### Constraint Solver Debugging +```bash +/debug --constraint-solver +``` + +**Constraint Debug Session**: +``` +๐Ÿ”— Constraint Solver Debug +=========================== +Current Problem: Generic function resolution +Function: map(list: List, f: fn(T) -> U) -> List +Call Site: map(numbers, |x| x.to_string()) + +Active Constraints: +โ”œโ”€โ”€ T = int (from numbers: List) +โ”œโ”€โ”€ U = string (from to_string() return type) +โ”œโ”€โ”€ fn(T) -> U โ‰ก fn(int) -> string โœ“ +โ””โ”€โ”€ List = List โœ“ + +Solver Steps: +1. Unify T with int from context โœ“ +2. Infer U from closure return type โœ“ +3. Check function type compatibility โœ“ +4. Construct result type List โœ“ + +Result: Successfully resolved all constraints +Final Type: List + +Debug Commands: +[step] Step through solver +[constraints] Show all constraints +[unify T U] Test unification +[backtrack] Show solver backtracking +``` + +## Error Pattern Recognition + +### Common Error Patterns +The debug command recognizes and provides specialized help for common error patterns: + +#### 1. Ownership and Borrowing Issues +```rust +// Pattern: Use after move +let x = vec![1, 2, 3]; +let y = x; // Move occurs here +println!("{:?}", x); // Error: use after move + +// Debug analysis: +๐Ÿ” Ownership Error Detected +=========================== +Issue: Use of moved value 'x' +Pattern: Classic move semantic violation + +Explanation: +โ”œโ”€โ”€ Line 1: x owns Vec +โ”œโ”€โ”€ Line 2: Ownership transferred to y +โ””โ”€โ”€ Line 3: Attempt to use moved value x + +Solutions: +1. Clone before move: let y = x.clone(); +2. Use reference: let y = &x; +3. Use x after y: swap lines 2 and 3 +4. Use y instead: println!("{:?}", y); +``` + +#### 2. Type Mismatch Patterns +```rust +// Pattern: Generic constraint failure +fn process(value: T) { + println!("{}", value); +} + +process(SomeStruct {}); // Error: SomeStruct doesn't implement Display + +// Debug analysis: +๐Ÿ” Trait Bound Error +=================== +Issue: Type doesn't satisfy constraint +Missing: Display implementation for SomeStruct + +Quick Fixes: +1. Add #[derive(Display)] to SomeStruct +2. Implement Display manually +3. Use Debug instead: and {:?} +4. Convert to string: value.to_string() +``` + +## Integration with Knowledge Base + +### Debug Session Logging +All debugging sessions are automatically logged to the knowledge base: + +```markdown +# Debug Session Report +**Date**: 2025-07-15T14:32:00Z +**Issue**: Type inference failure in generic function +**Resolution**: Added explicit type bounds +**Files Modified**: +- src/semantic/type_inference.rs +- tests/type_system/generic_bounds.rs + +## Problem Analysis +The type inference system failed to resolve constraints for a complex generic function with multiple trait bounds. + +## Solution Applied +Added explicit where clauses to disambiguate type relationships. + +## Prevention Strategy +- Add more comprehensive constraint solver tests +- Improve error messages for constraint failures +- Document common generic programming patterns +``` + +### Issue Tracking Integration +- Failed debug sessions create issues in `kb/active/DEBUG_.md` +- Resolved issues move to `kb/completed/` +- Recurring patterns update knowledge base patterns +- Performance improvements tracked in benchmarks + +## Advanced Debugging Tools + +### AST Visualization +```bash +/debug --ast-dump +``` + +**Visual AST Output**: +``` +๐ŸŒณ Abstract Syntax Tree +======================== +Program +โ”œโ”€โ”€ FunctionDecl: fibonacci +โ”‚ โ”œโ”€โ”€ Parameters: [n: int] +โ”‚ โ”œโ”€โ”€ ReturnType: int +โ”‚ โ””โ”€โ”€ Body: Block +โ”‚ โ””โ”€โ”€ IfElse +โ”‚ โ”œโ”€โ”€ Condition: BinaryOp(<=) +โ”‚ โ”‚ โ”œโ”€โ”€ Left: Identifier(n) +โ”‚ โ”‚ โ””โ”€โ”€ Right: Literal(1) +โ”‚ โ”œโ”€โ”€ ThenBranch: Return(Literal(1)) +โ”‚ โ””โ”€โ”€ ElseBranch: Return(BinaryOp(+)) +โ”‚ โ”œโ”€โ”€ Left: Call(fibonacci) +โ”‚ โ”‚ โ””โ”€โ”€ Arg: BinaryOp(-) +โ”‚ โ”‚ โ”œโ”€โ”€ Left: Identifier(n) +โ”‚ โ”‚ โ””โ”€โ”€ Right: Literal(1) +โ”‚ โ””โ”€โ”€ Right: Call(fibonacci) +โ”‚ โ””โ”€โ”€ Arg: BinaryOp(-) +โ”‚ โ”œโ”€โ”€ Left: Identifier(n) +โ”‚ โ””โ”€โ”€ Right: Literal(2) +``` + +### IR Analysis +```bash +/debug --ir-dump +``` + +**IR Debug Output**: +``` +๐Ÿ”ง Intermediate Representation +============================== +Function: fibonacci(n: int) -> int + +Basic Blocks: +BB0: Entry +โ”œโ”€โ”€ %0 = param n: int +โ”œโ”€โ”€ %1 = const 1: int +โ”œโ”€โ”€ %2 = icmp_le %0, %1 +โ””โ”€โ”€ br %2, BB1, BB2 + +BB1: Base Case +โ”œโ”€โ”€ %3 = const 1: int +โ””โ”€โ”€ ret %3 + +BB2: Recursive Case +โ”œโ”€โ”€ %4 = const 1: int +โ”œโ”€โ”€ %5 = isub %0, %4 +โ”œโ”€โ”€ %6 = call fibonacci(%5) +โ”œโ”€โ”€ %7 = const 2: int +โ”œโ”€โ”€ %8 = isub %0, %7 +โ”œโ”€โ”€ %9 = call fibonacci(%8) +โ”œโ”€โ”€ %10 = iadd %6, %9 +โ””โ”€โ”€ ret %10 + +Optimization Opportunities: +โš  Tail recursion not optimized +โš  Memoization possible for fibonacci +โœ“ No memory leaks detected +โœ“ No undefined behavior +``` + +## Command Integration + +### Synergy with Other Commands +- `/debug` + `/test`: Debug failing tests with detailed analysis +- `/debug` + `/audit`: Debug security issues found in audits +- `/debug` + `/implement`: Debug issues during feature implementation +- `/debug` + `/status`: Debug build and compilation issues + +### Workflow Examples +```bash +# Complete debugging workflow: +/test semantic # Run semantic tests +# Test failure detected +/debug semantic # Debug the semantic issues +# Issue identified and fixed +/test semantic # Re-run tests to verify fix +/audit src/semantic/fixed_code.rs # Security audit the fix +``` + +## Best Practices + +### Effective Debugging +- Start with high-level error categories, drill down to specifics +- Use interactive mode for complex issues +- Save debug sessions to knowledge base for future reference +- Combine multiple debugging approaches for difficult problems + +### Performance Debugging +- Profile before optimizing +- Focus on algorithmic improvements over micro-optimizations +- Test performance fixes with realistic workloads +- Monitor for performance regressions + +### Security Debugging +- Always consider security implications of debug information +- Don't log sensitive data in debug sessions +- Verify fixes don't introduce new vulnerabilities +- Use security-focused test cases for validation + +## Limitations and Future Enhancements + +### Current Limitations +- Limited support for distributed debugging +- Basic integration with external debuggers +- Manual interpretation of some complex error patterns +- Platform-specific debugging features vary + +### Planned Enhancements +- Real-time collaborative debugging +- AI-powered error pattern recognition +- Integration with LLDB/GDB for runtime debugging +- Visual debugging interface for complex data structures +- Automated fix suggestion and application + +This `/debug` command provides comprehensive debugging support that enables developers to quickly identify, understand, and resolve issues throughout the Script language development process. \ No newline at end of file diff --git a/.claude/commands/docs.md b/.claude/commands/docs.md new file mode 100644 index 00000000..cd559f2c --- /dev/null +++ b/.claude/commands/docs.md @@ -0,0 +1,785 @@ +# /docs Command Documentation + +## Overview + +The `/docs` command provides comprehensive documentation management and generation for the Script programming language project. It automates documentation creation, maintains consistency across all documentation types, validates examples and references, and ensures documentation stays synchronized with code changes. + +## Purpose + +This command enhances documentation quality and developer experience by: +- Generating API documentation automatically from source code +- Creating and maintaining comprehensive language guides and tutorials +- Validating code examples and cross-references for accuracy +- Synchronizing documentation with codebase changes +- Managing documentation versioning and publishing workflows +- Ensuring consistent documentation style and formatting across the project + +## Usage + +### Basic Syntax +```bash +/docs # Interactive documentation management +/docs # Generate specific documentation type +/docs --validate # Validate all documentation +/docs --update # Update documentation from code changes +``` + +### Documentation Types +```bash +/docs api # API reference documentation +/docs language # Language specification and grammar +/docs guide # User guides and tutorials +/docs examples # Code examples and snippets +/docs reference # Quick reference materials +/docs internal # Internal/developer documentation +/docs deployment # Installation and deployment guides +/docs changelog # Release notes and changelogs +``` + +### Generation Options +```bash +/docs --generate # Generate all documentation +/docs --incremental # Update only changed sections +/docs --format # Specify output format (markdown, html, pdf) +/docs --output # Specify output directory +/docs --template