
Oma Debug
- 127 installs
- 41 repo stars
- Updated August 4, 2026
- gracefullight/stock-checker
Diagnose failing stock-checker tests, runtime exceptions, and financial API faults using reproduce-minimize-hypothesize-fix loops with regression coverage.
About
Oma-debug skill applies a disciplined diagnosis loop for stock-checker bugs: reproduce failures, minimize cases, hypothesize causes, instrument code, implement fixes, and add regression tests so agents resolve errors without guesswork.
- Failure reproduction
- Minimal repro cases
- Targeted instrumentation
- Root-cause fixes
- Regression tests
Oma Debug by the numbers
- 127 all-time installs (skills.sh)
- Ranked #223 of 596 Debugging skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/gracefullight/stock-checker --skill oma-debugAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 127 |
|---|---|
| repo stars | ★ 41 |
| Last updated | August 4, 2026 |
| Repository | gracefullight/stock-checker ↗ |
What it does
Diagnose failing stock-checker tests, runtime exceptions, and financial API faults using reproduce-minimize-hypothesize-fix loops with regression coverage.
Files
Debug Agent - Bug Fixing Specialist
Scheduling
Goal
Reproduce, diagnose, minimally fix, and regression-test bugs while preserving scope discipline and documenting root cause.
Intent signature
- User reports a bug, crash, traceback, exception, error message, performance issue, intermittent failure, or regression.
- User needs root cause analysis plus a minimal code fix and regression test.
When to use
- User reports a bug with error messages
- Something is broken and needs fixing
- Performance issues or slowdowns
- Intermittent failures or race conditions
- Regression bugs
When NOT to use
- Building new features -> use Frontend/Backend/Mobile agents
- General code review -> use QA Agent
Expected inputs
- Error message, failing behavior, reproduction steps, logs, test failure, or affected code path
- Existing tests, stack traces, environment notes, and suspected regression boundary
Expected outputs
- Root cause explanation
- Minimal fix scoped to the failing behavior
- Regression test or explicit reason it cannot be added
- Bug documentation under
.agents/results/bugs/when appropriate
Dependencies
resources/execution-protocol.md, examples, checklist, common patterns, and debugging checklist- Local codebase search and symbol/reference tools
- Project test, lint, typecheck, and runtime commands
Control-flow features
- Branches by reproduction success, error class, suspected layer, and verification outcome
- Reads logs/code/tests and writes code/tests/docs
- Must search for similar patterns after fixing
Structural Flow
Entry
1. Capture the reported symptom and suspected scope. 2. Reproduce or establish the closest reliable failing signal. 3. Identify affected files, tests, and related patterns.
Scenes
1. PREPARE: Gather symptoms, logs, reproduction path, and verification command. 2. ACQUIRE: Read failing code, tests, references, and similar patterns. 3. REASON: Isolate root cause and reject unsupported hypotheses. 4. ACT: Apply minimal fix and regression test. 5. VERIFY: Re-run failing and related checks. 6. FINALIZE: Document root cause, fix, test, and residual risk.
Transitions
- If reproduction fails, use logs/tests to establish a weaker but explicit diagnostic signal.
- If the first fix fails verification, return to root-cause analysis.
- If similar patterns exist, inspect and patch only affected cases.
- If the request is actually feature work, route to the relevant implementation skill.
Failure and recovery
- If environment is missing, document the blocker and provide the closest static diagnosis.
- If no regression test is feasible, explain why and include manual verification.
- If fix scope grows, stop and call out the broader design issue.
Exit
- Success: bug is fixed, regression coverage exists, and checks pass.
- Partial success: root cause or verification blocker is explicit.
Logical Operations
Actions
| Action | SSL primitive | Evidence |
|---|---|---|
| Reproduce failure | CALL_TOOL | Test/runtime/log command |
| Search affected code | READ | Code, tests, symbols, references |
| Compare similar patterns | COMPARE | Pattern search |
| Infer root cause | INFER | Diagnostic reasoning |
| Write minimal fix | WRITE | Code patch |
| Write regression test | WRITE | Test patch |
| Verify behavior | VALIDATE | Tests/checks |
| Report result | NOTIFY | Root-cause summary |
Tools and instruments
- Project test, lint, typecheck, runtime, and logging commands
- Serena MCP symbol/reference/pattern search when available
- Debugging checklist and bug report template
Canonical workflow path
rg "<error-message-or-symbol>"
rg --filesThen run the smallest reproduction command first, add a regression test, and re-run the failing check plus related tests.
Resource scope
| Scope | Resource target |
|---|---|
CODEBASE | Failing source, tests, and related patterns |
LOCAL_FS | Bug reports and result artifacts |
PROCESS | Reproduction and verification commands |
MEMORY | Hypotheses, root-cause notes, verification evidence |
Preconditions
- A bug signal, symptom, or failing behavior is available.
- Relevant code and verification path can be inspected or the blocker is stated.
Effects and side effects
- Mutates source/tests only as needed for the fix.
- May create bug documentation under
.agents/results/bugs/.
Guardrails
1. Reproduce first, then diagnose - never guess at fixes 2. Identify root cause, not just symptoms 3. Minimal fix: change only what's necessary 4. Every fix gets a regression test 5. Search for similar patterns elsewhere after fixing 6. Document in .agents/results/bugs/
Serena MCP
find_symbol("functionName"): Locate the functionfind_referencing_symbols("Component"): Find all usagessearch_for_pattern("error pattern"): Find similar issues
References
Follow resources/execution-protocol.md step by step. See resources/examples.md for input/output examples. Before submitting, run resources/checklist.md. Vendor-specific execution protocols are injected automatically by oma agent:spawn. Source files live under ../_shared/runtime/execution-protocols/{vendor}.md.
- Execution steps:
resources/execution-protocol.md - Code examples:
resources/examples.md - Checklist:
resources/checklist.md - Error recovery:
resources/error-playbook.md - Bug report template:
resources/bug-report-template.md - Common patterns:
resources/common-patterns.md - Debugging checklist:
resources/debugging-checklist.md - Context loading:
../_shared/core/context-loading.md - Reasoning templates:
../_shared/core/reasoning-templates.md - Context budget:
../_shared/core/context-budget.md - Lessons learned:
../_shared/core/lessons-learned.md - Observability handoff:
../oma-observability/SKILL.md§Integrations — traces/logs bytrace_id, 6-dim forensics
Bug Report Template
Use this template when documenting bugs in the Knowledge Base.
Save to: .agents/results/bugs/bug-YYYYMMDD-[short-description].md
---
Bug: [Short Descriptive Title]
Date Reported: YYYY-MM-DD Date Fixed: YYYY-MM-DD (or "In Progress") Reporter: [User name or issue number] Assignee: [Agent that fixed it] Severity: CRITICAL | HIGH | MEDIUM | LOW Status: OPEN | IN PROGRESS | FIXED | ON HOLD | WON'T FIX
---
Problem Description
What happened? [Clear description of the bug from user's perspective]
What was expected? [What should have happened instead]
Impact:
- Users affected: [All | Specific role | Percentage]
- Business impact: [Revenue loss | User frustration | Security risk]
- Workaround available: [Yes/No - describe if yes]
---
Reproduction Steps
1. Navigate to [page/route] 2. Click on [button/element] 3. Enter [data] in [field] 4. Observe [unexpected behavior]
Frequency:
- [ ] Every time (100%)
- [ ] Intermittent (specify pattern: ___%)
- [ ] Specific conditions only (describe: ___)
---
Evidence
Error Messages:
[Exact error text from console/logs]Stack Trace:
[Full stack trace if available]Screenshots:
- Before: [description or file path]
- After: [description or file path]
- Error state: [description or file path]
Browser Console:
// Relevant console errorsNetwork Requests:
Request URL: [URL]
Status Code: [200/404/500/etc]
Response: [relevant response data]---
Environment
Frontend:
- Browser: [Chrome 120 | Firefox 121 | Safari 17]
- OS: [Windows 11 | macOS 14 | iOS 17 | Android 14]
- Screen size: [Desktop | Tablet | Mobile]
- Browser extensions: [Any relevant extensions]
Backend:
- Environment: [Development | Staging | Production]
- Server version: [API version]
- Database: [PostgreSQL 16.1]
Mobile (if applicable):
- Device: [iPhone 15 | Samsung Galaxy S24]
- OS Version: [iOS 17.2 | Android 14]
- App Version: [1.2.3]
---
Investigation
Initial Analysis
Hypothesis: [What you think is causing the bug]
Investigation Steps Taken: 1. [What was checked] 2. [What was ruled out] 3. [Key findings]
Root Cause
Technical Explanation: [Deep dive into why the bug occurs]
Code Location:
- File:
path/to/file.tsx - Line: 145
- Function:
handleSubmit()
Specific Issue:
// Problem code
const user = data.user.profile.name; // Crashes if profile is undefinedWhy it happens: [Explain the conditions that trigger this]
---
Solution
Fix Applied
Approach: [High-level description of the fix strategy]
Code Changes:
// File: path/to/file.tsx (line 145)
// BEFORE (buggy code)
const user = data.user.profile.name;
// AFTER (fixed code)
const user = data?.user?.profile?.name ?? 'Unknown';Why this works: [Explain the fix]
Files Modified
src/components/UserProfile.tsx- Added null check for profilesrc/lib/api/users.ts- Improved error handlingsrc/components/UserProfile.test.tsx- Added regression test
Migration/Deployment Notes
Database Changes: None | [Describe migrations needed] Configuration Changes: None | [Describe config updates] Breaking Changes: None | [Describe breaking changes] Rollback Plan: [How to revert if needed]
---
Verification
Testing Performed
- [x] Regression test added
- File:
src/components/UserProfile.test.tsx - Coverage: Null profile, undefined user, missing name
- [x] Manual testing
- Tested original reproduction steps
- Tested edge cases (null, undefined, empty)
- Verified fix works in all browsers
- [x] Related areas checked
- Found similar pattern in
TeamProfile.tsx- also fixed - Checked all
.profile.usages - 3 more locations updated
- [x] Performance impact: None | [Describe if any]
Test Results
Unit Tests: 15/15 passing Integration Tests: 8/8 passing E2E Tests: 3/3 passing Manual QA: Verified on Chrome, Firefox, Safari
---
Prevention
How to Avoid Similar Bugs
1. Always check for null/undefined before accessing nested properties 2. Use optional chaining (`?.`) for safe property access 3. Provide default values with nullish coalescing (??) 4. Add TypeScript strict null checks to catch at compile time 5. Write defensive code - assume data might be missing
Code Patterns to Follow
// GOOD: Safe access with fallback
const name = user?.profile?.name ?? 'Anonymous';
// GOOD: Explicit null check
if (user?.profile) {
const name = user.profile.name;
}
// GOOD: Early return
if (!user?.profile) {
return <div>No profile available</div>;
}
// BAD: Unsafe nested access
const name = user.profile.name; // Crashes if profile undefinedRecommended Tools
- TypeScript with
strictNullChecks: true - ESLint rule:
no-unsafe-member-access - Unit tests for edge cases (null, undefined, empty)
---
Related
Similar Bugs:
- Bug #123: Similar null check issue in
CommentList - Bug #456: Related data loading pattern
Dependent Issues:
- Issue #789: Need to improve error handling across all API calls
Documentation:
- [Link to architecture decision record]
- [Link to API documentation]
External References:
- [Stack Overflow link if used]
- [GitHub issue in library if relevant]
---
Metrics
Time to Fix: [2 hours | 1 day | 1 week] Lines Changed: [+15 -5] Files Affected: [3 files] Tests Added: [5 new tests]
---
Communication
Notified:
- [x] Product Manager - Impact assessment
- [x] QA Team - Additional testing needed
- [x] Users affected - Via email/announcement
- [ ] Other teams - [Specify]
Changelog Entry:
### Fixed
- Fixed crash when user profile is missing ([#issue-number])---
Lessons Learned
What went well:
- Quick identification of root cause
- Proactive fix of similar patterns
- Comprehensive test coverage
What could improve:
- Should have caught this in code review
- TypeScript strict mode would have prevented this
- Need better null check linting rules
Action Items:
- [ ] Enable TypeScript strictNullChecks across project
- [ ] Add ESLint rule for unsafe member access
- [ ] Update code review checklist to include null checks
- [ ] Create coding standards doc for defensive programming
---
Tags
frontend null-check crash typescript user-profile high-priority
---
Sign-off: [Your name/agent name] Reviewed by: [PM Agent | QA Agent | Frontend Agent] Approved for deploy: [Yes/No]
---
Template Notes
How to use this template:
1. Copy this template when documenting a new bug 2. Fill in all sections - don't skip parts 3. Be specific - future developers need details 4. Include code - show the before/after 5. Link related issues - help connect patterns 6. Update status as work progresses 7. Save to Knowledge Base for future reference
Sections you can skip:
- Screenshots (if text description is clear)
- Stack trace (if no error thrown)
- Migration notes (if no DB/config changes)
Optional sections to add:
- Timeline (for long-running bugs)
- Cost impact (for business-critical bugs)
- Vendor communication (if third-party bug)
Debug Agent - Self-Verification Checklist
Run through every item before submitting your fix.
Fix Quality
- [ ] Root cause identified (not just symptom patched)
- [ ] Fix is minimal and focused (no unrelated changes)
- [ ] Edge cases handled (null, empty, boundary values)
- [ ] No new bugs introduced
Regression Test
- [ ] Test written that reproduces the bug
- [ ] Fix reverted → test fails (confirms test actually catches the bug)
- [ ] Fix restored → test passes
- [ ] Test covers the specific triggering condition
- [ ] All existing tests still pass
Similar Patterns
- [ ] Searched for same pattern elsewhere in codebase
- [ ] Reported or fixed similar occurrences
- [ ] Noted if systemic issue needs architectural fix
Documentation
- [ ] Bug report saved to
.agents/results/bugs/ - [ ] Root cause clearly explained
- [ ] Prevention advice included
- [ ] Files modified listed
Security Check (if applicable)
- [ ] Fix doesn't introduce SQL injection, XSS, or auth bypass
- [ ] Sensitive data not exposed in error messages or logs
Common Bug Patterns & Solutions
Quick reference guide for frequently encountered bugs and their fixes.
---
Frontend Bugs
1. Undefined/Null Errors
Problem: Cannot read property 'X' of undefined
// Crash when data not loaded yet
const name = user.profile.name;Solutions:
// Option 1: Optional chaining + nullish coalescing
const name = user?.profile?.name ?? 'Unknown';
// Option 2: Conditional rendering
{user?.profile && <div>{user.profile.name}</div>}
// Option 3: Early return
if (!user?.profile) return <div>Loading...</div>;---
2. Stale Closures in useEffect
Problem: Event handlers/callbacks use old state values
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // Always logs 0!
}, 1000);
return () => clearInterval(interval);
}, []); // Missing dependency
return <button onClick={() => setCount(c => c + 1)}>+</button>;
}Solutions:
// Option 1: Include dependency
useEffect(() => {
const interval = setInterval(() => {
console.log(count); // Now updates!
}, 1000);
return () => clearInterval(interval);
}, [count]); // Dependency added
// Option 2: Use functional update
useEffect(() => {
const interval = setInterval(() => {
setCount(c => {
console.log(c); // Current value
return c;
});
}, 1000);
return () => clearInterval(interval);
}, []); // Can stay empty
// Option 3: Use ref for latest value
const countRef = useRef(count);
countRef.current = count;
useEffect(() => {
const interval = setInterval(() => {
console.log(countRef.current); // Latest value
}, 1000);
return () => clearInterval(interval);
}, []);---
3. Missing Cleanup in useEffect
Problem: Memory leaks from subscriptions/listeners
useEffect(() => {
const subscription = api.subscribe(data => setData(data));
// Missing cleanup!
}, []);Solution:
useEffect(() => {
const subscription = api.subscribe(data => setData(data));
return () => {
subscription.unsubscribe(); // Cleanup
};
}, []);Common things that need cleanup:
- Event listeners (
addEventListener) - Intervals (
setInterval) - Timeouts (
setTimeout) - Subscriptions (WebSockets, observables)
- API requests (cancellation tokens)
---
4. Race Conditions in Async Effects
Problem: Old requests overwrite new ones
useEffect(() => {
fetchUser(userId).then(setUser);
// If userId changes quickly, old responses arrive after new ones
}, [userId]);Solution:
useEffect(() => {
let cancelled = false;
fetchUser(userId).then(user => {
if (!cancelled) {
setUser(user);
}
});
return () => {
cancelled = true;
};
}, [userId]);---
5. Infinite Re-render Loops
Problem: Component re-renders infinitely
function Component() {
const [data, setData] = useState([]);
useEffect(() => {
setData([...data, 'new']); // Triggers effect again!
}, [data]); // Dependency causes loop
return <div>{data.length}</div>;
}Solutions:
// Option 1: Remove problematic dependency
useEffect(() => {
setData(prevData => [...prevData, 'new']);
}, []); // Empty deps - runs once
// Option 2: Use ref instead of state
const dataRef = useRef([]);
useEffect(() => {
dataRef.current = [...dataRef.current, 'new'];
}, []);
// Option 3: Add condition
useEffect(() => {
if (data.length === 0) { // Only run when empty
setData(['new']);
}
}, [data]);---
6. Key Prop Issues in Lists
Problem: List items reordering incorrectly
// Using index as key
{todos.map((todo, index) => (
<TodoItem key={index} todo={todo} />
))}Solution:
// Use stable, unique ID
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
// If no ID, generate stable key
{todos.map((todo, index) => (
<TodoItem key={`${todo.title}-${index}`} todo={todo} />
))}---
7. Form Input Controlled/Uncontrolled Switch
Problem: Warning: A component is changing an uncontrolled input to be controlled
const [value, setValue] = useState(); // undefined initially
<input value={value} onChange={e => setValue(e.target.value)} />Solution:
// Initialize with empty string
const [value, setValue] = useState('');
<input value={value} onChange={e => setValue(e.target.value)} />
// Or use defaultValue for uncontrolled
<input defaultValue="" onChange={e => console.log(e.target.value)} />---
Backend Bugs
1. SQL Injection
Problem: User input directly in SQL query
# DANGEROUS!
email = request.args.get('email')
query = f"SELECT * FROM users WHERE email = '{email}'"
db.execute(query)
# User can input: ' OR '1'='1Solution:
# Use parameterized queries
from sqlalchemy import text
email = request.args.get('email')
query = text("SELECT * FROM users WHERE email = :email")
result = db.execute(query, {"email": email})
# Or use ORM
user = db.query(User).filter(User.email == email).first()---
2. N+1 Query Problem
Problem: One query per item in a loop
# 1 query to get todos
todos = db.query(Todo).all()
# N queries (one per todo)
for todo in todos:
user = db.query(User).filter(User.id == todo.user_id).first()
print(f"{todo.title} by {user.name}")Solution:
# Use JOIN - single query
from sqlalchemy.orm import joinedload
todos = db.query(Todo).options(joinedload(Todo.user)).all()
for todo in todos:
print(f"{todo.title} by {todo.user.name}") # No extra query---
3. Missing Authentication Check
Problem: Protected endpoint accessible without auth
@app.get("/api/admin/users")
async def get_all_users(db: DatabaseDep):
return db.query(User).all() # Anyone can access!Solution:
@app.get("/api/admin/users")
async def get_all_users(
db: DatabaseDep,
current_user: User = Depends(get_current_user) # Require auth
):
if current_user.role != "admin": # Check role
raise HTTPException(403, "Admin only")
return db.query(User).all()---
4. Missing Input Validation
Problem: Invalid data causes errors
@app.post("/api/users")
async def create_user(email: str, age: int):
# No validation!
user = User(email=email, age=age)
db.add(user)
db.commit()Solution:
from pydantic import BaseModel, EmailStr, Field
class UserCreate(BaseModel):
email: EmailStr # Validates email format
age: int = Field(ge=0, le=150) # Must be 0-150
@app.post("/api/users")
async def create_user(user: UserCreate):
# Pydantic validates automatically
db_user = User(**user.model_dump())
db.add(db_user)
db.commit()---
5. Unhandled Exceptions
Problem: Server crashes on error
@app.post("/api/todos")
async def create_todo(todo: TodoCreate, user: User = Depends(get_current_user)):
db_todo = Todo(**todo.model_dump(), user_id=user.id)
db.add(db_todo)
db.commit() # Could fail!
return db_todoSolution:
from fastapi import HTTPException
@app.post("/api/todos")
async def create_todo(todo: TodoCreate, user: User = Depends(get_current_user)):
try:
db_todo = Todo(**todo.model_dump(), user_id=user.id)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
except IntegrityError as e:
db.rollback()
raise HTTPException(409, "Duplicate entry")
except Exception as e:
db.rollback()
logger.error(f"Failed to create todo: {e}")
raise HTTPException(500, "Internal server error")---
6. Missing CORS Configuration
Problem: Frontend can't call API
Access to fetch at 'http://localhost:8000/api/todos' from origin
'http://localhost:3000' has been blocked by CORS policySolution:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"], # Frontend URL
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# For production, be specific:
# allow_origins=["https://yourdomain.com"]---
7. Password Storage
Problem: Passwords stored in plain text
user = User(email=email, password=password) # NEVER DO THIS!Solution:
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Hash before storing
password_hash = pwd_context.hash(password)
user = User(email=email, password_hash=password_hash)
# Verify on login
if not pwd_context.verify(plain_password, user.password_hash):
raise HTTPException(401, "Invalid credentials")---
Mobile Bugs
1. Memory Leaks in Flutter
Problem: Controllers not disposed
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final controller = TextEditingController();
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
// Missing dispose!
}Solution:
class _MyWidgetState extends State<MyWidget> {
final controller = TextEditingController();
@override
void dispose() {
controller.dispose(); // Clean up
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: controller);
}
}---
2. Platform-Specific Code Not Checked
Problem: iOS-specific code crashes on Android
// Crashes on Android
import 'dart:io' show Platform;
final deviceName = Platform.isIOS ? 'iPhone' : 'Unknown';Solution:
import 'dart:io' show Platform;
final deviceName = Platform.isIOS
? 'iPhone'
: Platform.isAndroid
? 'Android'
: 'Unknown';
// Or use conditional imports
if (Platform.isIOS) {
// iOS-specific code
} else if (Platform.isAndroid) {
// Android-specific code
}---
Performance Bugs
1. Unnecessary Re-renders (React)
Problem: Component re-renders on every parent render
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
<ExpensiveChild data={someData} /> {/* Re-renders every time! */}
</div>
);
}Solution:
// Memoize the expensive component
const ExpensiveChild = React.memo(function ExpensiveChild({ data }) {
// Only re-renders when data changes
return <div>{/* expensive computation */}</div>;
});
// Or memoize the props
function Parent() {
const [count, setCount] = useState(0);
const memoizedData = useMemo(() => computeData(), []);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
<ExpensiveChild data={memoizedData} />
</div>
);
}---
2. Large Bundle Size
Problem: Importing entire library
// Imports all of lodash (~70KB)
import _ from 'lodash';
const unique = _.uniq(array);Solution:
// Import only what you need
import uniq from 'lodash/uniq'; // ~2KB
const unique = uniq(array);
// Or use native methods
const unique = [...new Set(array)];---
Security Bugs
1. XSS (Cross-Site Scripting)
Problem: User input rendered as HTML
// Dangerous!
<div dangerouslySetInnerHTML={{ __html: userComment }} />Solution:
// React escapes by default
<div>{userComment}</div>
// If HTML needed, sanitize first
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(userComment)
}} />---
2. Missing Rate Limiting
Problem: API can be abused
@app.post("/api/auth/login")
async def login(credentials: LoginRequest):
# No rate limiting - brute force possible!
...Solution:
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
@app.post("/api/auth/login")
@limiter.limit("5/minute") # Max 5 attempts per minute
async def login(request: Request, credentials: LoginRequest):
...---
Common Error Messages & Solutions
| Error | Likely Cause | Solution |
|---|---|---|
Cannot read property 'X' of undefined | Accessing property before data loads | Add null check or optional chaining |
Maximum update depth exceeded | Infinite re-render loop | Check useEffect dependencies |
Warning: Each child should have unique key | Missing/duplicate keys in list | Use unique, stable IDs as keys |
401 Unauthorized | Missing/invalid auth token | Check token in request headers |
403 Forbidden | Insufficient permissions | Verify user role/permissions |
404 Not Found | Wrong URL or resource doesn't exist | Check endpoint path and resource ID |
500 Internal Server Error | Backend exception | Check server logs for stack trace |
CORS Error | Cross-origin request blocked | Configure CORS middleware |
ERR_CONNECTION_REFUSED | Server not running | Start the backend server |
---
Quick Debugging Commands
Frontend
# Check for errors
npm run lint
# Run tests
npm test
# Build and check bundle size
npm run build
npm run analyze
# Check for unused dependencies
npx depcheckBackend
# Check for security issues
pip install safety
safety check
# Run tests with coverage
pytest --cov=app
# Check for SQL injection
bandit -r app/Mobile
# Check for issues
flutter analyze
# Run tests
flutter test
# Check app size
flutter build apk --analyze-size---
When to Use Each Agent
| Bug Type | Best Agent | Reason |
|---|---|---|
| Frontend crash | debug-agent | Specializes in bug diagnosis |
| Backend API error | debug-agent | Can trace through stack |
| Complex multi-domain | oma-coordination | Coordinates multiple agents |
| Security vulnerability | qa-agent | Security expertise |
| Performance issue | qa-agent | Performance profiling tools |
| New feature needed | Specialist agent | Not a bug, it's a feature |
---
Prevention Tips
1. Write tests first - Catch bugs before they ship 2. Use TypeScript - Catch type errors at compile time 3. Enable strict mode - More safety checks 4. Code review - Second pair of eyes 5. Automated linting - Enforce best practices 6. Error monitoring - Sentry, LogRocket, etc. 7. User testing - Real users find real bugs
---
Remember: The best bug is the one that never happens. Write defensive code, test thoroughly, and document lessons learned!
Debugging Checklist
Use this checklist when investigating bugs to ensure thorough analysis.
Initial Information Gathering
- [ ] Bug description - What is the expected vs actual behavior?
- [ ] Error messages - Exact error text, stack trace, error codes
- [ ] Reproduction steps - Clear, numbered steps to trigger the bug
- [ ] Frequency - Every time, intermittent, specific conditions?
- [ ] Environment - Browser/OS/version, mobile device, server environment
- [ ] User impact - How many users affected? Severity?
- [ ] Recent changes - New deploy? Code changes? Configuration updates?
- [ ] Screenshots/videos - Visual evidence of the bug
Frontend Debugging
JavaScript/TypeScript Errors
- [ ] Check browser console (F12) for errors
- [ ] Review stack trace - which file and line?
- [ ] Identify error type (TypeError, ReferenceError, etc.)
- [ ] Check for null/undefined values
- [ ] Verify variable types (especially after API calls)
- [ ] Look for typos in property names
React Component Issues
- [ ] State problems
- [ ] State not updating? (need setState/useState)
- [ ] Stale state in closures? (use refs or functional updates)
- [ ] State out of sync with props?
- [ ] Effect problems
- [ ] Missing dependencies in useEffect?
- [ ] Effect running too many times?
- [ ] Cleanup function needed?
- [ ] Memory leak from uncancelled requests?
- [ ] Rendering issues
- [ ] Conditional rendering logic correct?
- [ ] Keys on list items unique and stable?
- [ ] Unnecessary re-renders? (use React DevTools Profiler)
UI/UX Issues
- [ ] CSS not applying? (check specificity, typos)
- [ ] Layout broken? (check responsive breakpoints)
- [ ] Accessibility issues? (keyboard nav, screen reader)
- [ ] Dark mode broken?
- [ ] Mobile-specific issues?
API Integration
- [ ] Network tab investigation
- [ ] Request sent? (check Headers tab)
- [ ] Correct endpoint URL?
- [ ] Proper HTTP method (GET, POST, etc.)?
- [ ] Headers included (Authorization, Content-Type)?
- [ ] Request body formatted correctly?
- [ ] Response status code (200, 401, 404, 500)?
- [ ] Response data structure matches expected?
- [ ] Error handling
- [ ] Try/catch around API calls?
- [ ] Error state displayed to user?
- [ ] Timeout handling?
- [ ] Network failure handling?
- [ ] Loading states
- [ ] Loading spinner shown?
- [ ] Disabled buttons during load?
- [ ] Optimistic updates causing issues?
Backend Debugging
Python/FastAPI Errors
- [ ] Stack trace analysis
- [ ] Read error message carefully
- [ ] Identify the failing file and line
- [ ] Understand the error type (ValueError, KeyError, etc.)
- [ ] Check for None values
- [ ] Verify data types
- [ ] Database issues
- [ ] Query syntax correct?
- [ ] N+1 query problem?
- [ ] Missing JOIN?
- [ ] Indexes present on filtered columns?
- [ ] Connection pool exhausted?
- [ ] Transaction isolation issues?
- [ ] Authentication/Authorization
- [ ] Token validation working?
- [ ] Token expired?
- [ ] Permissions checked correctly?
- [ ] User session valid?
- [ ] CORS configured properly?
API Endpoint Issues
- [ ] Request validation
- [ ] Pydantic schema matches request?
- [ ] Required fields present?
- [ ] Field types correct?
- [ ] Value ranges validated?
- [ ] Response formatting
- [ ] Correct status code?
- [ ] Response schema matches contract?
- [ ] Error responses formatted properly?
- [ ] Pagination working?
- [ ] Performance
- [ ] Response time acceptable (<200ms)?
- [ ] Query optimization needed?
- [ ] Caching implemented?
- [ ] Rate limiting working?
Server Issues
- [ ] Logs examination
- [ ] Check application logs
- [ ] Check error logs
- [ ] Check access logs
- [ ] Timestamps correlate with bug reports?
- [ ] Environment
- [ ] Environment variables set?
- [ ] Configuration correct for environment (dev/prod)?
- [ ] External services reachable?
- [ ] Database migrations applied?
Mobile Debugging
Platform-Specific Issues
- [ ] iOS vs Android differences
- [ ] Test on both platforms
- [ ] Check platform-specific code (Platform.OS)
- [ ] Review native module integration
- [ ] Verify permissions (camera, location, etc.)
- [ ] Device-specific
- [ ] Test on actual device (not just emulator)
- [ ] Check different screen sizes
- [ ] Test different OS versions
- [ ] Memory constraints on older devices?
Flutter-Specific
- [ ] Widget tree issues
- [ ] State management correct? (Riverpod/Bloc)
- [ ] Build method pure?
- [ ] Keys used properly?
- [ ] Dispose called for controllers?
- [ ] Platform channels
- [ ] Native code errors?
- [ ] Method channel names correct?
- [ ] Data serialization working?
Mobile Performance
- [ ] Memory leaks? (listeners not disposed)
- [ ] Excessive rebuilds?
- [ ] Large images not optimized?
- [ ] Too many simultaneous network requests?
Security Bugs
- [ ] Authentication bypassed?
- [ ] Token validation on all protected routes?
- [ ] Token expiry checked?
- [ ] Refresh token flow secure?
- [ ] Authorization broken?
- [ ] User can access others' data?
- [ ] Admin functions accessible to regular users?
- [ ] Horizontal privilege escalation possible?
- [ ] Injection vulnerabilities
- [ ] SQL injection? (use parameterized queries)
- [ ] XSS? (sanitize user input)
- [ ] Command injection?
- [ ] Path traversal?
- [ ] Data exposure
- [ ] Sensitive data in logs?
- [ ] Passwords in plain text?
- [ ] API keys exposed?
- [ ] Error messages leaking info?
Performance Bugs
Frontend Performance
- [ ] Lighthouse audit
- [ ] Performance score >90?
- [ ] First Contentful Paint <1.5s?
- [ ] Largest Contentful Paint <2.5s?
- [ ] Cumulative Layout Shift <0.1?
- [ ] Bundle analysis
- [ ] Main bundle <500KB?
- [ ] Code splitting implemented?
- [ ] Large dependencies tree-shaken?
- [ ] Lazy loading used?
- [ ] React performance
- [ ] Unnecessary re-renders? (React DevTools Profiler)
- [ ] Memo/useMemo/useCallback used appropriately?
- [ ] Virtual scrolling for long lists?
Backend Performance
- [ ] API latency
- [ ] p95 response time <200ms?
- [ ] Slow queries identified?
- [ ] Indexes added?
- [ ] Caching implemented?
- [ ] Database
- [ ] Connection pooling configured?
- [ ] Query plan optimized? (EXPLAIN)
- [ ] N+1 queries eliminated?
Root Cause Analysis
- [ ] Reproduce the bug
- [ ] Follow exact reproduction steps
- [ ] Confirm bug exists
- [ ] Note any variations
- [ ] Isolate the problem
- [ ] Which component/function fails?
- [ ] What input triggers it?
- [ ] What conditions must be met?
- [ ] Trace the data flow
- [ ] Where does the bad data come from?
- [ ] How is it transformed?
- [ ] Where does it cause the failure?
- [ ] Identify the root cause
- [ ] Not just the symptom
- [ ] Why does this happen?
- [ ] What assumption was wrong?
Fix Verification
- [ ] Fix applied
- [ ] Code changed in correct file(s)
- [ ] Logic correct
- [ ] Edge cases handled
- [ ] No new bugs introduced
- [ ] Testing
- [ ] Regression test written
- [ ] Test passes
- [ ] Manual verification done
- [ ] Edge cases tested
- [ ] Related areas checked
- [ ] Similar patterns elsewhere?
- [ ] Other code depending on this?
- [ ] Breaking changes avoided?
- [ ] Documentation
- [ ] Bug documented in Knowledge Base
- [ ] Fix explained
- [ ] Prevention notes added
When to Escalate
Escalate to other agents if:
- [ ] Bug spans multiple domains → oma-coordination
- [ ] Requires architectural change → PM Agent
- [ ] Need comprehensive security audit → QA Agent
- [ ] Complex frontend refactoring needed → Frontend Agent
- [ ] Database schema changes needed → Backend Agent
- [ ] Platform-specific mobile issue → Mobile Agent
Priority Assessment
CRITICAL - Fix immediately:
- [ ] App crashes on launch
- [ ] Data loss or corruption
- [ ] Security vulnerability
- [ ] Payment/auth completely broken
- [ ] Affects all users
HIGH - Fix within 24 hours:
- [ ] Major feature broken
- [ ] Affects >50% of users
- [ ] No workaround available
- [ ] Significant revenue impact
MEDIUM - Fix within sprint:
- [ ] Minor feature broken
- [ ] Affects <50% of users
- [ ] Workaround exists
- [ ] Moderate inconvenience
LOW - Schedule for future:
- [ ] Edge case
- [ ] Cosmetic issue
- [ ] Rarely encountered
- [ ] No user impact
Documentation Template
After fixing, document in .agents/results/bugs/:
# Bug: [Title]
**Date**: YYYY-MM-DD
**Severity**: CRITICAL/HIGH/MEDIUM/LOW
**Status**: FIXED
## Problem
[What was broken]
## Root Cause
[Why it was broken]
## Fix
[What was changed]
## Files Modified
- path/to/file
## Testing
- [x] Regression test added
- [x] Manual verification
- [x] Related areas checked
## Prevention
[How to avoid in future]---
Pro Tips
1. Read the error message - It usually tells you exactly what's wrong 2. Reproduce first - Don't waste time fixing unconfirmed bugs 3. One change at a time - Don't fix multiple things simultaneously 4. Test thoroughly - Verify the fix and check for regressions 5. Document everything - Future you will be grateful 6. Look for patterns - One bug often reveals more
Tools Reference
- Browser DevTools: F12 (Console, Network, React DevTools)
- Serena MCP: find_symbol, search_for_pattern, find_referencing_symbols
- Antigravity Browser: Automated testing and reproduction
- React Profiler: Performance analysis
- Lighthouse: Performance audit
- Git bisect: Find when bug was introduced
Debug Agent - Error Recovery Playbook
When you encounter a failure during debugging, follow these recovery steps. Do NOT stop or ask for help until you have exhausted the playbook.
---
Cannot Reproduce the Bug
Symptoms: Bug described by user but you can't trigger it
1. Re-read user's reproduction steps; are you following them exactly? 2. Check environment differences: browser, OS, node/python version 3. Check data-dependent: does it need specific DB state or test data? 4. Check timing: is it a race condition? Try adding delays or rapid repetition 5. After 3 attempts: Record Status: cannot_reproduce in result with condition list
- NEVER give up immediately saying "cannot reproduce"
---
Fix Introduces New Failure
Symptoms: Original bug fixed but other tests break
1. Read the failing tests; are they testing the old (buggy) behavior? 2. If yes: update tests to reflect correct behavior 3. If no: your fix has side effects. Revert and try a more targeted approach 4. find_referencing_symbols("fixedFunction") to check all callers 5. Consider: is the function contract changing? If so, update all callers
---
Root Cause Unclear
Symptoms: You see the failure but can't trace why
1. Add logging at each step of the execution path 2. Binary search: is the bug before or after the midpoint? 3. search_for_pattern("suspicious_pattern") to find related code 4. Check git history: git log --oneline -20 -- path/to/file. When was it last changed? 5. Check: is it a dependency issue? Library version mismatch? 6. No progress after 5 turns: Record current analysis in progress, switch to different hypothesis
---
Bug Is in Another Agent's Domain
Symptoms: Frontend bug caused by backend API, or vice versa
1. Confirm: is the root cause really in the other domain? 2. Document the cross-domain issue clearly:
- Which endpoint/component is wrong
- What the correct behavior should be
- Evidence (request/response logs, stack trace)
3. Record in result: cross_domain_issue: {agent: "backend", description: "..."} 4. Do NOT modify directly; touching another agent's code causes conflicts
---
Performance Bug Hard to Measure
Symptoms: "It's slow" but no clear metric
1. Establish baseline: measure current response time / render time 2. Backend: enable SQL query logging, count queries, check EXPLAIN ANALYZE 3. Frontend: run Lighthouse, check React DevTools Profiler 4. Mobile: use Flutter DevTools performance tab 5. Profile before fixing; never optimize without data
---
Test Cannot Be Written
Symptoms: Bug is real but hard to test (race condition, environment-specific)
1. Try: mock the timing / environment condition 2. Try: integration test instead of unit test 3. If truly untestable: document the manual reproduction steps 4. Add a comment in code explaining why the fix is correct 5. Note in result: test_limitation: "reason why automated test is not feasible"
---
Rate Limit / Quota / Memory Fallback
Same as the backend playbook: see ../../oma-backend/resources/error-playbook.md §"Rate Limit / Quota Error (Gemini API)" and §"Serena Memory Unavailable".
---
General Principles
- After 3 failures: If same approach fails 3 times, must try a different method
- Blocked: If no progress after 5 turns, save current state,
Status: blocked - Out of scope: Other agent's domain. Only record, do not modify directly
Debug Agent - Examples
Example 1: Null Reference Error
Input: "TodoList crashes with 'Cannot read property map of undefined'"
Output:
## Bug Analysis
**Root Cause**: TodoList renders before API data loads. `todos` is undefined
on first render, and `.map()` is called immediately.
**Why**: useEffect fetches async, but component doesn't guard against
undefined initial state.
## Fix
- Before: `todos.map(t => <TodoItem ... />)`
- After: `todos?.map(t => <TodoItem ... />) ?? <EmptyState />`
- Also added loading spinner while fetching
## Changes Made
1. Added `if (isLoading) return <Spinner />`
2. Added optional chaining on `todos?.map()`
3. Added empty state component
## Files Modified
- src/components/TodoList.tsx (guard + loading state)
- src/components/EmptyState.tsx (NEW)
- tests/TodoList.test.tsx (regression test)
## Prevention
Use TanStack Query which provides `isLoading`/`data` pattern by default.Example 2: N+1 Query Performance Bug
Input: "The posts page takes 3 seconds to load with only 50 posts"
Output:
## Bug Analysis
**Root Cause**: N+1 query. For each post, a separate SQL query fetches
the author. 50 posts = 51 queries.
**Why**: SQLAlchemy lazy-loads relationships by default.
## Fix
- Before: `db.query(Post).all()`
- After: `db.query(Post).options(joinedload(Post.author)).all()`
## Changes Made
1. Added eager loading with joinedload
2. Load time: 3000ms -> 45ms
## Files Modified
- app/api/posts.py (eager loading)
- tests/test_posts.py (performance assertion: < 200ms)Example 3: Race Condition
Input: "Search results show wrong data when typing fast"
Output:
## Bug Analysis
**Root Cause**: Race condition. Fast typing triggers multiple API calls.
Slower early requests resolve after faster recent ones, overwriting
correct results.
**Why**: No request cancellation; last-write-wins causes stale data.
## Fix
Added AbortController to cancel previous request on new keystroke.
## Changes Made
1. useEffect cleanup cancels pending request
2. Added debounce (300ms) to reduce API calls
3. Added `cancelled` flag to ignore stale responses
## Files Modified
- src/hooks/useSearch.ts (abort + debounce)
- tests/useSearch.test.ts (race condition test)Debug Agent - Execution Protocol
Step 0: Prepare
1. Assess difficulty: see ../../_shared/core/difficulty-guide.md
- Simple: Skip to Step 3 | Medium: All 4 steps | Complex: All steps + checkpoints
2. Check lessons: read your domain section in ../../_shared/core/lessons-learned.md 3. Clarify requirements: follow ../../_shared/core/clarification-protocol.md
- Check Uncertainty Triggers: security/auth related bugs, existing code conflict potential?
- Determine level: LOW → proceed | MEDIUM → present options | HIGH → ask immediately
4. Use reasoning templates: for Complex bugs, use ../../_shared/core/reasoning-templates.md (hypothesis loop, execution trace) 5. Budget context: follow ../../_shared/core/context-budget.md (use find_symbol, not read_file)
Intelligent Escalation: When uncertain, escalate early. Don't blindly proceed.
Follow these steps in order (adjust depth by difficulty).
Step 1: Understand
- Gather: What happened? What was expected? Error messages? Steps to reproduce?
- Read relevant code using Serena:
find_symbol("functionName"): Locate the failing functionfind_referencing_symbols("Component"): Find all callerssearch_for_pattern("error pattern"): Find similar issues- Classify: logic bug, runtime error, performance issue, security flaw, or integration failure
Step 2: Reproduce & Diagnose
- Trace execution flow from entry point to failure
- Identify the exact line and condition that causes the bug
- Determine root cause (not just symptom):
- Null/undefined access?
- Race condition?
- Missing validation?
- Wrong assumption about data shape?
- Check
resources/common-patterns.mdfor known patterns
Step 3: Fix & Test
- Apply minimal fix that addresses the root cause
- Write a regression test that:
- Fails without the fix
- Passes with the fix
- Covers the specific edge case
- Check for similar patterns elsewhere:
search_for_pattern("same_bug_pattern") - If found, fix proactively or report them
Step 4: Document & Verify
- Run
resources/checklist.mditems - Save bug report to
.agents/results/bugs/usingresources/bug-report-template.md - Include: root cause, fix, prevention advice
- Verify no regressions in related functionality
On Error
See resources/error-playbook.md for recovery steps.