Debugging Detective
The Debugging Detective agent specializes in finding and fixing bugs, analyzing errors, and troubleshooting issues.
Expertise Areas#
- Error Analysis - Stack traces, error messages, logs
- Root Cause Analysis - Finding the source of issues
- Debugging Tools - DevTools, debuggers, profilers
- Performance Issues - Memory leaks, slow queries
- Integration Bugs - API issues, third-party problems
- Reproduction - Creating minimal test cases
- Fix Strategies - Patches, workarounds, proper fixes
Usage Examples#
Error Analysis#
Use the debugging-detective agent to analyze this error:
TypeError: Cannot read properties of undefined (reading 'map')
at UserList (UserList.tsx:15:23)
Response includes:
- Error explanation
- Likely causes
- Code investigation points
- Fix recommendations
Performance Investigation#
Use the debugging-detective agent to investigate why our API is slow.
Response includes:
- Investigation steps
- Profiling recommendations
- Common causes
- Optimization suggestions
Bug Hunting#
Use the debugging-detective agent to find why user sessions are randomly expiring.
Response includes:
- Systematic investigation plan
- Likely causes
- Logging recommendations
- Verification steps
Debugging Process#
1. Understand the Problem#
Questions to answer:
- What is the expected behavior?
- What is the actual behavior?
- When did it start happening?
- Is it reproducible?
- What changed recently?
2. Gather Evidence#
Evidence sources:
- Error messages and stack traces
- Application logs
- Network requests/responses
- Database queries
- User reports
- Git history
3. Form Hypotheses#
Based on evidence, list possible causes:
1. Most likely: [hypothesis]
2. Second likely: [hypothesis]
3. Less likely but possible: [hypothesis]
4. Test Hypotheses#
For each hypothesis:
1. Create a test case
2. Add logging/debugging
3. Reproduce the issue
4. Verify the cause
5. Fix and Verify#
Fix approach:
1. Implement the fix
2. Write regression test
3. Test the fix
4. Review for side effects
5. Deploy and monitor
Common Bug Patterns#
Null/Undefined Errors#
1// Problem
2const name = user.profile.name; // user.profile is undefined
3
4// Fix 1: Optional chaining
5const name = user?.profile?.name;
6
7// Fix 2: Default values
8const name = user?.profile?.name ?? 'Unknown';
9
10// Fix 3: Guard clause
11if (!user?.profile) {
12 throw new Error('User profile not loaded');
13}
14const name = user.profile.name;Race Conditions#
1// Problem: State update after unmount
2useEffect(() => {
3 fetchData().then(setData); // Component might unmount
4}, []);
5
6// Fix: Cleanup function
7useEffect(() => {
8 let cancelled = false;
9
10 fetchData().then(data => {
11 if (!cancelled) setData(data);
12 });
13
14 return () => { cancelled = true; };
15}, []);Memory Leaks#
1// Problem: Event listener not cleaned up
2useEffect(() => {
3 window.addEventListener('resize', handleResize);
4}, []); // Missing cleanup!
5
6// Fix: Return cleanup function
7useEffect(() => {
8 window.addEventListener('resize', handleResize);
9 return () => window.removeEventListener('resize', handleResize);
10}, []);Async/Await Errors#
1// Problem: Unhandled promise rejection
2async function fetchUser(id: string) {
3 const response = await fetch(`/api/users/${id}`);
4 return response.json(); // What if response is not OK?
5}
6
7// Fix: Proper error handling
8async function fetchUser(id: string) {
9 const response = await fetch(`/api/users/${id}`);
10
11 if (!response.ok) {
12 throw new Error(`Failed to fetch user: ${response.status}`);
13 }
14
15 return response.json();
16}Debugging Tools#
Browser DevTools#
1// Console methods
2console.log('Basic log');
3console.table(arrayOfObjects);
4console.time('operation');
5// ... operation
6console.timeEnd('operation');
7console.trace('Call stack');
8
9// Debugger statement
10function problematicFunction() {
11 debugger; // Execution pauses here
12 // ... code to debug
13}Node.js Debugging#
1# Inspect mode
2node --inspect app.js
3
4# Break on first line
5node --inspect-brk app.js
6
7# Debug tests
8node --inspect-brk node_modules/.bin/jest --runInBandNetwork Debugging#
1// Log all fetch requests
2const originalFetch = window.fetch;
3window.fetch = async (...args) => {
4 console.log('Fetch:', args);
5 const response = await originalFetch(...args);
6 console.log('Response:', response.status);
7 return response;
8};Logging Strategies#
Structured Logging#
1import pino from 'pino';
2
3const logger = pino({
4 level: process.env.LOG_LEVEL || 'info',
5});
6
7// Good logging
8logger.info({ userId, action: 'login' }, 'User logged in');
9logger.error({ err, userId, endpoint }, 'API request failed');
10
11// Include context
12logger.child({ requestId, userId }).info('Processing request');Debug Points#
1// Strategic logging points
2async function processOrder(order: Order) {
3 logger.info({ orderId: order.id }, 'Starting order processing');
4
5 try {
6 const validated = await validateOrder(order);
7 logger.debug({ orderId: order.id }, 'Order validated');
8
9 const payment = await processPayment(validated);
10 logger.debug({ orderId: order.id, paymentId: payment.id }, 'Payment processed');
11
12 const result = await fulfillOrder(validated, payment);
13 logger.info({ orderId: order.id }, 'Order completed');
14
15 return result;
16 } catch (error) {
17 logger.error({ err: error, orderId: order.id }, 'Order processing failed');
18 throw error;
19 }
20}Sample Prompts#
| Task | Prompt |
|---|---|
| Error analysis | "Why am I getting 'Maximum update depth exceeded'?" |
| Performance | "Debug why this component re-renders constantly" |
| Async issues | "Find the race condition in this checkout flow" |
| Memory leak | "Investigate memory growth in this long-running process" |
| Integration | "Debug why webhook payloads are malformed" |
Configuration#
1// bootspring.config.js
2module.exports = {
3 agents: {
4 customInstructions: {
5 'debugging-detective': `
6 - Ask clarifying questions
7 - Start with the most likely cause
8 - Suggest adding strategic logging
9 - Consider edge cases
10 - Recommend regression tests
11 `,
12 },
13 },
14};Related Agents#
- Testing Expert - Regression tests
- Performance Expert - Performance issues
- Backend Expert - Server-side debugging