compact-agent 1.24.2 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rules.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Rules engine — per-language coding standards.
3
- * Loads rules from ~/.crowcoder/rules/ and injects into system prompt.
3
+ * Loads rules from ~/.compact-agent/rules/ and injects into system prompt.
4
4
  * Ships with built-in presets for common languages.
5
5
  */
6
6
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
@@ -10,126 +10,126 @@ import { getConfigDir } from './config.js';
10
10
  const RULES_DIR = join(getConfigDir(), 'rules');
11
11
  // ── Built-in rule presets ─────────────────────────────────
12
12
  const BUILTIN_RULES = {
13
- typescript: `# TypeScript Rules
14
- - Use strict mode; enable all strict compiler options
15
- - Prefer const over let; never use var
16
- - Use explicit return types on exported functions
17
- - Use interfaces for object shapes, types for unions/intersections
18
- - Prefer readonly arrays and properties where possible
19
- - Use nullish coalescing (??) over OR (||) for defaults
20
- - Use optional chaining (?.) for deep property access
21
- - Handle all Promise rejections — no floating promises
22
- - Use template literals over string concatenation
23
- - Use ESM imports (import/export), not CommonJS (require)
24
- - File naming: kebab-case for files, PascalCase for components/classes
25
- - Max file length: 300 lines — split if larger
13
+ typescript: `# TypeScript Rules
14
+ - Use strict mode; enable all strict compiler options
15
+ - Prefer const over let; never use var
16
+ - Use explicit return types on exported functions
17
+ - Use interfaces for object shapes, types for unions/intersections
18
+ - Prefer readonly arrays and properties where possible
19
+ - Use nullish coalescing (??) over OR (||) for defaults
20
+ - Use optional chaining (?.) for deep property access
21
+ - Handle all Promise rejections — no floating promises
22
+ - Use template literals over string concatenation
23
+ - Use ESM imports (import/export), not CommonJS (require)
24
+ - File naming: kebab-case for files, PascalCase for components/classes
25
+ - Max file length: 300 lines — split if larger
26
26
  - Prefer early returns over deeply nested conditionals`,
27
- python: `# Python Rules
28
- - Follow PEP 8 style guidelines
29
- - Use type hints on all function signatures
30
- - Use dataclasses or Pydantic for structured data
31
- - Prefer f-strings over .format() or % formatting
32
- - Use pathlib.Path instead of os.path for file operations
33
- - Use context managers (with) for resource management
34
- - Use list/dict/set comprehensions where readable
35
- - Prefer enumerate() over range(len())
36
- - Never use mutable default arguments (use None + factory)
37
- - Use logging module, not print(), for non-user-facing output
38
- - Max function length: 30 lines — extract if larger
27
+ python: `# Python Rules
28
+ - Follow PEP 8 style guidelines
29
+ - Use type hints on all function signatures
30
+ - Use dataclasses or Pydantic for structured data
31
+ - Prefer f-strings over .format() or % formatting
32
+ - Use pathlib.Path instead of os.path for file operations
33
+ - Use context managers (with) for resource management
34
+ - Use list/dict/set comprehensions where readable
35
+ - Prefer enumerate() over range(len())
36
+ - Never use mutable default arguments (use None + factory)
37
+ - Use logging module, not print(), for non-user-facing output
38
+ - Max function length: 30 lines — extract if larger
39
39
  - Write docstrings for all public functions (Google style)`,
40
- go: `# Go Rules
41
- - Follow Effective Go and Go Proverbs
42
- - Use gofmt/goimports for formatting
43
- - Handle every error — no _ for errors unless explicitly justified
44
- - Use short variable declarations (:=) inside functions
45
- - Keep interfaces small — 1-3 methods, defined where used
46
- - Use context.Context as the first parameter for long-running ops
47
- - Use table-driven tests
48
- - Prefer returning errors over panicking
49
- - Use defer for cleanup
50
- - Package naming: short, lowercase, no underscores
51
- - Avoid init() functions — prefer explicit initialization
40
+ go: `# Go Rules
41
+ - Follow Effective Go and Go Proverbs
42
+ - Use gofmt/goimports for formatting
43
+ - Handle every error — no _ for errors unless explicitly justified
44
+ - Use short variable declarations (:=) inside functions
45
+ - Keep interfaces small — 1-3 methods, defined where used
46
+ - Use context.Context as the first parameter for long-running ops
47
+ - Use table-driven tests
48
+ - Prefer returning errors over panicking
49
+ - Use defer for cleanup
50
+ - Package naming: short, lowercase, no underscores
51
+ - Avoid init() functions — prefer explicit initialization
52
52
  - Use struct embedding for composition, not inheritance`,
53
- rust: `# Rust Rules
54
- - Follow Rust API Guidelines (RFC 430)
55
- - Use clippy lints: #![warn(clippy::all)]
56
- - Prefer &str over String for function parameters
57
- - Use Result<T, E> for fallible operations, not panics
58
- - Implement Display for error types
59
- - Use iterators and combinators over manual loops where clear
60
- - Prefer owned types in struct fields, borrows in function params
61
- - Use derive macros for Debug, Clone, PartialEq where appropriate
62
- - Keep unsafe blocks minimal and well-documented
63
- - Use cargo fmt for formatting
53
+ rust: `# Rust Rules
54
+ - Follow Rust API Guidelines (RFC 430)
55
+ - Use clippy lints: #![warn(clippy::all)]
56
+ - Prefer &str over String for function parameters
57
+ - Use Result<T, E> for fallible operations, not panics
58
+ - Implement Display for error types
59
+ - Use iterators and combinators over manual loops where clear
60
+ - Prefer owned types in struct fields, borrows in function params
61
+ - Use derive macros for Debug, Clone, PartialEq where appropriate
62
+ - Keep unsafe blocks minimal and well-documented
63
+ - Use cargo fmt for formatting
64
64
  - Prefer match over if-let chains for >2 variants`,
65
- java: `# Java Rules
66
- - Follow Google Java Style Guide
67
- - Use records for value objects (Java 16+)
68
- - Use var for local variables with clear initialization
69
- - Prefer List.of(), Map.of() over mutable collections
70
- - Use Optional instead of null for potentially absent values
71
- - Use try-with-resources for all Closeable resources
72
- - Prefer streams over explicit loops for collection transforms
73
- - Use @Override annotation always
74
- - Final fields by default; minimize mutability
75
- - One class per file; class name matches filename
65
+ java: `# Java Rules
66
+ - Follow Google Java Style Guide
67
+ - Use records for value objects (Java 16+)
68
+ - Use var for local variables with clear initialization
69
+ - Prefer List.of(), Map.of() over mutable collections
70
+ - Use Optional instead of null for potentially absent values
71
+ - Use try-with-resources for all Closeable resources
72
+ - Prefer streams over explicit loops for collection transforms
73
+ - Use @Override annotation always
74
+ - Final fields by default; minimize mutability
75
+ - One class per file; class name matches filename
76
76
  - Use SLF4J for logging`,
77
- kotlin: `# Kotlin Rules
78
- - Follow Kotlin Coding Conventions
79
- - Use data classes for value objects
80
- - Prefer val over var — immutability by default
81
- - Use sealed classes for restricted hierarchies
82
- - Use when instead of if-else chains (>2 branches)
83
- - Use scope functions (let, run, apply, also) appropriately
84
- - Use coroutines for async — avoid callbacks
85
- - Prefer extension functions for utility operations
86
- - Use string templates over concatenation
77
+ kotlin: `# Kotlin Rules
78
+ - Follow Kotlin Coding Conventions
79
+ - Use data classes for value objects
80
+ - Prefer val over var — immutability by default
81
+ - Use sealed classes for restricted hierarchies
82
+ - Use when instead of if-else chains (>2 branches)
83
+ - Use scope functions (let, run, apply, also) appropriately
84
+ - Use coroutines for async — avoid callbacks
85
+ - Prefer extension functions for utility operations
86
+ - Use string templates over concatenation
87
87
  - Use named arguments for functions with >3 parameters`,
88
- cpp: `# C++ Rules
89
- - Follow C++ Core Guidelines
90
- - Use smart pointers (unique_ptr, shared_ptr) — no raw owning pointers
91
- - Use RAII for resource management
92
- - Prefer references over pointers where nullability is not needed
93
- - Use const correctly and consistently
94
- - Use auto for complex types where the type is obvious from context
95
- - Prefer range-based for loops
96
- - Use std::string_view for non-owning string parameters
97
- - Use [[nodiscard]] for functions where ignoring return is an error
98
- - Use std::optional for values that may not exist
99
- - Keep headers minimal — forward-declare where possible
88
+ cpp: `# C++ Rules
89
+ - Follow C++ Core Guidelines
90
+ - Use smart pointers (unique_ptr, shared_ptr) — no raw owning pointers
91
+ - Use RAII for resource management
92
+ - Prefer references over pointers where nullability is not needed
93
+ - Use const correctly and consistently
94
+ - Use auto for complex types where the type is obvious from context
95
+ - Prefer range-based for loops
96
+ - Use std::string_view for non-owning string parameters
97
+ - Use [[nodiscard]] for functions where ignoring return is an error
98
+ - Use std::optional for values that may not exist
99
+ - Keep headers minimal — forward-declare where possible
100
100
  - Use namespaces to avoid name collisions`,
101
- php: `# PHP Rules
102
- - Use PHP 8.1+ features: enums, fibers, readonly properties
103
- - Use strict types: declare(strict_types=1) in every file
104
- - Use type declarations for all parameters, return types, and properties
105
- - Follow PSR-12 coding style
106
- - Use constructor promotion for simple classes
107
- - Use match() over switch for value mapping
108
- - Use null coalescing (??) and nullsafe (?->) operators
109
- - Use named arguments for clarity
110
- - Prefer arrays + array functions over manual loops
101
+ php: `# PHP Rules
102
+ - Use PHP 8.1+ features: enums, fibers, readonly properties
103
+ - Use strict types: declare(strict_types=1) in every file
104
+ - Use type declarations for all parameters, return types, and properties
105
+ - Follow PSR-12 coding style
106
+ - Use constructor promotion for simple classes
107
+ - Use match() over switch for value mapping
108
+ - Use null coalescing (??) and nullsafe (?->) operators
109
+ - Use named arguments for clarity
110
+ - Prefer arrays + array functions over manual loops
111
111
  - Use Composer autoloading (PSR-4)`,
112
- sql: `# SQL Rules
113
- - Use parameterized queries to prevent injection
114
- - Avoid SELECT * — specify needed columns
115
- - Use proper indexes on WHERE, JOIN, ORDER BY columns
116
- - Avoid N+1 query patterns — use joins or eager loading
117
- - Write migrations that are reversible
118
- - Use foreign keys for referential integrity
119
- - Follow naming conventions: snake_case for tables/columns
120
- - Add CHECK constraints for business rule validation
121
- - Use transactions for multi-step operations
112
+ sql: `# SQL Rules
113
+ - Use parameterized queries to prevent injection
114
+ - Avoid SELECT * — specify needed columns
115
+ - Use proper indexes on WHERE, JOIN, ORDER BY columns
116
+ - Avoid N+1 query patterns — use joins or eager loading
117
+ - Write migrations that are reversible
118
+ - Use foreign keys for referential integrity
119
+ - Follow naming conventions: snake_case for tables/columns
120
+ - Add CHECK constraints for business rule validation
121
+ - Use transactions for multi-step operations
122
122
  - Document complex queries with comments`,
123
- csharp: `# C# Rules
124
- - Follow Microsoft C# Coding Conventions
125
- - Use PascalCase for public members, camelCase for private
126
- - Use LINQ where appropriate over manual loops
127
- - Use async/await for I/O operations
128
- - Use nullable reference types (C# 8+)
129
- - Prefer pattern matching in switch statements
130
- - Use dependency injection for testability
131
- - Follow SOLID principles
132
- - Use records for immutable data types
123
+ csharp: `# C# Rules
124
+ - Follow Microsoft C# Coding Conventions
125
+ - Use PascalCase for public members, camelCase for private
126
+ - Use LINQ where appropriate over manual loops
127
+ - Use async/await for I/O operations
128
+ - Use nullable reference types (C# 8+)
129
+ - Prefer pattern matching in switch statements
130
+ - Use dependency injection for testability
131
+ - Follow SOLID principles
132
+ - Use records for immutable data types
133
133
  - Document public APIs with XML comments`,
134
134
  };
135
135
  function ensureDir() {
@@ -330,697 +330,697 @@ export function getLanguageRules(language) {
330
330
  }
331
331
  // Return comprehensive built-in rules with additional detail
332
332
  const detailedRules = {
333
- typescript: `# TypeScript Code Standards
334
-
335
- ## Type System & Strict Mode
336
- - Enforce \`"strict": true\` in tsconfig.json for all strict compiler options
337
- - Prefer const over let; never use var for any reason
338
- - Explicitly declare return types on all exported functions and public methods
339
- - Use interfaces for object shapes and contracts; use types for unions, intersections, and aliases
340
- - Prefer readonly arrays and properties to prevent accidental mutations
341
- - Always provide explicit generic type parameters; don't rely on inference for complex types
342
- - Use discriminated unions for type-safe pattern matching
343
-
344
- ## Null & Undefined Safety
345
- - Use nullish coalescing (??) over logical OR (||) for proper falsy value handling
346
- - Use optional chaining (?.) for deep property access
347
- - Avoid non-null assertions (!) unless absolutely necessary and well-documented
348
- - Handle all Promise rejections—no floating promises
349
- - Never assume values exist; always add type guards or assertions
350
-
351
- ## Async Patterns & Promises
352
- - Mark async operations with explicit async/await or return Promise<T>
353
- - Handle all .catch() blocks; use try-catch in async functions
354
- - Ensure Promise.all() and Promise.race() have error handling
355
- - Set timeouts on long-running async operations
356
- - Avoid mixing callbacks with promises
357
-
358
- ## Imports & Module System
359
- - Use ESM (import/export); never CommonJS (require)
360
- - Import order: Node.js built-ins → npm packages → local files
361
- - Use named imports when importing specific exports
362
- - Avoid circular dependencies—refactor shared logic to a common module
363
- - Include file extensions in relative imports (.js, .ts)
364
- - Use index.ts for directory exports to control public API
365
-
366
- ## Code Organization & Naming
367
- - Max function length: 50 lines; extract if larger
368
- - Max file length: 300 lines; split into multiple files if exceeded
369
- - Use kebab-case for filenames, PascalCase for classes/components
370
- - Use camelCase for functions and variables
371
- - Use UPPER_SNAKE_CASE for constants
372
- - Place public functions before private in file order
373
-
374
- ## Code Quality & Maintainability
375
- - No console.log in production—use a logger (winston, pino, etc.)
376
- - Avoid deeply nested conditionals; use early returns for guard clauses
377
- - DRY: extract duplicated logic into reusable functions
378
- - No magic numbers—use named constants with descriptive names
379
- - Add comments explaining "why", not "what"
380
- - Keep cyclomatic complexity reasonable (<5 per function)
381
-
382
- ## Performance & Memory
383
- - Avoid N+1 database queries by batch loading or joining data
384
- - Memoize expensive computations (use memoization libraries)
385
- - Remove event listeners (removeEventListener) to prevent memory leaks
386
- - Unsubscribe from subscriptions in cleanup functions
387
- - Don't hold large objects in memory longer than necessary
388
-
389
- ## Testing
390
- - Write unit tests for all business logic and utilities
391
- - Cover happy paths and at least 3 edge cases per function
392
- - Add JSDoc comments to public functions with @param, @returns, @throws
333
+ typescript: `# TypeScript Code Standards
334
+
335
+ ## Type System & Strict Mode
336
+ - Enforce \`"strict": true\` in tsconfig.json for all strict compiler options
337
+ - Prefer const over let; never use var for any reason
338
+ - Explicitly declare return types on all exported functions and public methods
339
+ - Use interfaces for object shapes and contracts; use types for unions, intersections, and aliases
340
+ - Prefer readonly arrays and properties to prevent accidental mutations
341
+ - Always provide explicit generic type parameters; don't rely on inference for complex types
342
+ - Use discriminated unions for type-safe pattern matching
343
+
344
+ ## Null & Undefined Safety
345
+ - Use nullish coalescing (??) over logical OR (||) for proper falsy value handling
346
+ - Use optional chaining (?.) for deep property access
347
+ - Avoid non-null assertions (!) unless absolutely necessary and well-documented
348
+ - Handle all Promise rejections—no floating promises
349
+ - Never assume values exist; always add type guards or assertions
350
+
351
+ ## Async Patterns & Promises
352
+ - Mark async operations with explicit async/await or return Promise<T>
353
+ - Handle all .catch() blocks; use try-catch in async functions
354
+ - Ensure Promise.all() and Promise.race() have error handling
355
+ - Set timeouts on long-running async operations
356
+ - Avoid mixing callbacks with promises
357
+
358
+ ## Imports & Module System
359
+ - Use ESM (import/export); never CommonJS (require)
360
+ - Import order: Node.js built-ins → npm packages → local files
361
+ - Use named imports when importing specific exports
362
+ - Avoid circular dependencies—refactor shared logic to a common module
363
+ - Include file extensions in relative imports (.js, .ts)
364
+ - Use index.ts for directory exports to control public API
365
+
366
+ ## Code Organization & Naming
367
+ - Max function length: 50 lines; extract if larger
368
+ - Max file length: 300 lines; split into multiple files if exceeded
369
+ - Use kebab-case for filenames, PascalCase for classes/components
370
+ - Use camelCase for functions and variables
371
+ - Use UPPER_SNAKE_CASE for constants
372
+ - Place public functions before private in file order
373
+
374
+ ## Code Quality & Maintainability
375
+ - No console.log in production—use a logger (winston, pino, etc.)
376
+ - Avoid deeply nested conditionals; use early returns for guard clauses
377
+ - DRY: extract duplicated logic into reusable functions
378
+ - No magic numbers—use named constants with descriptive names
379
+ - Add comments explaining "why", not "what"
380
+ - Keep cyclomatic complexity reasonable (<5 per function)
381
+
382
+ ## Performance & Memory
383
+ - Avoid N+1 database queries by batch loading or joining data
384
+ - Memoize expensive computations (use memoization libraries)
385
+ - Remove event listeners (removeEventListener) to prevent memory leaks
386
+ - Unsubscribe from subscriptions in cleanup functions
387
+ - Don't hold large objects in memory longer than necessary
388
+
389
+ ## Testing
390
+ - Write unit tests for all business logic and utilities
391
+ - Cover happy paths and at least 3 edge cases per function
392
+ - Add JSDoc comments to public functions with @param, @returns, @throws
393
393
  - Document non-obvious logic with inline comments`,
394
- python: `# Python Code Standards
395
-
396
- ## Type Hints & Static Typing
397
- - Add type hints to all function parameters and return types
398
- - Use type hints on class attributes using typing module or PEP 526
399
- - Use complex type aliases (TypeAlias) for clarity
400
- - Run mypy or pyright to validate types
401
- - Use Union[X, Y] or X | Y (3.10+) for multiple types
402
- - Never use implicit Any—always be explicit
403
-
404
- ## PEP 8 Compliance
405
- - Use 4 spaces for indentation; never tabs
406
- - Keep lines ≤79 characters (100 for comments/docstrings)
407
- - Use CamelCase for classes; snake_case for functions and variables
408
- - Use UPPER_SNAKE_CASE for module-level constants
409
- - Place 2 blank lines between top-level definitions, 1 between methods
410
- - Use trailing commas in multi-line collections
411
-
412
- ## Strings & Documentation
413
- - Always use f-strings (f"...") for string formatting
414
- - Never use % formatting or .format() unless f-string unavailable
415
- - Write docstrings in Google style for all public functions/classes
416
- - Use triple double quotes (""") for docstrings
417
- - Use raw strings (r"...") for regex patterns
418
- - Avoid string concatenation in loops—collect in list, then join
419
-
420
- ## Async & Concurrency
421
- - Use async/await; don't mix with threading without careful consideration
422
- - Manage asyncio event loop explicitly; understand run_until_complete
423
- - Never block I/O in async functions (no time.sleep(); use asyncio.sleep())
424
- - Set timeouts on all async operations using asyncio.wait_for()
425
- - Use asyncio.gather() or asyncio.TaskGroup for concurrent tasks
426
- - Understand GIL implications when using threading
427
-
428
- ## Exception Handling
429
- - Never use bare except:; always catch specific exceptions
430
- - Use custom exception classes for domain errors
431
- - Use finally blocks for cleanup or context managers (with statement)
432
- - Log exceptions with context before re-raising
433
- - Don't silently swallow exceptions
434
- - Use context managers for all resource management
435
-
436
- ## File I/O & Paths
437
- - Always use pathlib.Path instead of os.path
438
- - Use context managers for file operations: with open(...) as f:
439
- - Always specify encoding explicitly (utf-8 is typical)
440
- - Never hardcode absolute paths—use config or environment variables
441
- - Check file existence before operations using if path.exists()
442
-
443
- ## Data Structures & Functions
444
- - Limit function length to ~30 lines; extract if larger
445
- - Limit function parameters to 3-4; use dataclass if more needed
446
- - Never use mutable defaults: def foo(items=[]) is wrong; use None + factory
447
- - Prefer dataclasses or Pydantic for structured data
448
- - Use enumerate() instead of range(len())
449
- - Use list/dict/set comprehensions for readability
450
- - Use generator expressions for large datasets
451
-
452
- ## Testing & Documentation
453
- - Write docstrings for all public functions using Google style
454
- - Use pytest for unit tests; organize with fixtures and markers
455
- - Cover happy paths, edge cases, and error conditions
456
- - Use mocks/patches to isolate external dependencies
457
- - Never use print() in production—use logging module
458
- - Configure logging with proper levels: DEBUG, INFO, WARNING, ERROR
459
-
460
- ## Performance & Best Practices
461
- - Avoid N+1 queries using select_related() or prefetch_related() in ORMs
462
- - Use pagination for large result sets
463
- - Cache expensive computations (consider functools.lru_cache)
464
- - Avoid algorithms with O(n²) or worse without justification
394
+ python: `# Python Code Standards
395
+
396
+ ## Type Hints & Static Typing
397
+ - Add type hints to all function parameters and return types
398
+ - Use type hints on class attributes using typing module or PEP 526
399
+ - Use complex type aliases (TypeAlias) for clarity
400
+ - Run mypy or pyright to validate types
401
+ - Use Union[X, Y] or X | Y (3.10+) for multiple types
402
+ - Never use implicit Any—always be explicit
403
+
404
+ ## PEP 8 Compliance
405
+ - Use 4 spaces for indentation; never tabs
406
+ - Keep lines ≤79 characters (100 for comments/docstrings)
407
+ - Use CamelCase for classes; snake_case for functions and variables
408
+ - Use UPPER_SNAKE_CASE for module-level constants
409
+ - Place 2 blank lines between top-level definitions, 1 between methods
410
+ - Use trailing commas in multi-line collections
411
+
412
+ ## Strings & Documentation
413
+ - Always use f-strings (f"...") for string formatting
414
+ - Never use % formatting or .format() unless f-string unavailable
415
+ - Write docstrings in Google style for all public functions/classes
416
+ - Use triple double quotes (""") for docstrings
417
+ - Use raw strings (r"...") for regex patterns
418
+ - Avoid string concatenation in loops—collect in list, then join
419
+
420
+ ## Async & Concurrency
421
+ - Use async/await; don't mix with threading without careful consideration
422
+ - Manage asyncio event loop explicitly; understand run_until_complete
423
+ - Never block I/O in async functions (no time.sleep(); use asyncio.sleep())
424
+ - Set timeouts on all async operations using asyncio.wait_for()
425
+ - Use asyncio.gather() or asyncio.TaskGroup for concurrent tasks
426
+ - Understand GIL implications when using threading
427
+
428
+ ## Exception Handling
429
+ - Never use bare except:; always catch specific exceptions
430
+ - Use custom exception classes for domain errors
431
+ - Use finally blocks for cleanup or context managers (with statement)
432
+ - Log exceptions with context before re-raising
433
+ - Don't silently swallow exceptions
434
+ - Use context managers for all resource management
435
+
436
+ ## File I/O & Paths
437
+ - Always use pathlib.Path instead of os.path
438
+ - Use context managers for file operations: with open(...) as f:
439
+ - Always specify encoding explicitly (utf-8 is typical)
440
+ - Never hardcode absolute paths—use config or environment variables
441
+ - Check file existence before operations using if path.exists()
442
+
443
+ ## Data Structures & Functions
444
+ - Limit function length to ~30 lines; extract if larger
445
+ - Limit function parameters to 3-4; use dataclass if more needed
446
+ - Never use mutable defaults: def foo(items=[]) is wrong; use None + factory
447
+ - Prefer dataclasses or Pydantic for structured data
448
+ - Use enumerate() instead of range(len())
449
+ - Use list/dict/set comprehensions for readability
450
+ - Use generator expressions for large datasets
451
+
452
+ ## Testing & Documentation
453
+ - Write docstrings for all public functions using Google style
454
+ - Use pytest for unit tests; organize with fixtures and markers
455
+ - Cover happy paths, edge cases, and error conditions
456
+ - Use mocks/patches to isolate external dependencies
457
+ - Never use print() in production—use logging module
458
+ - Configure logging with proper levels: DEBUG, INFO, WARNING, ERROR
459
+
460
+ ## Performance & Best Practices
461
+ - Avoid N+1 queries using select_related() or prefetch_related() in ORMs
462
+ - Use pagination for large result sets
463
+ - Cache expensive computations (consider functools.lru_cache)
464
+ - Avoid algorithms with O(n²) or worse without justification
465
465
  - Profile before optimizing`,
466
- go: `# Go Code Standards
467
-
468
- ## Error Handling (Go Proverbs: "Errors are values")
469
- - Always handle every error; use _ = err only with explicit justification comment
470
- - Wrap errors with context: fmt.Errorf("doing X: %w", err)
471
- - Define custom error types for domain-specific errors
472
- - Never panic in libraries; only in main or tests
473
- - Provide helpful error messages to users
474
- - Use error chains to understand error context
475
-
476
- ## Interface Design & Struct Composition
477
- - Keep interfaces small: 1-3 methods, defined where they're needed
478
- - Prefer composition over inheritance; use embedding for type reuse
479
- - Use pointer receivers when modifying receiver; value otherwise
480
- - Don't create interfaces for every type; only when needed
481
- - Use unexported (lowercase) fields by default; export only what's public
482
- - Document exported identifiers with comments starting with the name
483
-
484
- ## Context & Concurrency
485
- - Pass context.Context as the first parameter in long-running functions
486
- - Always respect context cancellation in loops
487
- - Set timeouts on contexts: ctx, cancel := context.WithTimeout(ctx, time.Minute)
488
- - Never store context in struct fields; pass as parameter
489
- - Use context.Background() only at application entry point
490
- - Never block indefinitely—always have timeout or cancellation
491
-
492
- ## Goroutines & Channel Safety
493
- - Prevent goroutine leaks by ensuring all goroutines exit
494
- - Use sync.WaitGroup or context cancellation to coordinate goroutines
495
- - Test with go run -race to detect data races
496
- - Always close channels from the sender; receivers don't close
497
- - Use select with timeout to prevent deadlocks
498
- - Protect shared memory with sync.Mutex or use channels
499
-
500
- ## Code Style & Organization
501
- - Run gofmt automatically; never commit unformatted code
502
- - Run goimports to organize imports correctly
503
- - Keep function comments at the top, starting with function name
504
- - Document packages with a package comment at the top of the file
505
- - Group related code; use blank lines to separate logical blocks
506
- - File structure: package comment → imports → constants → vars → types → interfaces → functions
507
-
508
- ## Function & File Structure
509
- - Place exported functions before unexported ones
510
- - Keep functions focused on a single task
511
- - Table-driven tests for testing multiple scenarios
512
- - Use subtests (t.Run) for test clarity and isolation
513
- - Max cyclomatic complexity ~5; refactor if exceeded
514
- - Package names: short, lowercase, no underscores
515
-
516
- ## Testing Strategy
517
- - Use table-driven tests: test different inputs with same logic
518
- - Use t.Run for subtests and clearer test organization
519
- - Mock external dependencies; unit tests shouldn't call external services
520
- - Write benchmarks for performance-critical code
521
- - Fuzz tests for parsers and validators
522
- - Test error paths, not just happy paths
523
-
524
- ## Common Go Patterns
525
- - Use defer for cleanup (files, locks, connections)
526
- - Check type assertions with v, ok := x.(Type)
527
- - Avoid init() functions; prefer explicit initialization
528
- - Use iota for enum-like constants
466
+ go: `# Go Code Standards
467
+
468
+ ## Error Handling (Go Proverbs: "Errors are values")
469
+ - Always handle every error; use _ = err only with explicit justification comment
470
+ - Wrap errors with context: fmt.Errorf("doing X: %w", err)
471
+ - Define custom error types for domain-specific errors
472
+ - Never panic in libraries; only in main or tests
473
+ - Provide helpful error messages to users
474
+ - Use error chains to understand error context
475
+
476
+ ## Interface Design & Struct Composition
477
+ - Keep interfaces small: 1-3 methods, defined where they're needed
478
+ - Prefer composition over inheritance; use embedding for type reuse
479
+ - Use pointer receivers when modifying receiver; value otherwise
480
+ - Don't create interfaces for every type; only when needed
481
+ - Use unexported (lowercase) fields by default; export only what's public
482
+ - Document exported identifiers with comments starting with the name
483
+
484
+ ## Context & Concurrency
485
+ - Pass context.Context as the first parameter in long-running functions
486
+ - Always respect context cancellation in loops
487
+ - Set timeouts on contexts: ctx, cancel := context.WithTimeout(ctx, time.Minute)
488
+ - Never store context in struct fields; pass as parameter
489
+ - Use context.Background() only at application entry point
490
+ - Never block indefinitely—always have timeout or cancellation
491
+
492
+ ## Goroutines & Channel Safety
493
+ - Prevent goroutine leaks by ensuring all goroutines exit
494
+ - Use sync.WaitGroup or context cancellation to coordinate goroutines
495
+ - Test with go run -race to detect data races
496
+ - Always close channels from the sender; receivers don't close
497
+ - Use select with timeout to prevent deadlocks
498
+ - Protect shared memory with sync.Mutex or use channels
499
+
500
+ ## Code Style & Organization
501
+ - Run gofmt automatically; never commit unformatted code
502
+ - Run goimports to organize imports correctly
503
+ - Keep function comments at the top, starting with function name
504
+ - Document packages with a package comment at the top of the file
505
+ - Group related code; use blank lines to separate logical blocks
506
+ - File structure: package comment → imports → constants → vars → types → interfaces → functions
507
+
508
+ ## Function & File Structure
509
+ - Place exported functions before unexported ones
510
+ - Keep functions focused on a single task
511
+ - Table-driven tests for testing multiple scenarios
512
+ - Use subtests (t.Run) for test clarity and isolation
513
+ - Max cyclomatic complexity ~5; refactor if exceeded
514
+ - Package names: short, lowercase, no underscores
515
+
516
+ ## Testing Strategy
517
+ - Use table-driven tests: test different inputs with same logic
518
+ - Use t.Run for subtests and clearer test organization
519
+ - Mock external dependencies; unit tests shouldn't call external services
520
+ - Write benchmarks for performance-critical code
521
+ - Fuzz tests for parsers and validators
522
+ - Test error paths, not just happy paths
523
+
524
+ ## Common Go Patterns
525
+ - Use defer for cleanup (files, locks, connections)
526
+ - Check type assertions with v, ok := x.(Type)
527
+ - Avoid init() functions; prefer explicit initialization
528
+ - Use iota for enum-like constants
529
529
  - Prefer if err != nil { return err } over else blocks`,
530
- rust: `# Rust Code Standards
531
-
532
- ## Ownership & Lifetimes
533
- - Understand and follow Rust's ownership rules strictly
534
- - Annotate lifetimes explicitly when the compiler can't infer
535
- - Use references (&T) for non-owning access; Box<T> for owned allocations
536
- - Pass &str instead of &String for function parameters
537
- - Pass &[T] instead of &Vec<T> for function parameters
538
- - Use &T for immutable access; &mut T for exclusive mutable access
539
-
540
- ## Error Handling & Results
541
- - Use Result<T, E> for all fallible operations—never panic in libraries
542
- - Implement Error + Display traits for custom error types
543
- - Use the ? operator for error propagation
544
- - Add context to errors when wrapping
545
- - Never use unwrap() or expect() in production code (tests OK)
546
- - Consider custom error types instead of generic String errors
547
-
548
- ## Smart Pointers & Memory Safety
549
- - Use Box<T> for owned heap allocations
550
- - Use Arc<T> for shared ownership; Rc<T> only in single-threaded contexts
551
- - Break circular references with Weak<T>
552
- - Understand Arc overhead and use judiciously
553
- - Never use raw pointers (*const T, *mut T) outside unsafe blocks
554
- - Never hold references across .await points without understanding
555
-
556
- ## Unsafe Code
557
- - Minimize unsafe blocks; they should be last resort
558
- - Document safety invariants above every unsafe block
559
- - Include a SAFETY comment explaining why it's safe
560
- - Verify bounds before any pointer dereference
561
- - Use high-level safe abstractions instead of unsafe when possible
562
- - Review unsafe code with extra scrutiny during code review
563
-
564
- ## Const Correctness & Generics
565
- - Use const for compile-time constant values
566
- - Use const fn for functions that can run at compile time
567
- - Use const generics for compile-time parameterization
568
- - Annotate mutable references only when mutation happens
569
- - Use &self for immutable methods; &mut self for mutating
570
- - Default to immutable bindings (let, not let mut)
571
-
572
- ## Clippy & Code Quality
573
- - Enable #![warn(clippy::all)] or stricter in lib.rs/main.rs
574
- - Address all clippy warnings; understand before dismissing
575
- - Use cargo clippy to find idiomatic Rust patterns
576
- - Apply rustfmt for consistent formatting
577
- - Keep function length reasonable; extract if complex
578
- - DRY: refactor duplicated logic into helpers
579
-
580
- ## Code Style & Documentation
581
- - Use snake_case for functions/variables, CamelCase for types/traits
582
- - Run cargo fmt before committing
583
- - Document all public functions with /// doc comments
584
- - Include examples in doc comments; they're compiled with cargo test --doc
585
- - Add SAFETY comments for all unsafe blocks explaining why it's safe
586
- - Write INVARIANT comments for complex data structures
587
-
588
- ## Testing & Verification
589
- - Write unit tests in modules with #[cfg(test)]
590
- - Write integration tests in tests/ directory
591
- - Include examples in doc comments with /// \`\`\`
592
- - Test error paths and edge cases
593
- - Use property-based testing (proptest) for combinatorial coverage
594
- - Profile before optimizing; use cargo flamegraph
595
-
596
- ## Trait & Generic Design
597
- - Keep traits cohesive; single responsibility
598
- - Use explicit generic bounds: fn foo<T: Clone + Display>(...)
599
- - Use associated types to avoid over-generalization
600
- - Follow orphan rule: implement foreign traits only on local types
601
- - Use HRTB (for<'a>) for advanced lifetime scenarios
530
+ rust: `# Rust Code Standards
531
+
532
+ ## Ownership & Lifetimes
533
+ - Understand and follow Rust's ownership rules strictly
534
+ - Annotate lifetimes explicitly when the compiler can't infer
535
+ - Use references (&T) for non-owning access; Box<T> for owned allocations
536
+ - Pass &str instead of &String for function parameters
537
+ - Pass &[T] instead of &Vec<T> for function parameters
538
+ - Use &T for immutable access; &mut T for exclusive mutable access
539
+
540
+ ## Error Handling & Results
541
+ - Use Result<T, E> for all fallible operations—never panic in libraries
542
+ - Implement Error + Display traits for custom error types
543
+ - Use the ? operator for error propagation
544
+ - Add context to errors when wrapping
545
+ - Never use unwrap() or expect() in production code (tests OK)
546
+ - Consider custom error types instead of generic String errors
547
+
548
+ ## Smart Pointers & Memory Safety
549
+ - Use Box<T> for owned heap allocations
550
+ - Use Arc<T> for shared ownership; Rc<T> only in single-threaded contexts
551
+ - Break circular references with Weak<T>
552
+ - Understand Arc overhead and use judiciously
553
+ - Never use raw pointers (*const T, *mut T) outside unsafe blocks
554
+ - Never hold references across .await points without understanding
555
+
556
+ ## Unsafe Code
557
+ - Minimize unsafe blocks; they should be last resort
558
+ - Document safety invariants above every unsafe block
559
+ - Include a SAFETY comment explaining why it's safe
560
+ - Verify bounds before any pointer dereference
561
+ - Use high-level safe abstractions instead of unsafe when possible
562
+ - Review unsafe code with extra scrutiny during code review
563
+
564
+ ## Const Correctness & Generics
565
+ - Use const for compile-time constant values
566
+ - Use const fn for functions that can run at compile time
567
+ - Use const generics for compile-time parameterization
568
+ - Annotate mutable references only when mutation happens
569
+ - Use &self for immutable methods; &mut self for mutating
570
+ - Default to immutable bindings (let, not let mut)
571
+
572
+ ## Clippy & Code Quality
573
+ - Enable #![warn(clippy::all)] or stricter in lib.rs/main.rs
574
+ - Address all clippy warnings; understand before dismissing
575
+ - Use cargo clippy to find idiomatic Rust patterns
576
+ - Apply rustfmt for consistent formatting
577
+ - Keep function length reasonable; extract if complex
578
+ - DRY: refactor duplicated logic into helpers
579
+
580
+ ## Code Style & Documentation
581
+ - Use snake_case for functions/variables, CamelCase for types/traits
582
+ - Run cargo fmt before committing
583
+ - Document all public functions with /// doc comments
584
+ - Include examples in doc comments; they're compiled with cargo test --doc
585
+ - Add SAFETY comments for all unsafe blocks explaining why it's safe
586
+ - Write INVARIANT comments for complex data structures
587
+
588
+ ## Testing & Verification
589
+ - Write unit tests in modules with #[cfg(test)]
590
+ - Write integration tests in tests/ directory
591
+ - Include examples in doc comments with /// \`\`\`
592
+ - Test error paths and edge cases
593
+ - Use property-based testing (proptest) for combinatorial coverage
594
+ - Profile before optimizing; use cargo flamegraph
595
+
596
+ ## Trait & Generic Design
597
+ - Keep traits cohesive; single responsibility
598
+ - Use explicit generic bounds: fn foo<T: Clone + Display>(...)
599
+ - Use associated types to avoid over-generalization
600
+ - Follow orphan rule: implement foreign traits only on local types
601
+ - Use HRTB (for<'a>) for advanced lifetime scenarios
602
602
  - Prefer composition over trait objects when possible`,
603
- java: `# Java Code Standards
604
-
605
- ## Null Safety & Optional
606
- - Use Optional<T> instead of returning null
607
- - Use Optional.orElse(), orElseThrow(), orElseGet()
608
- - Never call Optional.get() without isPresent() check
609
- - Use @Nullable/@NonNull annotations for clarity
610
- - Handle NullPointerException in tests
611
- - Understand Optional is not a general-purpose wrapper
612
-
613
- ## Resource Management (Try-With-Resources)
614
- - Always use try-with-resources for Closeable resources
615
- - Never use try-finally for resource cleanup
616
- - Connection/Statement always closed in try-with-resources
617
- - Stream/Reader/Writer closed in try-with-resources
618
- - Test for resource leaks with tools like NetBeans Profiler
619
-
620
- ## Collections & Streams
621
- - Prefer Stream API over explicit loops for transformations
622
- - Use List.of(), Map.of(), Set.of() for immutable collections
623
- - Never create unnecessary new ArrayList/HashMap
624
- - Terminal operations required in Stream chains
625
- - Avoid nested flatMap; limit depth for readability
626
- - Use Collectors.groupingBy, toMap, etc. appropriately
627
-
628
- ## Spring Boot & Dependency Injection
629
- - Constructor injection preferred over @Autowired on fields
630
- - Use @Autowired on constructor for single dependency
631
- - Avoid circular dependencies; refactor if found
632
- - Use @Service, @Repository, @Controller on appropriate classes
633
- - @Transactional on service methods, not on getters
634
- - Use @ConfigurationProperties for externalized configuration
635
-
636
- ## JPA & ORM Patterns
637
- - Use fetch joins to prevent N+1 query problems
638
- - Avoid lazy loading issues; use eager loading when needed
639
- - Ensure entities only modified within transactions
640
- - Set @Transactional(readOnly=true) on query methods
641
- - Careful with cascade configuration—avoid unintended deletes
642
- - Use projections for read-only queries
643
-
644
- ## Code Style & Conventions
645
- - 4-space indentation; never tabs
646
- - Max 100 characters per line
647
- - CamelCase for classes; camelCase for methods/variables
648
- - UPPER_SNAKE_CASE for constants
649
- - Always use @Override annotation
650
- - Comments explain "why", not "what"
651
-
652
- ## Type Safety & Generics
653
- - Specify generic type bounds: <T extends SomeClass>
654
- - Use wildcard types appropriately: ? extends, ? super
655
- - Minimize unchecked casts; document when necessary
656
- - Never use raw types (List instead of List<String>)
657
- - Understand type erasure implications
658
-
659
- ## Testing
660
- - Use JUnit 5 with @Test annotations
661
- - Mock external dependencies with Mockito
662
- - Test names describe what is tested
663
- - Follow Arrange-Act-Assert pattern
664
- - Document public APIs with Javadoc
665
- - Use @param, @return, @throws in Javadoc
666
-
667
- ## Object-Oriented Design
668
- - Use inheritance sparingly; prefer composition
669
- - Mark immutable classes as final
670
- - Encapsulate fields; provide getters
671
- - Follow SOLID principles
672
- - Single Responsibility per class
603
+ java: `# Java Code Standards
604
+
605
+ ## Null Safety & Optional
606
+ - Use Optional<T> instead of returning null
607
+ - Use Optional.orElse(), orElseThrow(), orElseGet()
608
+ - Never call Optional.get() without isPresent() check
609
+ - Use @Nullable/@NonNull annotations for clarity
610
+ - Handle NullPointerException in tests
611
+ - Understand Optional is not a general-purpose wrapper
612
+
613
+ ## Resource Management (Try-With-Resources)
614
+ - Always use try-with-resources for Closeable resources
615
+ - Never use try-finally for resource cleanup
616
+ - Connection/Statement always closed in try-with-resources
617
+ - Stream/Reader/Writer closed in try-with-resources
618
+ - Test for resource leaks with tools like NetBeans Profiler
619
+
620
+ ## Collections & Streams
621
+ - Prefer Stream API over explicit loops for transformations
622
+ - Use List.of(), Map.of(), Set.of() for immutable collections
623
+ - Never create unnecessary new ArrayList/HashMap
624
+ - Terminal operations required in Stream chains
625
+ - Avoid nested flatMap; limit depth for readability
626
+ - Use Collectors.groupingBy, toMap, etc. appropriately
627
+
628
+ ## Spring Boot & Dependency Injection
629
+ - Constructor injection preferred over @Autowired on fields
630
+ - Use @Autowired on constructor for single dependency
631
+ - Avoid circular dependencies; refactor if found
632
+ - Use @Service, @Repository, @Controller on appropriate classes
633
+ - @Transactional on service methods, not on getters
634
+ - Use @ConfigurationProperties for externalized configuration
635
+
636
+ ## JPA & ORM Patterns
637
+ - Use fetch joins to prevent N+1 query problems
638
+ - Avoid lazy loading issues; use eager loading when needed
639
+ - Ensure entities only modified within transactions
640
+ - Set @Transactional(readOnly=true) on query methods
641
+ - Careful with cascade configuration—avoid unintended deletes
642
+ - Use projections for read-only queries
643
+
644
+ ## Code Style & Conventions
645
+ - 4-space indentation; never tabs
646
+ - Max 100 characters per line
647
+ - CamelCase for classes; camelCase for methods/variables
648
+ - UPPER_SNAKE_CASE for constants
649
+ - Always use @Override annotation
650
+ - Comments explain "why", not "what"
651
+
652
+ ## Type Safety & Generics
653
+ - Specify generic type bounds: <T extends SomeClass>
654
+ - Use wildcard types appropriately: ? extends, ? super
655
+ - Minimize unchecked casts; document when necessary
656
+ - Never use raw types (List instead of List<String>)
657
+ - Understand type erasure implications
658
+
659
+ ## Testing
660
+ - Use JUnit 5 with @Test annotations
661
+ - Mock external dependencies with Mockito
662
+ - Test names describe what is tested
663
+ - Follow Arrange-Act-Assert pattern
664
+ - Document public APIs with Javadoc
665
+ - Use @param, @return, @throws in Javadoc
666
+
667
+ ## Object-Oriented Design
668
+ - Use inheritance sparingly; prefer composition
669
+ - Mark immutable classes as final
670
+ - Encapsulate fields; provide getters
671
+ - Follow SOLID principles
672
+ - Single Responsibility per class
673
673
  - No "god classes" with too many responsibilities`,
674
- cpp: `# C++ Code Standards
675
-
676
- ## Memory Management (RAII, Smart Pointers)
677
- - Use std::unique_ptr for single ownership
678
- - Use std::shared_ptr for shared ownership
679
- - Never use raw owning pointers (new/delete)
680
- - Use std::make_unique/make_shared
681
- - Ensure all resources have destructors
682
- - No memory leaks possible even in exception paths
683
-
684
- ## Const Correctness
685
- - Mark methods const when they don't modify state
686
- - Use const references: const T& for parameters
687
- - Propagate const correctness up the call chain
688
- - Use mutable only for truly mutable implementation details
689
- - Mark data members const by default
690
- - const in templates: template<const T>
691
-
692
- ## Pointer & Reference Safety
693
- - Use std::string_view for non-owning string parameters
694
- - Prefer references over pointers when nullability unnecessary
695
- - Use bounds checking in array operations
696
- - Check pointers before dereference
697
- - Use std::span<T> for array ranges (C++20)
698
- - Use std::optional<T> for optional values
699
-
700
- ## RAII & Destructors
701
- - Every resource has a constructor (acquire) and destructor (release)
702
- - Define move constructor and move assignment
703
- - Copy constructor and assignment operator when deep copying needed
704
- - No resource leaks in exception paths
705
- - Use scopedexits pattern for cleanup
706
- - RAII applies to locks, files, network connections, memory
707
-
708
- ## Standard Library
709
- - Use std::vector for dynamic arrays
710
- - Use std::string for text (not char arrays)
711
- - Use std::array for fixed-size arrays
712
- - Use std::map/unordered_map for key-value
713
- - Understand iterator validity before/after operations
714
- - Use range-based for loops: for(auto& x : container)
715
- - Use <algorithm> library functions
716
-
717
- ## Error Handling
718
- - Exceptions preferred to error codes in modern C++
719
- - Provide strong or basic exception safety guarantee
720
- - Use noexcept appropriately; default to not noexcept
721
- - Custom exception types for domain errors
722
- - Avoid exception specifications; use noexcept only
723
- - Test exception paths in unit tests
724
-
725
- ## Code Style & Quality
726
- - Run clang-format automatically; never commit unformatted code
727
- - Never use using namespace std (except in function scope)
728
- - Meaningful variable/function names
729
- - Single responsibility per function
730
- - Reasonable cyclomatic complexity
731
- - Named constants instead of magic numbers
732
- - Comments explain non-obvious logic
733
-
734
- ## Testing & Documentation
735
- - Unit tests for critical functions
736
- - Integration tests for module interactions
737
- - Doxygen comments for public API
738
- - Include examples for complex APIs
739
- - README explains build and usage
740
- - Use Valgrind/AddressSanitizer for testing
741
-
742
- ## Template Metaprogramming
743
- - Template complexity justified
744
- - Use SFINAE or C++20 concepts for overload resolution
745
- - Minimize template instantiation bloat
746
- - Document explicit instantiations
747
- - Use static_assert for compile-time checks
748
- - C++20 concepts preferred over enable_if
749
-
750
- ## Performance
751
- - Use move semantics to avoid copies
752
- - Minimize allocations in hot loops
753
- - Reasonable algorithm complexity
754
- - Profile before optimizing
755
- - Cache-friendly data layout
674
+ cpp: `# C++ Code Standards
675
+
676
+ ## Memory Management (RAII, Smart Pointers)
677
+ - Use std::unique_ptr for single ownership
678
+ - Use std::shared_ptr for shared ownership
679
+ - Never use raw owning pointers (new/delete)
680
+ - Use std::make_unique/make_shared
681
+ - Ensure all resources have destructors
682
+ - No memory leaks possible even in exception paths
683
+
684
+ ## Const Correctness
685
+ - Mark methods const when they don't modify state
686
+ - Use const references: const T& for parameters
687
+ - Propagate const correctness up the call chain
688
+ - Use mutable only for truly mutable implementation details
689
+ - Mark data members const by default
690
+ - const in templates: template<const T>
691
+
692
+ ## Pointer & Reference Safety
693
+ - Use std::string_view for non-owning string parameters
694
+ - Prefer references over pointers when nullability unnecessary
695
+ - Use bounds checking in array operations
696
+ - Check pointers before dereference
697
+ - Use std::span<T> for array ranges (C++20)
698
+ - Use std::optional<T> for optional values
699
+
700
+ ## RAII & Destructors
701
+ - Every resource has a constructor (acquire) and destructor (release)
702
+ - Define move constructor and move assignment
703
+ - Copy constructor and assignment operator when deep copying needed
704
+ - No resource leaks in exception paths
705
+ - Use scopedexits pattern for cleanup
706
+ - RAII applies to locks, files, network connections, memory
707
+
708
+ ## Standard Library
709
+ - Use std::vector for dynamic arrays
710
+ - Use std::string for text (not char arrays)
711
+ - Use std::array for fixed-size arrays
712
+ - Use std::map/unordered_map for key-value
713
+ - Understand iterator validity before/after operations
714
+ - Use range-based for loops: for(auto& x : container)
715
+ - Use <algorithm> library functions
716
+
717
+ ## Error Handling
718
+ - Exceptions preferred to error codes in modern C++
719
+ - Provide strong or basic exception safety guarantee
720
+ - Use noexcept appropriately; default to not noexcept
721
+ - Custom exception types for domain errors
722
+ - Avoid exception specifications; use noexcept only
723
+ - Test exception paths in unit tests
724
+
725
+ ## Code Style & Quality
726
+ - Run clang-format automatically; never commit unformatted code
727
+ - Never use using namespace std (except in function scope)
728
+ - Meaningful variable/function names
729
+ - Single responsibility per function
730
+ - Reasonable cyclomatic complexity
731
+ - Named constants instead of magic numbers
732
+ - Comments explain non-obvious logic
733
+
734
+ ## Testing & Documentation
735
+ - Unit tests for critical functions
736
+ - Integration tests for module interactions
737
+ - Doxygen comments for public API
738
+ - Include examples for complex APIs
739
+ - README explains build and usage
740
+ - Use Valgrind/AddressSanitizer for testing
741
+
742
+ ## Template Metaprogramming
743
+ - Template complexity justified
744
+ - Use SFINAE or C++20 concepts for overload resolution
745
+ - Minimize template instantiation bloat
746
+ - Document explicit instantiations
747
+ - Use static_assert for compile-time checks
748
+ - C++20 concepts preferred over enable_if
749
+
750
+ ## Performance
751
+ - Use move semantics to avoid copies
752
+ - Minimize allocations in hot loops
753
+ - Reasonable algorithm complexity
754
+ - Profile before optimizing
755
+ - Cache-friendly data layout
756
756
  - Inline hints used conservatively`,
757
- kotlin: `# Kotlin Code Standards
758
-
759
- ## Null Safety & Type System
760
- - Non-nullable types (T) preferred; nullable (T?) explicit
761
- - Safe calls (.?) and assertions (!!); assert only in tests
762
- - Elvis operator (?:) for defaults
763
- - Use val by default; var only when needed
764
- - lateinit for late initialization; lazy for computed values
765
- - Never use !!
766
-
767
- ## Data Classes & Immutability
768
- - data class for value objects with auto-generated equals, hashCode, toString
769
- - Use copy() for "modifications" (maintains immutability)
770
- - val everywhere; var sparingly
771
- - Destructuring: val (x, y) = pair
772
- - Private constructors for controlled creation
773
- - sealed class for restricted hierarchies
774
-
775
- ## Coroutines & Async
776
- - async/await instead of callbacks
777
- - Proper scope: GlobalScope avoided; use lifecycle scopes
778
- - Exception handling in coroutine builders
779
- - Cancellation respected in loops
780
- - launch vs async: launch for fire-and-forget, async for results
781
- - Job/Task properly awaited
782
-
783
- ## Control Flow & When Expressions
784
- - when instead of if-else chains (>2 branches)
785
- - when exhaustive or explicit else
786
- - Scope functions (let, run, apply, also) appropriately used
787
- - if-expressions return values when possible
788
- - Early returns to avoid nesting
789
- - Guard clauses instead of nested blocks
790
-
791
- ## Extension Functions & Higher-Order Functions
792
- - Extension functions for utility operations
793
- - Receiver clarity in extension scopes
794
- - No extensions on Any/Object
795
- - Lambdas single-expression when possible
796
- - it implicit parameter understood
797
- - Function types clear in signatures
798
-
799
- ## Collections & Sequences
800
- - listOf, mapOf, setOf for immutable collections
801
- - Sequences for lazy evaluation chains
802
- - map/filter/reduce chains clear and efficient
803
- - groupBy for grouping; associate for map creation
804
- - No unnecessary list conversions
805
- - forEach/forEachIndexed over manual loops
806
-
807
- ## Strings & Text
808
- - String templates (with ${'${}'}) instead of concatenation
809
- - Triple quotes (""" """) for multiline
810
- - Raw strings for regex/JSON
811
- - No string building in loops
812
-
813
- ## Testing & Spring Integration
814
- - JUnit 5 with @Test
815
- - Mockk or similar for mocking
816
- - Test names describe behavior
817
- - Arrange-Act-Assert pattern
818
- - KDoc for public APIs
819
- - @SpringBootTest for integration tests
820
-
821
- ## Code Style & Conventions
822
- - ktlint for consistent formatting
823
- - No redundant modifiers (public, final)
824
- - camelCase for functions; PascalCase for types
825
- - Comments explain "why" not "what"
826
- - Function length ~30 lines; file length ~300 lines
757
+ kotlin: `# Kotlin Code Standards
758
+
759
+ ## Null Safety & Type System
760
+ - Non-nullable types (T) preferred; nullable (T?) explicit
761
+ - Safe calls (.?) and assertions (!!); assert only in tests
762
+ - Elvis operator (?:) for defaults
763
+ - Use val by default; var only when needed
764
+ - lateinit for late initialization; lazy for computed values
765
+ - Never use !!
766
+
767
+ ## Data Classes & Immutability
768
+ - data class for value objects with auto-generated equals, hashCode, toString
769
+ - Use copy() for "modifications" (maintains immutability)
770
+ - val everywhere; var sparingly
771
+ - Destructuring: val (x, y) = pair
772
+ - Private constructors for controlled creation
773
+ - sealed class for restricted hierarchies
774
+
775
+ ## Coroutines & Async
776
+ - async/await instead of callbacks
777
+ - Proper scope: GlobalScope avoided; use lifecycle scopes
778
+ - Exception handling in coroutine builders
779
+ - Cancellation respected in loops
780
+ - launch vs async: launch for fire-and-forget, async for results
781
+ - Job/Task properly awaited
782
+
783
+ ## Control Flow & When Expressions
784
+ - when instead of if-else chains (>2 branches)
785
+ - when exhaustive or explicit else
786
+ - Scope functions (let, run, apply, also) appropriately used
787
+ - if-expressions return values when possible
788
+ - Early returns to avoid nesting
789
+ - Guard clauses instead of nested blocks
790
+
791
+ ## Extension Functions & Higher-Order Functions
792
+ - Extension functions for utility operations
793
+ - Receiver clarity in extension scopes
794
+ - No extensions on Any/Object
795
+ - Lambdas single-expression when possible
796
+ - it implicit parameter understood
797
+ - Function types clear in signatures
798
+
799
+ ## Collections & Sequences
800
+ - listOf, mapOf, setOf for immutable collections
801
+ - Sequences for lazy evaluation chains
802
+ - map/filter/reduce chains clear and efficient
803
+ - groupBy for grouping; associate for map creation
804
+ - No unnecessary list conversions
805
+ - forEach/forEachIndexed over manual loops
806
+
807
+ ## Strings & Text
808
+ - String templates (with ${'${}'}) instead of concatenation
809
+ - Triple quotes (""" """) for multiline
810
+ - Raw strings for regex/JSON
811
+ - No string building in loops
812
+
813
+ ## Testing & Spring Integration
814
+ - JUnit 5 with @Test
815
+ - Mockk or similar for mocking
816
+ - Test names describe behavior
817
+ - Arrange-Act-Assert pattern
818
+ - KDoc for public APIs
819
+ - @SpringBootTest for integration tests
820
+
821
+ ## Code Style & Conventions
822
+ - ktlint for consistent formatting
823
+ - No redundant modifiers (public, final)
824
+ - camelCase for functions; PascalCase for types
825
+ - Comments explain "why" not "what"
826
+ - Function length ~30 lines; file length ~300 lines
827
827
  - Named arguments for functions with >3 parameters`,
828
- php: `# PHP Code Standards
829
-
830
- ## Type Safety & Strict Types
831
- - declare(strict_types=1) at the top of EVERY file
832
- - Type all parameters and return types
833
- - Type class properties
834
- - Avoid mixed type; be specific
835
- - Use typed properties (PHP 7.4+)
836
- - Static analysis with phpstan or psalm
837
-
838
- ## Null Safety & Error Handling
839
- - Null coalescing (??) over isset checks
840
- - Nullsafe operator (?->) for deep property access
841
- - No silent null failures
842
- - Type hints include ? for nullable types
843
- - Guard clauses for early returns
844
- - Specific exception handling, not catch(Exception)
845
-
846
- ## PSR Standards & Code Style
847
- - PSR-1: Basic Coding Standard
848
- - PSR-12: Extended Coding Style
849
- - PSR-4: Autoloading via Composer
850
- - 4-space indentation
851
- - CamelCase for classes; camelCase for methods
852
- - php_eol for line endings
853
-
854
- ## Modern PHP Features (8.1+)
855
- - Enums for restricted value sets
856
- - Readonly properties for immutability
857
- - Match expressions instead of switch
858
- - Named arguments for clarity
859
- - Constructor promotion (public __construct(private string $name))
860
- - Fibers for async control flow
861
-
862
- ## Eloquent & Database
863
- - Model relationships defined clearly
864
- - Eager loading (with()) prevents N+1
865
- - select() for specific columns
866
- - Query scopes for reusable logic
867
- - Soft deletes for historical data
868
- - Mass assignment protection ($guarded, $fillable)
869
-
870
- ## Validation & Security
871
- - Request validation classes for input
872
- - Validate ALL user input
873
- - Custom validation messages
874
- - Gate/Policy for authorization
875
- - CSRF protection enabled
876
- - Parameterized queries (ORM handles this)
877
-
878
- ## Collections & Functional
879
- - Illuminate\Support\Collection methods
880
- - map/filter/reduce for transformations
881
- - array functions for simple operations
882
- - No manual loops when collection methods suffice
883
- - Null-safe operations with collection methods
884
- - Type-safe collection usage
885
-
886
- ## Laravel Patterns
887
- - Service/Repository for business logic
888
- - Middleware for cross-cutting concerns
889
- - Jobs/Queues for async operations
890
- - Service providers for registration
891
- - Facades appropriately used
892
- - Dependency injection via constructor
893
-
894
- ## Testing
895
- - PHPUnit for unit tests
896
- - Feature tests for user workflows
897
- - Mocking external dependencies
898
- - Test database transactions
899
- - Meaningful assertion messages
900
- - Good test organization
901
-
902
- ## Documentation & Strings
903
- - Docblock comments on public methods
904
- - README explains setup and usage
905
- - PHPDoc for parameter/return types
906
- - Heredoc/Nowdoc for multiline strings
907
- - No hardcoded values (use config)
828
+ php: `# PHP Code Standards
829
+
830
+ ## Type Safety & Strict Types
831
+ - declare(strict_types=1) at the top of EVERY file
832
+ - Type all parameters and return types
833
+ - Type class properties
834
+ - Avoid mixed type; be specific
835
+ - Use typed properties (PHP 7.4+)
836
+ - Static analysis with phpstan or psalm
837
+
838
+ ## Null Safety & Error Handling
839
+ - Null coalescing (??) over isset checks
840
+ - Nullsafe operator (?->) for deep property access
841
+ - No silent null failures
842
+ - Type hints include ? for nullable types
843
+ - Guard clauses for early returns
844
+ - Specific exception handling, not catch(Exception)
845
+
846
+ ## PSR Standards & Code Style
847
+ - PSR-1: Basic Coding Standard
848
+ - PSR-12: Extended Coding Style
849
+ - PSR-4: Autoloading via Composer
850
+ - 4-space indentation
851
+ - CamelCase for classes; camelCase for methods
852
+ - php_eol for line endings
853
+
854
+ ## Modern PHP Features (8.1+)
855
+ - Enums for restricted value sets
856
+ - Readonly properties for immutability
857
+ - Match expressions instead of switch
858
+ - Named arguments for clarity
859
+ - Constructor promotion (public __construct(private string $name))
860
+ - Fibers for async control flow
861
+
862
+ ## Eloquent & Database
863
+ - Model relationships defined clearly
864
+ - Eager loading (with()) prevents N+1
865
+ - select() for specific columns
866
+ - Query scopes for reusable logic
867
+ - Soft deletes for historical data
868
+ - Mass assignment protection ($guarded, $fillable)
869
+
870
+ ## Validation & Security
871
+ - Request validation classes for input
872
+ - Validate ALL user input
873
+ - Custom validation messages
874
+ - Gate/Policy for authorization
875
+ - CSRF protection enabled
876
+ - Parameterized queries (ORM handles this)
877
+
878
+ ## Collections & Functional
879
+ - Illuminate\Support\Collection methods
880
+ - map/filter/reduce for transformations
881
+ - array functions for simple operations
882
+ - No manual loops when collection methods suffice
883
+ - Null-safe operations with collection methods
884
+ - Type-safe collection usage
885
+
886
+ ## Laravel Patterns
887
+ - Service/Repository for business logic
888
+ - Middleware for cross-cutting concerns
889
+ - Jobs/Queues for async operations
890
+ - Service providers for registration
891
+ - Facades appropriately used
892
+ - Dependency injection via constructor
893
+
894
+ ## Testing
895
+ - PHPUnit for unit tests
896
+ - Feature tests for user workflows
897
+ - Mocking external dependencies
898
+ - Test database transactions
899
+ - Meaningful assertion messages
900
+ - Good test organization
901
+
902
+ ## Documentation & Strings
903
+ - Docblock comments on public methods
904
+ - README explains setup and usage
905
+ - PHPDoc for parameter/return types
906
+ - Heredoc/Nowdoc for multiline strings
907
+ - No hardcoded values (use config)
908
908
  - Localization for user-facing strings`,
909
- sql: `# SQL Code Standards
910
-
911
- ## Security (SQL Injection Prevention)
912
- - Always use parameterized queries (? or :name)
913
- - Never string-interpolate user input
914
- - Input validation before SQL operations
915
- - User input never directly in WHERE/SELECT
916
- - Prepared statements cached and reused
917
- - Stored procedures with parameter binding
918
- - ORM systems with parameterization
919
-
920
- ## Query Optimization
921
- - N+1 query prevention; use JOINs
922
- - SELECT specific columns, never SELECT *
923
- - Pagination for large result sets
924
- - EXPLAIN PLAN for complex queries
925
- - Indexes on WHERE, JOIN, ORDER BY columns
926
- - Join order matters for optimizer
927
- - Subqueries not in SELECT list
928
-
929
- ## Schema Design & Constraints
930
- - Primary keys on every table
931
- - Foreign keys establish relationships
932
- - Data types match actual values
933
- - NOT NULL constraints explicit
934
- - UNIQUE constraints for natural keys
935
- - Normalization (3NF minimum)
936
- - No magic numbers as IDs
937
-
938
- ## Migrations & Version Control
939
- - Migrations reversible (up/down)
940
- - Schema changes safe (add before remove)
941
- - Data migrations with rollback path
942
- - Test migrations up and down
943
- - Breaking changes documented
944
- - Backward compatibility maintained
945
- - One migration per change
946
-
947
- ## Performance & Indexing
948
- - Indexes on high-cardinality columns
949
- - Composite indexes for multi-column filters
950
- - Covering indexes for hot queries
951
- - No redundant indexes
952
- - Index maintenance cost considered
953
- - Statistics updated regularly
954
-
955
- ## Data Integrity & Testing
956
- - Audit columns (created_at, updated_at)
957
- - Soft deletes for historical data
958
- - Archival strategy documented
959
- - Backup/restore tested
960
- - Consistent validation rules
961
- - Temporal data handled correctly
962
-
963
- ## Comments & Documentation
964
- - Comments on complex queries
965
- - Document table purposes
966
- - Explain non-obvious indexes
967
- - Record any known performance issues
909
+ sql: `# SQL Code Standards
910
+
911
+ ## Security (SQL Injection Prevention)
912
+ - Always use parameterized queries (? or :name)
913
+ - Never string-interpolate user input
914
+ - Input validation before SQL operations
915
+ - User input never directly in WHERE/SELECT
916
+ - Prepared statements cached and reused
917
+ - Stored procedures with parameter binding
918
+ - ORM systems with parameterization
919
+
920
+ ## Query Optimization
921
+ - N+1 query prevention; use JOINs
922
+ - SELECT specific columns, never SELECT *
923
+ - Pagination for large result sets
924
+ - EXPLAIN PLAN for complex queries
925
+ - Indexes on WHERE, JOIN, ORDER BY columns
926
+ - Join order matters for optimizer
927
+ - Subqueries not in SELECT list
928
+
929
+ ## Schema Design & Constraints
930
+ - Primary keys on every table
931
+ - Foreign keys establish relationships
932
+ - Data types match actual values
933
+ - NOT NULL constraints explicit
934
+ - UNIQUE constraints for natural keys
935
+ - Normalization (3NF minimum)
936
+ - No magic numbers as IDs
937
+
938
+ ## Migrations & Version Control
939
+ - Migrations reversible (up/down)
940
+ - Schema changes safe (add before remove)
941
+ - Data migrations with rollback path
942
+ - Test migrations up and down
943
+ - Breaking changes documented
944
+ - Backward compatibility maintained
945
+ - One migration per change
946
+
947
+ ## Performance & Indexing
948
+ - Indexes on high-cardinality columns
949
+ - Composite indexes for multi-column filters
950
+ - Covering indexes for hot queries
951
+ - No redundant indexes
952
+ - Index maintenance cost considered
953
+ - Statistics updated regularly
954
+
955
+ ## Data Integrity & Testing
956
+ - Audit columns (created_at, updated_at)
957
+ - Soft deletes for historical data
958
+ - Archival strategy documented
959
+ - Backup/restore tested
960
+ - Consistent validation rules
961
+ - Temporal data handled correctly
962
+
963
+ ## Comments & Documentation
964
+ - Comments on complex queries
965
+ - Document table purposes
966
+ - Explain non-obvious indexes
967
+ - Record any known performance issues
968
968
  - Database version requirements noted`,
969
- csharp: `# C# Code Standards
970
-
971
- ## Code Style & Conventions
972
- - Follow Microsoft C# Coding Conventions
973
- - PascalCase for public members; camelCase for private
974
- - 4-space indentation
975
- - Meaningful names for all identifiers
976
- - Max function length ~30 lines
977
- - Single Responsibility Principle
978
-
979
- ## Language Features
980
- - LINQ for collection queries (not loops)
981
- - async/await for I/O operations
982
- - Nullable reference types (C# 8+)
983
- - Pattern matching in switch statements
984
- - Records for immutable data types
985
- - Tuples for returning multiple values
986
- - String interpolation ($"...")
987
-
988
- ## Null Safety
989
- - Enable nullable reference types in csproj
990
- - Non-null types by default; ? for nullable
991
- - Use null-conditional operators (?., ?[])
992
- - Guard clauses for null checks
993
- - Null coalescing (??) for defaults
994
-
995
- ## Dependency Injection & Architecture
996
- - Constructor injection for dependencies
997
- - Interface-based design
998
- - Dependency Injection containers
999
- - Inversion of Control pattern
1000
- - SOLID principles
1001
-
1002
- ## Testing & Documentation
1003
- - Unit tests with xUnit or NUnit
1004
- - Mock dependencies with Moq
1005
- - Test names describe behavior
1006
- - Integration tests for workflows
1007
- - XML documentation on public APIs
1008
- - Examples in documentation
1009
-
1010
- ## async/await & Threading
1011
- - async/await for I/O operations
1012
- - ConfigureAwait(false) in libraries
1013
- - Proper exception handling in async
1014
- - Avoid sync-over-async patterns
1015
- - Task.Run for CPU-bound work
1016
- - Cancellation tokens passed through
1017
-
1018
- ## Collections & Generics
1019
- - LINQ over manual loops
1020
- - Generic constraints explicit
1021
- - Immutable collections for safety
1022
- - IEnumerable for lazy evaluation
1023
- - Choose collection type by use case
969
+ csharp: `# C# Code Standards
970
+
971
+ ## Code Style & Conventions
972
+ - Follow Microsoft C# Coding Conventions
973
+ - PascalCase for public members; camelCase for private
974
+ - 4-space indentation
975
+ - Meaningful names for all identifiers
976
+ - Max function length ~30 lines
977
+ - Single Responsibility Principle
978
+
979
+ ## Language Features
980
+ - LINQ for collection queries (not loops)
981
+ - async/await for I/O operations
982
+ - Nullable reference types (C# 8+)
983
+ - Pattern matching in switch statements
984
+ - Records for immutable data types
985
+ - Tuples for returning multiple values
986
+ - String interpolation ($"...")
987
+
988
+ ## Null Safety
989
+ - Enable nullable reference types in csproj
990
+ - Non-null types by default; ? for nullable
991
+ - Use null-conditional operators (?., ?[])
992
+ - Guard clauses for null checks
993
+ - Null coalescing (??) for defaults
994
+
995
+ ## Dependency Injection & Architecture
996
+ - Constructor injection for dependencies
997
+ - Interface-based design
998
+ - Dependency Injection containers
999
+ - Inversion of Control pattern
1000
+ - SOLID principles
1001
+
1002
+ ## Testing & Documentation
1003
+ - Unit tests with xUnit or NUnit
1004
+ - Mock dependencies with Moq
1005
+ - Test names describe behavior
1006
+ - Integration tests for workflows
1007
+ - XML documentation on public APIs
1008
+ - Examples in documentation
1009
+
1010
+ ## async/await & Threading
1011
+ - async/await for I/O operations
1012
+ - ConfigureAwait(false) in libraries
1013
+ - Proper exception handling in async
1014
+ - Avoid sync-over-async patterns
1015
+ - Task.Run for CPU-bound work
1016
+ - Cancellation tokens passed through
1017
+
1018
+ ## Collections & Generics
1019
+ - LINQ over manual loops
1020
+ - Generic constraints explicit
1021
+ - Immutable collections for safety
1022
+ - IEnumerable for lazy evaluation
1023
+ - Choose collection type by use case
1024
1024
  - No unnecessary allocations`,
1025
1025
  };
1026
1026
  return detailedRules[language] || BUILTIN_RULES[language] || `# Rules for ${language}\n(No rules defined for this language)`;
@@ -1031,7 +1031,7 @@ export function printRules() {
1031
1031
  for (const s of sets) {
1032
1032
  console.log(chalk.dim(` ${s.language.padEnd(15)} [${s.source}]`));
1033
1033
  }
1034
- console.log(chalk.dim(' \n Custom rules: ~/.crowcoder/rules/<language>.md'));
1034
+ console.log(chalk.dim(' \n Custom rules: ~/.compact-agent/rules/<language>.md'));
1035
1035
  console.log();
1036
1036
  }
1037
1037
  //# sourceMappingURL=rules.js.map