agentleFS
alxyrginalxyrgin/secondbrain_ai/.claude/skills-dev/debugging/SKILL.md

debugging

Skill17 starsChanged 9 months agoMITView on GitHub

Structured debugging methodology for systematic problem-solving. Use when user asks to "отладь", "найди баг", "почему не работает", "debug this", "fix bug", "why is this failing", or when code has errors, unexpected behavior, or needs troubleshooting.

Files
SKILL.md

Debugging Skill — структурированная отладка

Систематический подход к поиску и устранению багов через воспроизведение, анализ и проверку гипотез.

Когда использовать

  • Код не работает как ожидается
  • Есть ошибка или exception
  • Непредсказуемое поведение
  • Performance проблемы
  • Регрессия после изменений

Методология Debugging

Debugging следует научному методу:

  1. Reproduce — воспроизвести проблему
  2. Isolate — локализовать источник
  3. Hypothesize — сформулировать гипотезы
  4. Test — проверить гипотезы
  5. Fix — исправить и проверить
  6. Prevent — предотвратить повторение

Шаг 1: Reproduce (Воспроизведение)

Цель: Получить стабильное воспроизведение бага

Что нужно выяснить

✅ Когда проявляется?

  • При каких действиях?
  • В какой среде (dev/staging/prod)?
  • На каких данных?
  • Всегда или иногда?

✅ Как проявляется?

  • Что именно идёт не так?
  • Какая ошибка выдаётся?
  • Что ожидалось vs что получили?

✅ Можно ли воспроизвести?

  • Шаги для воспроизведения
  • Minimal reproducible example
  • Условия окружения

Процесс воспроизведения

## Reproduction Steps

1. [Шаг 1]
2. [Шаг 2]
3. [Шаг 3]

**Expected:** [Что должно произойти]
**Actual:** [Что происходит]

**Environment:**
- OS: [macOS/Linux/Windows]
- Version: [версия приложения]
- Dependencies: [ключевые зависимости]

**Error message:**

[Точный текст ошибки]


**Frequency:** [Always / Sometimes / Rare]

Если не воспроизводится

🔍 Debugging the bug:

  • Проверь логи — есть ли дополнительная информация?
  • Спроси у пользователя точные шаги
  • Проверь различия в окружениях
  • Race condition или timing issue?

Шаг 2: Isolate (Локализация)

Цель: Сузить область поиска проблемы

Техники локализации

Binary Search (Деление пополам)

Убирай части кода пока проблема не исчезнет:

[Весь код] → баг есть
[Первая половина] → баг есть?
  Да → проблема здесь
  Нет → проблема во второй половине

Git Bisect (Поиск коммита)

Если раньше работало:

git bisect start
git bisect bad           # Текущий коммит — плохой
git bisect good <hash>   # Последний хороший коммит
# Git автоматически найдёт проблемный коммит

Isolation через тесты

Создай минимальный тест который показывает проблему:

// ❌ Так проявляется баг
test('minimal reproduction', () => {
  const result = buggyFunction(input);
  expect(result).toBe(expected); // Fails
});

Вопросы для локализации

  • В каком файле проблема?
  • В какой функции?
  • На какой строке возникает ошибка?
  • Какие данные вызывают проблему?
  • Что было изменено недавно?

Вывод локализации:

## Isolation

**Проблема локализована:**
- Файл: `src/services/payment.ts`
- Функция: `processPayment()`
- Строка: 67
- Условие: Происходит когда `amount > 1000`

**Stack trace:**

Error: Payment processing failed at processPayment (payment.ts:67) at handleCheckout (checkout.ts:42) at onClick (Button.tsx:15)


Шаг 3: Hypothesize (Гипотезы)

Цель: Сформулировать возможные причины

Типичные категории багов

🧮 Logic Errors

  • Off-by-one ошибки
  • Неправильные условия (if/else)
  • Неверная математика
  • Edge cases не обработаны

💾 State Issues

  • Race conditions
  • Stale state
  • Uninitialized variables
  • Memory leaks

🔄 Async Problems

  • Promise not awaited
  • Callback hell
  • Race conditions
  • Timing issues

📊 Data Issues

  • Null/undefined не проверены
  • Неверный тип данных
  • Проблемы сериализации
  • Кодировка (encoding)

