# Lint Rules Rationale

<<<<<<< HEAD
This document explains why each lint rule was promoted to error or disabled during the lint cleanup initiative (Epic: clean-up-lints, #154).

**Last Updated**: 2025-10-20 (Issue #159 - Documentation & Rollout)

---

## Table of Contents

- [Overview](#overview)
- [TypeScript/ESLint Rules](#typescripteslint-rules)
  - [Promoted to Error](#promoted-to-error)
  - [Removed Rules](#removed-rules)
- [TypeScript Compiler Flags](#typescript-compiler-flags)
- [Exception Policy](#exception-policy)
- [References](#references)

---

## Overview

During the lint cleanup initiative, we audited all ESLint rules and made evidence-based decisions to:
1. **Promote quality-focused rules to error** - Rules that prevent bugs or improve maintainability
2. **Remove style-only rules** - Rules better handled through code review or Prettier
3. **Enable strict TypeScript compiler options** - Maximum type safety

**Result**: 697 of 727 violations fixed (95.9% success rate), all production code lint-clean.

**Key Principle**: Every error should signal a real quality issue that must be fixed, not a style preference.
=======
This document provides comprehensive rationale for all linting rule decisions in the Buzztrail codebase. It explains why rules were promoted to errors, removed, or kept as warnings.

## Table of Contents
- [TypeScript/ESLint Rules](#typescripteslint-rules)
  - [Promoted to Error](#promoted-to-error-was-warning)
  - [Disabled Rules](#disabled-rules)
- [Python/Ruff Rules](#pythonruff-rules)
  - [Key Rules - Bug Prevention](#key-rules---bug-prevention)
  - [Key Rules - Code Quality](#key-rules---code-quality)
  - [Disabled Rules (Formatting)](#disabled-rules-formatting)
>>>>>>> lint-cleanup-initiative

---

## TypeScript/ESLint Rules

<<<<<<< HEAD
### Promoted to Error

These rules were promoted from `warn` to `error` during the cleanup initiative.

#### `@typescript-eslint/no-explicit-any`

**Status**: `error` (was: `warn`)
**Category**: Type Safety (P0 - Critical)

**Why**: The `any` type defeats TypeScript's type safety by disabling all type checking. It should only be used with explicit justification.

**Impact**: 510 instances replaced with proper types during cleanup (97.5% of violations).

**How to fix**:
```typescript
// ❌ BAD: any defeats type safety
function process(data: any) {
  return data.value; // No type checking!
}

// ✅ GOOD: Use specific interface
interface ProcessData {
  value: string;
}
function process(data: ProcessData) {
  return data.value; // Type-safe!
}

// ✅ GOOD: Use unknown + type narrowing
function process(data: unknown) {
  if (isProcessData(data)) {
    return data.value; // Type-safe after guard
  }
  throw new Error('Invalid data');
}

// ✅ GOOD: Generic objects
function process(data: Record<string, unknown>) {
  // Safe for key-value pairs
}
```

**Exceptions**: Complex generic types, third-party library integrations (must document with inline comment).

**Learn More**: [TypeScript Handbook - any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)
=======
### Promoted to Error (was: warning)

These rules were promoted from warnings to errors because they catch bugs, prevent logic errors, or enforce critical type safety.
>>>>>>> lint-cleanup-initiative

---

#### `@typescript-eslint/no-unused-vars`

<<<<<<< HEAD
**Status**: `error` (was: `warn`)
**Category**: Code Quality

**Why**: Unused variables indicate dead code, incomplete refactoring, or typos. They clutter the codebase and waste developer time.

**Impact**: 181 instances removed or prefixed during cleanup (98.4% of violations).

**How to fix**:
```typescript
// ❌ BAD: Unused import
import { useState, useEffect } from 'react'; // useEffect never used

// ✅ GOOD: Remove unused
import { useState } from 'react';

// ❌ BAD: Unused parameter
function handler(req, res) {
  // res never used
  return req.body;
}

// ✅ GOOD: Prefix with underscore
function handler(req, _res) {
  return req.body;
}

// ❌ BAD: Unused variable
const [state, setState] = useState(0);  // setState never used

// ✅ GOOD: Destructure only what's needed
const [state] = useState(0);
```

**Configuration**:
```javascript
'@typescript-eslint/no-unused-vars': ['error', {
  argsIgnorePattern: '^_',
  varsIgnorePattern: '^_',
  caughtErrorsIgnorePattern: '^_'
}]
```

**Pattern**: Prefix with `_` if variable is intentionally unused (e.g., for interface compliance).
=======
**Category:** Type Safety / Dead Code Detection

**Why:** Unused variables are a strong indicator of:
- Dead code that should be removed
- Incomplete refactoring
- Logic errors where a variable was meant to be used
- Code bloat that makes the codebase harder to maintain

**Impact:** Error-level enforcement prevents accumulation of unused code and forces developers to clean up as they go.

**How to fix:**
- Remove the unused variable
- If it's a function parameter that must match an interface, prefix with underscore: `_unusedParam`
- If it's destructured values where you only need some, use rest syntax: `const { needed, ...rest } = obj`

**Example:**
```typescript
// Before (warning)
function processUser(user: User, context: Context) {
  // 'context' is never used - bug or incomplete implementation?
  return user.name;
}

// After (fixed)
function processUser(user: User) {
  return user.name;
}

// Or if parameter is required by interface
function processUser(user: User, _context: Context) {
  return user.name;
}
```

**Exceptions:** None - unused code should always be removed or explicitly marked with underscore prefix.

---

#### `@typescript-eslint/no-explicit-any`

**Category:** Type Safety

**Why:** The `any` type completely defeats TypeScript's type system:
- Loses all type checking and IntelliSense
- Can hide bugs that would be caught by proper typing
- Makes code harder to refactor safely
- Spreads through the codebase ("type pollution")

**Impact:** Forcing proper types makes the codebase more maintainable and catches bugs at compile time.

**How to fix:**
- Define proper types or interfaces for your data
- Use `unknown` for truly unknown types, then narrow with type guards
- Use generics for reusable code with multiple types
- For complex third-party types, create wrapper types
- As last resort, use `any` with a comment explaining why and a TODO to fix it

**Example:**
```typescript
// Before (warning)
function processData(data: any) {
  return data.value.toUpperCase(); // No type safety, could crash at runtime
}

// After (fixed - proper types)
interface ProcessableData {
  value: string;
}

function processData(data: ProcessableData) {
  return data.value.toUpperCase(); // Type-safe
}

// After (fixed - unknown with type guard)
function processData(data: unknown) {
  if (typeof data === 'object' && data !== null && 'value' in data) {
    const typed = data as { value: unknown };
    if (typeof typed.value === 'string') {
      return typed.value.toUpperCase();
    }
  }
  throw new Error('Invalid data format');
}

// After (fixed - generics)
function processData<T extends { value: string }>(data: T) {
  return data.value.toUpperCase();
}
```

**Exceptions:**
- Complex third-party library integrations where types are truly unknowable
- Working with highly dynamic APIs (must document with comment)
- Temporary during migration (add TODO comment)

All uses of `any` should include a comment explaining why it's necessary.
>>>>>>> lint-cleanup-initiative

---

#### `@typescript-eslint/no-floating-promises`

<<<<<<< HEAD
**Status**: `error` (was: `warn`)
**Category**: Async Bug Prevention (P0 - Critical)

**Why**: Unhandled promises can cause silent failures, race conditions, and hard-to-debug production issues. Async errors may go unnoticed.

**Impact**: 58 instances fixed during cleanup (92.1% of violations).

**How to fix**:
```typescript
// ❌ BAD: Promise ignored (errors swallowed!)
async function processData() {
  riskyAsyncOperation(); // May throw, not handled
}

// ✅ GOOD: Await the promise
async function processData() {
  await riskyAsyncOperation();
}

// ✅ GOOD: Void for fire-and-forget (intentional)
async function processData() {
  void riskyAsyncOperation(); // Explicitly indicates we're not waiting
}

// ✅ GOOD: Handle errors explicitly
async function processData() {
  riskyAsyncOperation().catch(err => {
    console.error('Background operation failed:', err);
  });
}
```

**Real-world example from cleanup**:
```typescript
// Before (from shared-components)
daily?.join(); // Promise ignored - errors lost!

// After
void daily?.join(); // Explicit fire-and-forget
```

**Learn More**: [Promise Best Practices](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
=======
**Category:** Bug Prevention

**Why:** Promises that are not awaited or handled can cause:
- Race conditions where code executes in unexpected order
- Unhandled promise rejections that crash the application
- Silent failures where errors are never caught
- Difficult-to-debug async issues

**Impact:** Error-level enforcement ensures all async operations are properly handled.

**How to fix:**
- Add `await` if you need to wait for the result
- Add `.catch()` handler if you want to fire-and-forget but handle errors
- Wrap in `void` operator if you intentionally want to ignore (rare, needs comment)
- Return the promise if it should be handled by the caller

**Example:**
```typescript
// Before (warning - floating promise)
async function saveUser(user: User) {
  database.save(user); // Promise not awaited - may not complete before function returns!
  console.log('User saved'); // This might log before save actually completes
}

// After (fixed - awaited)
async function saveUser(user: User) {
  await database.save(user); // Wait for save to complete
  console.log('User saved'); // Now this logs after save completes
}

// After (fixed - fire-and-forget with error handling)
async function saveUser(user: User) {
  database.save(user).catch(err => {
    console.error('Failed to save user:', err);
    // Handle error appropriately
  });
  // Function continues without waiting
}

// After (fixed - return for caller to handle)
async function saveUser(user: User) {
  return database.save(user); // Caller must handle the promise
}

// After (fixed - intentional void with comment)
async function saveUser(user: User) {
  // Intentionally not waiting - save happens in background
  // Error handling done by global error handler
  void database.save(user);
}
```

**Exceptions:** Very rare. If you truly want fire-and-forget, use `void` operator and add a comment explaining why.
>>>>>>> lint-cleanup-initiative

---

#### `@typescript-eslint/no-misused-promises`

<<<<<<< HEAD
**Status**: `error` (was: `warn`)
**Category**: Async Bug Prevention (P0 - Critical)

**Why**: Async functions in non-async contexts (like event handlers or Express routes) can cause unhandled promise rejections and unexpected behavior.

**Impact**: 61 instances fixed during cleanup (91.0% of violations).

**How to fix**:
```typescript
// ❌ BAD: Async function in Express route (rejection not handled)
app.post('/api/data', async (req, res) => {
  await processData(req.body);
  res.json({ ok: true });
});

// ✅ GOOD: IIFE pattern for Express/event handlers
app.post('/api/data', (req, res) => void (async () => {
  await processData(req.body);
  res.json({ ok: true });
})());

// ❌ BAD: Async function in event handler
button.addEventListener('click', async () => {
  await doWork();
});

// ✅ GOOD: IIFE pattern for DOM events
button.addEventListener('click', () => void (async () => {
  await doWork();
})());
```

**Pattern**: Use `(req, res) => void (async () => { ... })()` for Express routes and event handlers.

**Real-world example from cleanup** (slide-system):
```typescript
// Before (102 errors in slide-system)
async function handler(req: MotiaRequest, { emit }: MotiaContext) {
  await doWork();
  emit('event', data); // emit() isn't async but was awaited
}

// After
function handler(req: MotiaRequest, { emit }: MotiaContext) {
  return (async () => {
    await doWork();
    emit('event', data); // No incorrect await
  })();
}
```

=======
**Category:** Bug Prevention

**Why:** Misusing promises in incorrect contexts causes logic errors:
- Using promise in if/while condition (always truthy)
- Passing promise where non-promise expected
- Promise in array destructuring
- Promise in spread operations

**Impact:** Prevents subtle async bugs that are hard to debug.

**How to fix:**
- Add `await` to get the value from the promise
- Use `.then()` for chaining if not in async context
- Restructure code to properly handle async operations

**Example:**
```typescript
// Before (warning - promise in condition)
async function checkUser() {
  const isValid = validateUser(); // Returns Promise<boolean>
  if (isValid) { // Promise object is always truthy!
    console.log('Valid'); // Always prints, even if validation fails
  }
}

// After (fixed)
async function checkUser() {
  const isValid = await validateUser(); // Get actual boolean value
  if (isValid) {
    console.log('Valid'); // Only prints if validation succeeds
  }
}

// Before (warning - promise in array)
async function getNames() {
  const user1 = getUser(1); // Promise<User>
  const user2 = getUser(2); // Promise<User>
  return [user1, user2].map(u => u.name); // Promises don't have .name!
}

// After (fixed)
async function getNames() {
  const [user1, user2] = await Promise.all([
    getUser(1),
    getUser(2)
  ]);
  return [user1, user2].map(u => u.name);
}
```

**Exceptions:** None - promises must always be properly awaited or handled.

>>>>>>> lint-cleanup-initiative
---

#### `@typescript-eslint/await-thenable`

<<<<<<< HEAD
**Status**: `error` (was: `warn`)
**Category**: Async Correctness

**Why**: Using `await` on non-promises is unnecessary and indicates confusion about async/await. May hide bugs or performance issues.

**Impact**: 6 instances fixed during cleanup (66.7% of violations).

**How to fix**:
```typescript
// ❌ BAD: Awaiting non-promise
await emit('event', data); // emit() is sync

// ✅ GOOD: Don't await sync functions
emit('event', data);

// ❌ BAD: Awaiting already-resolved value
const value = await 42;

// ✅ GOOD: Use value directly
const value = 42;
```

**Real-world example from cleanup** (slide-system):
```typescript
// Before (20+ instances)
await emit('slideshow:generated', { ... }); // emit() returns void

// After
emit('slideshow:generated', { ... });
```
=======
**Category:** Bug Prevention

**Why:** Using `await` on non-promise values indicates:
- Misunderstanding of the code (thought it was async)
- Copy-paste error
- Leftover from refactoring
- Logic error where wrong function is called

**Impact:** Catches mistakes and enforces correct async understanding.

**How to fix:**
- Remove `await` if value is not a promise
- Fix the function call if wrong function was used
- Make the function async if it should return a promise

**Example:**
```typescript
// Before (warning)
async function getUser(id: number) {
  const user = await findUserSync(id); // findUserSync returns User, not Promise!
  return user;
}

// After (fixed - remove await)
async function getUser(id: number) {
  const user = findUserSync(id);
  return user;
}

// Or after (fixed - use correct async function)
async function getUser(id: number) {
  const user = await findUserAsync(id); // Use async version
  return user;
}
```

**Exceptions:** None - `await` should only be used on promises.
>>>>>>> lint-cleanup-initiative

---

#### `no-template-curly-in-string`

<<<<<<< HEAD
**Status**: `error` (was: `warn`)
**Category**: Common Typos

**Why**: Catches common mistake of using `${variable}` in regular strings instead of template literals. This is almost always a bug.

**How to fix**:
```typescript
// ❌ BAD: Template syntax in regular string (outputs literally!)
const message = 'Hello ${name}'; // Outputs: "Hello ${name}"

// ✅ GOOD: Use template literal
const message = `Hello ${name}`; // Outputs: "Hello John"
=======
**Category:** Bug Prevention

**Why:** Detects when template literal syntax is used in a regular string:
- Almost always a developer mistake (forgot to use backticks)
- Results in literal string like "Hello ${name}" instead of interpolated value
- Very common typo that produces broken output

**Impact:** Catches a very common mistake that would otherwise go to production.

**How to fix:**
- Change single/double quotes to backticks for template literals
- Or escape the `${}` if you actually want literal `${}`

**Example:**
```typescript
// Before (warning - will print literal "${name}")
const greeting = 'Hello ${name}'; // Forgot backticks!
console.log(greeting); // Prints: Hello ${name}

// After (fixed)
const greeting = `Hello ${name}`; // Backticks for template literal
console.log(greeting); // Prints: Hello John

// Or if you really want literal ${}
const regex = 'pattern: \\${variable}'; // Escaped
```

**Exceptions:** Very rare cases where you want literal `${}` in a string (e.g., documentation, regex patterns). Escape with backslash.

---

### Disabled Rules

These rules were removed because they are style-focused, too rigid, or better handled by other tools/processes.

---

#### `max-lines`

**Category:** Code Style

**Why disabled:**
- File length is a useful code quality metric but enforcing a hard limit is too rigid
- Legitimate reasons for long files:
  - Generated code or types
  - Complex state machines or reducers
  - Comprehensive test suites
  - Data/constant definitions
  - Configuration objects
- Arbitrary limits don't account for context
- Better addressed through code review and refactoring discussions

**Alternative approach:**
- Use code review to identify files that should be split
- Use architectural guidelines for when to split files
- Monitor file length as a metric without blocking builds
- Consider file length in the context of complexity and cohesion

**Example of legitimate long file:**
```typescript
// apps/extension/src/state/reducer.ts (1200 lines)
// Complex state machine with many action handlers
// Splitting would make it harder to understand state transitions
// Better kept together despite length
>>>>>>> lint-cleanup-initiative
```

---

<<<<<<< HEAD
### Removed Rules

These rules were removed as they're style-only or better handled through other means.

#### `max-lines`, `max-lines-per-function`, `complexity`

**Status**: Removed (was: `warn`)
**Category**: Style/Metrics

**Why**:
- **Arbitrary thresholds**: No one-size-fits-all number works for all contexts
- **Encourages poor abstractions**: Developers split functions just to meet limits, not for better design
- **Better handled through code review**: Reviewers can flag genuinely complex code
- **Context-dependent**: A 200-line utility function may be fine; a 50-line business logic function may need splitting

**Example of bad refactoring from artificial limits**:
```typescript
// ❌ BAD: Split just to meet line limit (no benefit)
function processPart1(data) { ... }
function processPart2(data) { ... }
function processPart3(data) { ... }

// ✅ GOOD: One cohesive function (even if longer)
function processData(data) {
  // All related logic together, easy to understand
}
```

**Alternative**: Use code review to identify genuinely complex or long functions that need refactoring.

---

## TypeScript Compiler Flags

The following strict compiler flags are enabled in `tsconfig.base.json`:

### `strict: true`

**Enables**: All strict type checking flags
**Why**: Maximum type safety, catches more bugs at compile time
**Status**: Enabled since project inception

Sub-flags included:
- `noImplicitAny`: Every variable must have an explicit or inferred type
- `strictNullChecks`: `null` and `undefined` must be handled explicitly
- `strictFunctionTypes`: Function parameter types checked contravariantly
- `strictBindCallApply`: `bind`, `call`, `apply` type-checked
- `strictPropertyInitialization`: Class properties must be initialized
- `noImplicitThis`: `this` must have explicit type in functions
- `alwaysStrict`: Emit `"use strict"` in all files

### Additional Flags

- `noUnusedLocals`: Warn about unused local variables (caught by ESLint no-unused-vars)
- `noUnusedParameters`: Warn about unused parameters (caught by ESLint no-unused-vars)
- `noImplicitReturns`: All code paths must return a value
- `noFallthroughCasesInSwitch`: Switch cases must break or return

**Learn More**: [TypeScript Compiler Options](https://www.typescriptlang.org/tsconfig)

---

## Exception Policy

When you MUST use an exception (e.g., `eslint-disable`), follow these guidelines:

### ✅ GOOD: Inline disable with clear justification

```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Legacy third-party API requires 'any', documented in #123
function legacyIntegration(response: any) {
  // ...
}
```

### ✅ GOOD: Link to issue or documentation

```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- See LINT_CLEANUP_DEBT.md
const mockData: any = loadTestFixture();
```

### ❌ BAD: File-level disable with no explanation

```typescript
/* eslint-disable @typescript-eslint/no-explicit-any */
// Disables rule for entire file - too broad!
```

### ❌ BAD: Inline disable with no justification

```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = response; // Why is 'any' needed? Unclear!
```

### Exception Guidelines

1. **Use inline disables** (`eslint-disable-next-line`), not file-level
2. **Always include justification** in comment (why is exception needed?)
3. **Link to documentation** (issue number, LINT_CLEANUP_DEBT.md, etc.)
4. **Be specific** about which rule to disable (not all rules)
5. **Consider if exception is temporary** and document plan to fix

---

## References

### Official Documentation
- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
- [ESLint Rules](https://eslint.org/docs/latest/rules/)
- [TypeScript ESLint Rules](https://typescript-eslint.io/rules/)

### Project Documentation
- [CONTRIBUTING.md](../CONTRIBUTING.md) - Contribution guidelines and lint standards
- [TYPE_SAFETY.md](./development/TYPE_SAFETY.md) - Type safety patterns and practices
- [LINT_TROUBLESHOOTING.md](./LINT_TROUBLESHOOTING.md) - Common errors and quick fixes

### Epic Documentation
- **Epic**: #154 - clean-up-lints
- **Issues**: #155 (Baseline), #157 (Config), #162 (Core Libs), #156 (Non-critical), #160 (Production), #163 (Validation), #158 (CI/CD), #159 (Documentation)
- **Summary**: `.claude/epics/clean-up-lints/LINT-CLEANUP-SUMMARY.md`
- **Validation**: `.claude/epics/clean-up-lints/updates/163-final/FINAL-VALIDATION-REPORT.md`

### Statistics

From the lint cleanup initiative:
- **697 violations fixed** (95.9% of 727 total)
- **510 `any` types replaced** with proper TypeScript types
- **181 unused variables removed** or prefixed with `_`
- **125 async bugs fixed** (floating promises, misused promises)
- **All production apps**: 0 lint errors ✅
- **All shared libraries**: 0 lint errors ✅

---

**Questions or Issues?**
- Check [LINT_TROUBLESHOOTING.md](./LINT_TROUBLESHOOTING.md) for common fixes
- Ask in #engineering Slack channel
- Reference this doc in code reviews

---

*Generated as part of Issue #159 - Documentation & Rollout*
*Epic: clean-up-lints (#154)*
=======
#### `max-lines-per-function`

**Category:** Code Style

**Why disabled:**
- Function length is a guideline, not a hard rule
- Legitimate reasons for long functions:
  - Switch statements with many cases (each case is simple)
  - Initialization/setup logic that must happen in specific order
  - Complex but linear workflows that are clearer when kept together
  - Test cases with many assertions
- Arbitrary limits encourage poor abstractions just to satisfy the rule
- Better addressed through code review focusing on complexity and clarity

**Alternative approach:**
- Use code review to identify functions that should be refactored
- Focus on complexity and clarity rather than line count
- Extract functions when it improves readability, not just to satisfy a rule
- Use the `complexity` metric as a better indicator of refactoring needs

**Example of legitimate long function:**
```typescript
// Initialization function with sequential steps
async function initializeApplication() {
  // 150 lines of sequential initialization
  // Each step depends on previous steps
  // Splitting into functions would add indirection without clarity
  // Better kept together despite length
}
```

---

#### `complexity`

**Category:** Code Style

**Why disabled:**
- Cyclomatic complexity is a useful metric but arbitrary thresholds don't account for context
- Some logic is inherently complex and cannot be simplified:
  - Business rules with many conditions
  - State machines with multiple states
  - Validation logic with comprehensive checks
- A high complexity score doesn't always mean the code is unclear
- A low complexity score doesn't guarantee readable code
- Better used as a discussion point in code review rather than blocking rule

**Alternative approach:**
- Monitor complexity as a metric without enforcing hard limits
- Use complexity to identify candidates for refactoring
- Focus on clarity, testability, and maintainability in code review
- Consider breaking down complex functions case-by-case
- Prioritize refactoring high-complexity AND high-churn files

**Example of legitimate complex function:**
```typescript
// Validation function with many business rules
function validateOrder(order: Order): ValidationResult {
  // Complexity score: 18
  // But each condition is a clear business rule
  // Breaking it up would scatter related validation logic
  // Better kept together despite high complexity
  if (/* rule 1 */) return { valid: false, reason: 'rule1' };
  if (/* rule 2 */) return { valid: false, reason: 'rule2' };
  // ... 15 more clear business rules ...
  return { valid: true };
}
```

---

## Summary

### Rules Promoted to Error (6)
All these rules catch bugs or enforce critical type safety:
- `@typescript-eslint/no-unused-vars` - Dead code detection
- `@typescript-eslint/no-explicit-any` - Type safety
- `@typescript-eslint/no-floating-promises` - Async bug prevention
- `@typescript-eslint/no-misused-promises` - Async bug prevention
- `@typescript-eslint/await-thenable` - Async correctness
- `no-template-curly-in-string` - Common typo detection

### Rules Disabled (3)
All these rules are style-focused and better handled through code review:
- `max-lines` - File length is context-dependent
- `max-lines-per-function` - Function length is context-dependent
- `complexity` - Complexity metrics are guidelines, not rules

---

## Implementation Notes

When promoting rules from warning to error:
1. First run the linter to identify all violations
2. Fix or suppress each violation with justification
3. Update the rule level in `.eslintrc.js`
4. Document any suppressions with comments explaining why

For disabled rules:
1. Remove from `.eslintrc.js`
2. Update code review checklist to cover these concerns
3. Consider adding them to CI metrics/reporting without blocking

---

---

## Python/Ruff Rules

All Python linting is configured in `pyproject.toml` files using Ruff. We enable comprehensive rule sets and promote ALL rules to error level for strict enforcement.

### Configuration Philosophy

Unlike TypeScript where we selectively enable rules, Python/Ruff configuration uses a **select-and-error** approach:
- Select rule categories (E, W, F, I, UP, B, C4, SIM)
- All selected rules are errors by default
- Only disable specific rules with documented rationale
- No warning-level rules - either error or disabled

**Currently enabled categories:**
- `E` - pycodestyle errors
- `W` - pycodestyle warnings
- `F` - Pyflakes (bug detection)
- `I` - isort (import sorting)
- `UP` - pyupgrade (modern Python syntax)
- `B` - flake8-bugbear (bug detection and best practices)
- `C4` - flake8-comprehensions (performance)
- `SIM` - flake8-simplify (code quality)

### Key Rules - Bug Prevention

These rules catch bugs that would cause runtime errors or silent failures.

---

#### `F401` - unused-import

**Category:** Dead Code Detection

**Why:** Consistency with TypeScript `no-unused-vars`. Unused imports:
- Increase module load time and memory usage
- Indicate incomplete refactoring or dead code
- Create confusion about actual dependencies
- Can hide name conflicts

**How to fix:**
- Remove the unused import
- If needed for type checking only, use `TYPE_CHECKING` guard
- If needed for side effects, add `# noqa: F401` with explanation

**Example:**
```python
# Before (error)
from typing import List, Dict  # Dict is unused
from datetime import datetime  # datetime is unused

def get_names() -> List[str]:
    return ["Alice", "Bob"]

# After (fixed - removed unused)
from typing import List

def get_names() -> List[str]:
    return ["Alice", "Bob"]

# Or for type-only imports (Python 3.8+)
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from module import LargeClass  # Only imported for type hints
```

---

#### `F821` - undefined-name

**Category:** Bug Prevention

**Why:** Using undefined names causes `NameError` at runtime. This catches:
- Typos in variable names
- Missing imports
- Variables used before assignment
- Names deleted or out of scope

**Example:**
```python
# Before (error)
def process_user():
    return usr.name  # Typo - should be 'user'

# After (fixed)
def process_user(user):
    return user.name
```

---

#### `B006` - mutable-argument-default

**Category:** Bug Prevention (Classic Python Gotcha)

**Why:** Mutable default arguments (list, dict, set) are shared across all function calls:
- Same object reused for every call
- Mutations persist between calls
- Causes mysterious bugs where data leaks between calls
- One of Python's most common pitfalls

**How to fix:**
- Use `None` as default, create mutable in function body
- Or use `dataclass` with `field(default_factory=...)`

**Example:**
```python
# Before (error - shared list!)
def add_item(item, items=[]):  # BUG: list shared across calls!
    items.append(item)
    return items

result1 = add_item(1)  # [1]
result2 = add_item(2)  # [1, 2] - unexpected!

# After (fixed)
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

result1 = add_item(1)  # [1]
result2 = add_item(2)  # [2] - correct!

# Or with dataclass
from dataclasses import dataclass, field

@dataclass
class Container:
    items: list = field(default_factory=list)  # Fresh list for each instance
```

---

#### `B008` - function-call-in-default-argument

**Category:** Bug Prevention

**Why:** Function calls in default arguments are evaluated once at function definition, not at call time:
- Default value computed only once when function is defined
- All calls share the same computed value
- Time-dependent defaults (like `datetime.now()`) don't update
- Can cause subtle timing bugs

**Example:**
```python
# Before (error)
from datetime import datetime

def log_event(message, timestamp=datetime.now()):  # BUG: timestamp never updates!
    print(f"{timestamp}: {message}")

log_event("Start")  # 2024-10-19 10:00:00
time.sleep(60)
log_event("End")    # 2024-10-19 10:00:00 - same timestamp!

# After (fixed)
def log_event(message, timestamp=None):
    if timestamp is None:
        timestamp = datetime.now()  # Fresh timestamp each call
    print(f"{timestamp}: {message}")
```

---

#### `B023` - function-uses-loop-variable

**Category:** Bug Prevention (Late Binding)

**Why:** Functions capturing loop variables exhibit late-binding behavior:
- Function doesn't capture the value, it captures the variable reference
- By the time function is called, loop variable has final value
- All functions in list end up using the same (last) value
- Classic Python closure gotcha

**Example:**
```python
# Before (error)
callbacks = []
for i in range(3):
    callbacks.append(lambda: print(i))  # Captures 'i' reference, not value!

for cb in callbacks:
    cb()  # Prints: 2, 2, 2 (not 0, 1, 2!)

# After (fixed - default argument captures value)
callbacks = []
for i in range(3):
    callbacks.append(lambda x=i: print(x))  # Captures value of i

for cb in callbacks:
    cb()  # Prints: 0, 1, 2 - correct!

# Or (fixed - functools.partial)
from functools import partial

callbacks = []
for i in range(3):
    callbacks.append(partial(print, i))

for cb in callbacks:
    cb()  # Prints: 0, 1, 2 - correct!
```

---

#### `E722` - bare-except

**Category:** Bug Prevention

**Why:** Consistency with TypeScript async error handling. Bare `except:` catches everything including:
- `SystemExit` - prevents program from exiting
- `KeyboardInterrupt` - makes programs impossible to interrupt (Ctrl+C)
- `GeneratorExit` - breaks generator cleanup
- Makes debugging much harder

**How to fix:**
- Catch specific exceptions you expect
- If you must catch all, use `except Exception:` (doesn't catch system exits)
- Add logging in exception handlers

**Example:**
```python
# Before (error)
try:
    process_data()
except:  # BAD: Catches KeyboardInterrupt, SystemExit, etc.
    print("Error")

# After (fixed - specific exceptions)
try:
    process_data()
except (ValueError, KeyError) as e:
    print(f"Data error: {e}")

# Or (fixed - catch all application exceptions)
try:
    process_data()
except Exception as e:  # Doesn't catch SystemExit, KeyboardInterrupt
    logger.error(f"Unexpected error: {e}")
    raise  # Re-raise after logging
```

---

### Key Rules - Code Quality

These rules enforce modern Python best practices and prevent code quality issues.

---

#### `UP006` - non-pep585-annotation

**Category:** Best Practice (Modern Python)

**Why:** Consistency with TypeScript modern syntax. Python 3.9+ allows built-in types in annotations:
- Use `list[str]` instead of `typing.List[str]`
- Use `dict[str, int]` instead of `typing.Dict[str, int]`
- More concise and Pythonic
- Reduces typing imports
- Future-proof (typing generics may be deprecated)

**Example:**
```python
# Before (error - old typing imports)
from typing import List, Dict, Tuple, Optional

def process(items: List[str]) -> Dict[str, Tuple[int, int]]:
    pass

# After (fixed - built-in generics, Python 3.9+)
def process(items: list[str]) -> dict[str, tuple[int, int]]:
    pass

# Optional still needs import
from typing import Optional

def find_user(id: int) -> Optional[dict]:
    pass

# Or use | syntax (Python 3.10+)
def find_user(id: int) -> dict | None:
    pass
```

---

#### `UP007` - non-pep604-annotation

**Category:** Best Practice (Modern Python)

**Why:** Python 3.10+ allows `X | Y` syntax for unions:
- Use `str | int` instead of `Union[str, int]`
- Use `str | None` instead of `Optional[str]`
- More readable and concise
- Consistent with isinstance() syntax

**Example:**
```python
# Before (error - old Union syntax)
from typing import Union, Optional

def parse(value: Union[str, int, float]) -> Optional[dict]:
    pass

# After (fixed - | syntax, Python 3.10+)
def parse(value: str | int | float) -> dict | None:
    pass
```

---

#### `UP032` - f-string

**Category:** Best Practice (Performance)

**Why:** Consistency with TypeScript template literals. F-strings are:
- More readable than `.format()` or `%` formatting
- Faster (evaluated at compile time)
- Less error-prone (variables visible in string)
- PEP 498 recommended approach

**Example:**
```python
# Before (error - .format())
name = "Alice"
age = 30
message = "Hello, {name}. You are {age} years old.".format(name=name, age=age)

# After (fixed - f-string)
message = f"Hello, {name}. You are {age} years old."

# Before (error - % formatting)
message = "Hello, %s. You are %d years old." % (name, age)

# After (fixed - f-string)
message = f"Hello, {name}. You are {age} years old."
```

---

#### `B007` - unused-loop-control-variable

**Category:** Code Quality

**Why:** Consistency with TypeScript `no-unused-vars`. If loop variable is unused:
- Should use `_` to signal intentional discard
- Or indicates potential logic error
- Improves code clarity

**Example:**
```python
# Before (error)
for i in range(10):  # 'i' never used
    process_data()

# After (fixed - use underscore)
for _ in range(10):
    process_data()

# Before (error - destructuring)
for user, role in user_roles:  # 'role' never used
    print(user.name)

# After (fixed - use underscore)
for user, _ in user_roles:
    print(user.name)
```

---

#### `SIM115` - open-file-with-context-handler

**Category:** Bug Prevention (Resource Management)

**Why:** Files must be properly closed to prevent resource leaks:
- `with` statement ensures file is closed even if exception occurs
- Manual `.close()` often forgotten or unreachable due to exceptions
- Resource leaks cause "too many open files" errors
- Best practice for all file operations

**Example:**
```python
# Before (error - file might not be closed)
f = open('data.txt')
data = f.read()
f.close()  # Never called if read() raises exception!

# After (fixed - with statement)
with open('data.txt') as f:
    data = f.read()
# File automatically closed, even if exception occurs

# Multiple files
with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
    f_out.write(f_in.read())
# Both files properly closed
```

---

### Disabled Rules (Formatting)

These rules are disabled because they're handled by `ruff format` or are purely stylistic.

---

#### `E501` - line-too-long

**Category:** Style/Formatting

**Why disabled:**
- Already in ignore list
- Handled by `ruff format` or `black`
- Formatters have smarter line breaking logic
- Some lines (URLs, long strings) legitimately exceed limits

**Note:** Line length still enforced by formatter, just not as error.

---

#### `E1xx`, `E2xx`, `E3xx` - Whitespace and Indentation

**Category:** Style/Formatting

**Why disabled:** All pycodestyle whitespace rules removed:
- `E111-E117` - Indentation (handled by formatter)
- `E201-E275` - Whitespace (handled by formatter)
- `E301-E306` - Blank lines (handled by formatter)

These are purely cosmetic and `ruff format` handles them automatically.

---

#### `E401` - multiple-imports-on-one-line

**Category:** Style/Formatting

**Why disabled:**
- Import formatting handled by isort (I rules)
- Isort has smarter import grouping and sorting
- Formatter ensures consistency

**Note:** Import sorting still enforced, just not by E401.

---

#### `E701` - multiple-statements-on-one-line-colon

**Category:** Style/Formatting

**Why disabled:**
- Handled by `ruff format`
- Formatter automatically splits onto multiple lines
- Purely cosmetic with no safety impact

---

#### `W191`, `W291-W293` - Tab and Trailing Whitespace

**Category:** Style/Formatting

**Why disabled:**
- Handled by `ruff format`
- Formatter ensures consistent whitespace
- Trailing whitespace automatically removed

---

#### `I001` - unsorted-imports

**Category:** Style/Formatting

**Why disabled:**
- Handled by isort/ruff format
- Import order is purely organizational
- Formatter ensures consistency

**Note:** Import organization still enforced by tooling, just not as lint error.

---

#### `UP034` - extraneous-parentheses

**Category:** Style/Formatting

**Why disabled:**
- Handled by `ruff format`
- Parenthesis style is cosmetic
- Sometimes extra parentheses improve readability

---

#### `UP039` - unnecessary-class-parentheses

**Category:** Style/Formatting

**Why disabled:**
- Empty parentheses after `class` definition are cosmetic
- No runtime impact
- Some style guides prefer them for consistency

---

#### `SIM300` - yoda-conditions

**Category:** Style/Formatting

**Why disabled:**
- Constant-first comparisons (`if 42 == x`) are style preference
- No safety impact in Python (unlike C where `=` vs `==` matters)
- Some developers prefer Yoda conditions for consistency
- Not worth enforcing as error

---

### Rules Kept as Warning

These rules are kept as warnings to allow case-by-case judgment.

---

#### `W505` - doc-line-too-long

**Category:** Documentation

**Why warning:**
- Doc line length affects readability
- But legitimate exceptions exist:
  - Long URLs in docstrings
  - Code examples that shouldn't be wrapped
  - Tables or formatted text
- Warning allows judgment call

**How to fix:**
- Break long lines where reasonable
- For URLs, consider using link references
- For code examples, keep if wrapping hurts clarity

---

#### `SIM105` - use-contextlib-suppress

**Category:** Code Quality

**Why warning:**
- `contextlib.suppress` is concise but less explicit than try/except
- Some teams prefer explicit try/except for clarity
- Warning allows judgment on readability trade-off

**Example:**
```python
# Current (explicit try/except)
try:
    os.remove(temp_file)
except FileNotFoundError:
    pass

# Alternative (contextlib.suppress)
from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove(temp_file)

# Both are valid - choose based on team preference
```

---

#### `SIM112` - uncapitalized-environment-variables

**Category:** Code Quality

**Why warning:**
- Environment variables typically uppercase by convention
- But some APIs use lowercase (e.g., `PORT`, `npm_*`)
- Warning catches mistakes while allowing legitimate exceptions

---

#### `SIM116` - if-else-block-instead-of-dict-lookup

**Category:** Performance

**Why warning:**
- Dict lookup often cleaner than if/elif chain
- But sometimes if/elif is more readable
- Performance difference usually negligible
- Warning suggests optimization without forcing it

---

## Summary

### Python/Ruff Rules
- **Selected categories:** E, W, F, I, UP, B, C4, SIM (195+ rules)
- **All selected rules:** Error level (strict enforcement)
- **Disabled rules:** 40+ formatting rules (handled by ruff format)
- **Warning-level rules:** 4 rules requiring case-by-case judgment
- **Philosophy:** Consistency with TypeScript rules (unused vars, modern syntax, bug prevention)

### Consistency with TypeScript/ESLint
- **Unused code:** F401 (unused imports) ↔ no-unused-vars
- **Modern syntax:** UP006/UP007 (PEP 585/604) ↔ template literals
- **Error handling:** E722 (bare except) ↔ no-floating-promises
- **Formatting:** Disabled style rules ↔ Prettier handles formatting
- **Philosophy:** Error for bugs/quality, disable for style

---

## Related Documentation

- Ruff Configuration: `/libs/shared/types/pyproject.toml`
- Ruff Rules Reference: https://docs.astral.sh/ruff/rules/
- ESLint Configuration: `/.eslintrc.js`
- TypeScript Configuration: `/tsconfig.base.json`
- Code Review Guidelines: `/docs/CODE_REVIEW.md`
- Contributing Guide: `/docs/CONTRIBUTING.md`
>>>>>>> lint-cleanup-initiative
