Debugging

From alxyrgin/secondbrain_ai · View interactive version

Debugging is an AI agent skill from the GitHub repository alxyrgin/secondbrain_ai. 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.

How to use this skill

Skill file

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

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

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

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

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

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

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

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

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

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

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

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

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

## 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:


Шаг 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
💾 State Issues
🔄 Async Problems
📊 Data Issues
🔌 Integration Issues

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

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

### 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:**

async function processPayment(data) {

+

const result = await api.charge(data);

return result;

}


**Testing the fix:**
- [x] Unit test проходит
- [x] Integration test проходит
- [x] Manually tested — работает

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

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

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

Validation
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 для любого бага


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
  1. Use version control
  1. Write tests first
  1. Document findings

DON'T ❌

  1. Don't guess randomly
  1. Don't fix symptoms
  1. Don't skip tests
  1. Don't leave debug code

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

Общий debugging:

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

С ошибкой:

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

Performance:

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

Поведение:

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


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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.