🔌 Integration Issues

  • API изменился
  • Network timeout
  • Dependency версия
  • Environment variables

Формулирование гипотез

Для каждой гипотезы:

### Hypothesis #1: [Название]

**Причина:**
[Что могло вызвать проблему]

**Как проверить:**
[Как подтвердить или опровергнуть]

**Likelihood:** [High / Medium / Low]

Пример:

### Hypothesis #1: Race condition в async операции

**Причина:**
Функция `updateUser` вызывается дважды параллельно,
вторая перезаписывает результат первой

**Как проверить:**
1. Добавить логи до и после `await updateUser()`
2. Проверить что функция выполняется синхронно
3. Добавить debounce/throttle

**Likelihood:** High (90%)

Шаг 4: Test (Проверка гипотез)

Цель: Подтвердить или опровергнуть каждую гипотезу

Методы проверки

Logging & Debugging

// Добавить логи для отслеживания
console.log('[DEBUG] Input:', input);
console.log('[DEBUG] State before:', state);
console.log('[DEBUG] Result:', result);

// Или использовать debugger
debugger; // Pause execution here

Assertions

// Проверить предположения
console.assert(user !== null, 'User should not be null');
console.assert(amount > 0, 'Amount should be positive');

Experiments

Измени код чтобы проверить теорию:

// Hypothesis: проблема в async
// Experiment: сделать синхронным
const result = await processPayment(data);
// vs
const result = processPaymentSync(data);

Tests

Напиши тест который проверяет гипотезу:

test('race condition when called twice', async () => {
  const promise1 = updateUser(userId, data1);
  const promise2 = updateUser(userId, data2);

  const results = await Promise.all([promise1, promise2]);

  // Should not lose updates
  expect(results).toContainBoth(data1, data2);
});

Проверка гипотез по порядку

Начни с наиболее вероятной (High likelihood):

## Testing Hypotheses

### ✅ Hypothesis #1: CONFIRMED
- Added logs → второй вызов перезаписывает первый
- Timing показывает overlap в выполнении
- **Root cause found!**

### ⏸️ Hypothesis #2: NOT TESTED
- Не нужно — уже нашли причину

### ❌ Hypothesis #3: REJECTED
- Добавил проверку на null → ошибка осталась

Шаг 5: Fix (Исправление)

Цель: Устранить root cause, не симптомы

Принципы исправления

1. Fix the cause, not the symptom

// ❌ Fixing symptom
if (result === undefined) {
  result = defaultValue; // Маскирует проблему
}

// ✅ Fixing cause
const result = await calculateResult(data);
// Теперь result всегда определён

2. Minimal change

// ❌ Слишком большое изменение
// Переписал всю функцию

// ✅ Минимальное исправление
// Добавил одну строку с await
const result = await asyncOperation();

3. Make it obvious

// ❌ Неочевидное исправление
const x = data?.value || 0;

// ✅ Очевидное исправление
// Prevent race condition by locking
if (isProcessing) return;
isProcessing = true;
try {
  await processPayment(data);
} finally {
  isProcessing = false;
}

Процесс исправления

## Fix Implementation

**Root Cause:**
Race condition — функция вызывается параллельно

**Solution:**
Добавить механизм блокировки (mutex/semaphore)

**Changes:**
```diff
+ let isProcessing = false;

  async function processPayment(data) {
+   if (isProcessing) {
+     throw new Error('Payment already processing');
+   }
+
+   isProcessing = true;
+   try {
      const result = await api.charge(data);
      return result;
+   } finally {
+     isProcessing = false;
+   }
  }

Testing the fix:

  • Unit test проходит
  • Integration test проходит
  • Manually tested — работает

---

## Шаг 6: Prevent (Предотвращение)

**Цель:** Избежать повторения проблемы

### Добавить защиту

#### Validation

```javascript
function processPayment(amount, user) {
  // Add validation to prevent invalid input
  if (!user) throw new Error('User is required');
  if (amount <= 0) throw new Error('Amount must be positive');
  if (amount > MAX_AMOUNT) throw new Error('Amount too large');

  // ... process payment
}

Tests

// Regression test
test('should not allow concurrent payment processing', async () => {
  const promise1 = processPayment(data);
  const promise2 = processPayment(data);

  await expect(promise2).rejects.toThrow('already processing');
});

// Edge case tests
test('should handle zero amount', () => {
  expect(() => processPayment(0, user)).toThrow();
});

Documentation

/**
 * Process payment for user
 *
 * @throws {Error} If payment is already processing (prevents race condition)
 * @throws {Error} If amount is invalid
 *
 * NOTE: This function uses a lock to prevent concurrent execution.
 *       Do not call multiple times in parallel.
 */
async function processPayment(data) {
  // ...
}

Monitoring

// Add logging for debugging future issues
logger.info('Payment processing started', {
  userId,
  amount,
  timestamp: Date.now()
});

try {
  const result = await processPayment(data);
  logger.info('Payment processed successfully', { result });
} catch (error) {
  logger.error('Payment processing failed', { error, data });
  throw error;
}

Debugging Checklist

Quick Checklist для любого бага

  • Воспроизведение: Могу стабильно воспроизвести?
  • Локализация: Знаю где проблема (файл:строка)?
  • Stack trace: Изучил полный stack trace?
  • Логи: Проверил логи приложения?
  • Данные: Какие данные вызывают проблему?
  • Окружение: Проверил версии зависимостей?
  • История: Когда последний раз работало?
  • Гипотезы: Есть 2-3 теории о причине?
  • Тестирование: Проверил гипотезы?
  • Root cause: Нашёл настоящую причину?
  • Fix: Исправил минимально и очевидно?
  • Tests: Добавил regression test?
  • Prevention: Добавил защиту от повтора?

Debugging Tools

Логирование

// Structured logging
const debug = require('debug')('app:payment');

debug('Processing payment', { userId, amount });
debug('API response', { status, data });

Breakpoints

// Chrome DevTools / VS Code
debugger; // Pause здесь

// Conditional breakpoint
if (amount > 1000) {
  debugger; // Только для больших сумм
}

Assertions

const assert = require('assert');

assert(user !== null, 'User should exist');
assert(amount > 0, 'Amount should be positive');

Stack trace

console.trace('How did we get here?');

// Или
const stack = new Error().stack;
console.log(stack);

Network debugging

# Проверить API запросы
curl -v https://api.example.com/endpoint

# Проверить DNS
nslookup api.example.com

# Проверить connectivity
ping api.example.com

Common Bug Patterns

1. Off-by-one

// ❌ Bug
for (let i = 0; i <= array.length; i++) {
  // Вылетит на последней итерации
}

// ✅ Fix
for (let i = 0; i < array.length; i++) {
  // Корректно
}

2. Async не awaited

// ❌ Bug
async function loadData() {
  const data = fetchData(); // Forgot await
  console.log(data); // Promise, not data!
}

// ✅ Fix
async function loadData() {
  const data = await fetchData();
  console.log(data); // Actual data
}

3. Mutating state

// ❌ Bug
function addItem(array, item) {
  array.push(item); // Mutates original
  return array;
}

// ✅ Fix
function addItem(array, item) {
  return [...array, item]; // Immutable
}

4. Null/undefined не проверены

// ❌ Bug
function getName(user) {
  return user.name.toUpperCase();
  // Crashes if user is null
}

// ✅ Fix
function getName(user) {
  return user?.name?.toUpperCase() ?? 'Unknown';
}

5. Race condition

// ❌ Bug
let count = 0;
async function increment() {
  const current = count;
  await delay(100);
  count = current + 1; // Lost updates!
}

// ✅ Fix
let count = 0;
const lock = new AsyncLock();
async function increment() {
  await lock.acquire('count', async () => {
    count = count + 1;
  });
}

Best Practices

DO ✅

  1. Read error messages carefully
    • Полный текст ошибки
    • Stack trace до конца
    • Warnings тоже важны
  2. Use version control
    • git bisect для поиска коммита
    • git diff для изменений
    • git blame для истории
  3. Write tests first
    • Failing test = reproduction
    • Passing test = fix confirmed
  4. Document findings
    • Причина бага
    • Решение
    • Почему именно так

DON'T ❌

  1. Don't guess randomly
    • Не меняй код наугад
    • Сформулируй гипотезу сначала
  2. Don't fix symptoms
    • Найди root cause
    • Исправь источник
  3. Don't skip tests
    • Regression test обязателен
    • Иначе баг вернётся
  4. Don't leave debug code
    • Убери console.log
    • Убери debugger
    • Убери commented code

Шаблоны запросов

Общий debugging:

Отладь этот код, он не работает как ожидалось

С ошибкой:

Почему возникает ошибка "Cannot read property 'name' of undefined"?

Performance:

Найди почему эта функция работает медленно

Поведение:

Почему кнопка не срабатывает при клике?


Интеграция с другими skills

  • Перед debugging → используй research для понимания кода
  • После debugging → используй code-review для проверки fix
  • Если баг сложный → используй refactoring для улучшения структуры
  • Результаты debugging → документируй в комментариях или Todoist

Download now (ZIP)

  • Other versions106 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 106

    1. tursodatabase/turso★ 25ksame name
    2. JetBrains/intellij-community★ 21ksame name
    3. DetachHead/rebased★ 6ksame name
    4. mrgoonie/claudekit-skills★ 2.2ksame name
    5. JetBrains/MPS★ 1.7ksame name
    6. glommer/pgmicro★ 1.2ksame name
    7. karrioapi/karrio★ 799same name
    8. rapidaai/voice-ai★ 746same name
    9. i-am-manware/Manware-s-AI-Learning-Toolkit★ 717same name
    10. vchelaru/Gum★ 634same name

    96 more not listed

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • Used alongsideProjects with it also use Problem-Solving Techniques, media-processing and 10 more.

    Other files people use alongside this one.

    Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
    • truongtv22Skill

      Problem-Solving Techniques

      Apply systematic problem-solving techniques for complexity spirals (simplification cascades), innovation blocks (collision-zone thinking), recurring patterns (meta-pattern recognition), assumption constraints (inversion exercise), scale uncertainty (scale game), and dispatch when stuck. Techniques derived from Microsoft Amplifier project patterns adapted for immediate application.

      Also in 4 projects that use this

    • mrgoonieSkill

      media-processing

      Process multimedia files with FFmpeg (video/audio encoding, conversion, streaming, filtering, hardware acceleration) and ImageMagick (image manipulation, format conversion, batch processing, effects, composition). Use when converting media formats, encoding videos with specific codecs (H.264, H.265, VP9), resizing/cropping images, extracting audio from video, applying filters and effects, optimizing file sizes, creating streaming manifests (HLS/DASH), generating thumbnails, batch processing images, creating composite images, or implementing media processing pipelines. Supports 100+ formats, hardware acceleration (NVENC, QSV), and complex filtergraphs.

      Also in 6 projects that use this

    • JetBrainsSkill

      ssr

      Guide for using Structural Search and Replace in IntelliJ. Use when creating or modifying SSR inspections or search patterns.

      Also in 3 projects that use this

    • mrgoonieSkill

      web-frameworks

      Build modern full-stack web applications with Next.js (App Router, Server Components, RSC, PPR, SSR, SSG, ISR), Turborepo (monorepo management, task pipelines, remote caching, parallel execution), and RemixIcon (3100+ SVG icons in outlined/filled styles). Use when creating React applications, implementing server-side rendering, setting up monorepos with multiple packages, optimizing build performance and caching strategies, adding icon libraries, managing shared dependencies, or working with TypeScript full-stack projects.

      Also in 6 projects that use this

    • DevNewbie1826Skill

      programming

      MUST USE for work on Python, Rust, TypeScript, or Go source files and project manifests. Triggers: write or edit code; new project; Go HTTP service (gin lane); Bubble Tea TUI; CJK IME; Connect-Go RPC; sqlc or pgx; branded IDs; exhaustive matching; unsafe Rust; Miri; oversized file; refactoring; logging, log levels, structured logging, or observability; arena, allocator, bumpalo, const fn, const generics, compile-time programming, zero-allocation APIs, bitfields, repr, scope guards, errdefer-style cleanup, Zig-like patterns, zero-copy parsing, packed data, or FFI; Rust public API design or macros.

      Also in 3 projects that use this

    • +7 more from mrgoonie
  • In this repository18 other files it gives its agents.

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

Reviews can't be read right now.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.