Runtime debugging workflow with automated log collection. Use when fixing bugs that require runtime evidence (values, types, flow), when you'd otherwise ask user to "open DevTools, reproduce X, tell me what you see", or when bug depends on user interaction that can't be simulated. This skill automates log collection - logs are captured server-side and accessible programmatically.
Add this skill
npx mdskills install elie222/inbox-zeroComprehensive debugging workflow with hypothesis-driven instrumentation and automated log collection
1---2name: debug3description: Runtime debugging workflow with automated log collection. Use when fixing bugs that require runtime evidence (values, types, flow), when you'd otherwise ask user to "open DevTools, reproduce X, tell me what you see", or when bug depends on user interaction that can't be simulated. This skill automates log collection - logs are captured server-side and accessible programmatically.4---56# Debug Mode78Fix bugs with **runtime evidence**, not guesses.910```11Don't guess → Hypothesize → Instrument → Reproduce → Analyze → Fix → Verify12```1314## When to Use1516**Trigger signals** (if you're about to do any of these, use this skill instead):17- "Open DevTools Console and check for..."18- "Reproduce the bug and tell me what you see"19- "Add console.log and let me know the output"20- "Click X, open Y, check if Z appears in console"2122**Example scenario that should trigger this skill:**23```24❌ Without skill (manual, slow):25"I added debug logging. Please:261. Open the app in browser272. Open DevTools Console (F12)283. Open the defect modal and select a defect294. Check console for [DEBUG] logs305. Tell me what you see"3132✅ With skill (automated):33Logs are captured server-side → you read them directly → no user copy-paste needed34```3536**Use when debugging:**37- State/value issues (null, undefined, wrong type)38- Conditional logic (which branch was taken)39- Async timing (race conditions, load order)40- User interaction flows (modals, forms, clicks)4142## Arguments4344```45/debug /path/to/project46```4748If no path provided, use current working directory.4950## Workflow5152### Phase 1: Start Log Server5354**Step 1: Ensure server is running** (starts if needed, no-op if already running):5556```bash57node skills/debug/scripts/debug_server.js /path/to/project &58```5960Server outputs JSON:61- `{"status":"started",...}` - new server started62- `{"status":"already_running",...}` - server was already running (this is fine!)6364**Step 2: Create session** (server generates unique ID from your description):6566```bash67curl -s -X POST http://localhost:8787/session -d '{"name":"fix-null-userid"}'68```6970Response:71```json72{"session_id":"fix-null-userid-a1b2c3","log_file":"/path/to/project/.debug/debug-fix-null-userid-a1b2c3.log"}73```7475**Save the `session_id` from the response** - use it in all subsequent steps.7677**Server endpoints:**78- POST `/session` with `{"name": "description"}` → creates session, returns `{session_id, log_file}`79- POST `/log` with `{"sessionId": "...", "msg": "..."}` → writes to log file80- GET `/` → returns status and log directory8182**If port 8787 busy:** `lsof -ti :8787 | xargs kill -9` then restart8384──────────8586### Phase 2: Generate Hypotheses8788**Before instrumenting**, generate 3-5 specific hypotheses:8990```91Hypothesis H1: userId is null when passed to calculateScore()92 Expected: number (e.g., 5)93 Actual: null94 Test: Log userId at function entry9596Hypothesis H2: score is string instead of number97 Expected: 85 (number)98 Actual: "85" (string)99 Test: Log typeof score100```101102Each hypothesis must be:103- **Specific** (not "something is wrong")104- **Testable** (can confirm/reject with logs)105- **Cover different subsystems** (don't cluster)106107──────────108109### Phase 3: Instrument Code110111Add logging calls to test all hypotheses.112113**JavaScript/TypeScript:**114```javascript115// #region debug116const SESSION_ID = 'REPLACE_WITH_SESSION_ID'; // e.g. 'fix-null-userid-a1b2c3'117const DEBUG_LOG_URL = 'http://localhost:8787/log';118119const debugLog = (msg, data = {}, hypothesisId = null) => {120 const payload = JSON.stringify({121 sessionId: SESSION_ID,122 msg,123 data,124 hypothesisId,125 loc: new Error().stack?.split('\n')[2],126 });127128 if (navigator.sendBeacon?.(DEBUG_LOG_URL, payload)) return;129 fetch(DEBUG_LOG_URL, { method: 'POST', body: payload }).catch(() => {});130};131// #endregion132133// Usage134debugLog('Function entry', { userId, score, typeScore: typeof score }, 'H1,H2');135```136137**Python:**138```python139# #region debug140import requests, traceback141SESSION_ID = 'REPLACE_WITH_SESSION_ID' # e.g. 'fix-null-userid-a1b2c3'142def debug_log(msg, data=None, hypothesis_id=None):143 try:144 requests.post('http://localhost:8787/log', json={145 'sessionId': SESSION_ID, 'msg': msg, 'data': data,146 'hypothesisId': hypothesis_id, 'loc': traceback.format_stack()[-2].strip()147 }, timeout=0.5)148 except: pass149# #endregion150151# Usage152debug_log('Function entry', {'user_id': user_id, 'type': type(user_id)}, 'H1')153```154155**Guidelines:**156- 3-8 instrumentation points157- Cover: entry/exit, before/after critical ops, branch paths158- Tag each log with `hypothesisId`159- Wrap in `// #region debug` ... `// #endregion`160- **High-frequency events** (mousemove, scroll): log only on **state change**161- Log both **intent** and **result**162163──────────164165### Phase 4: Clear and Reproduce1661671. Clear logs:168 ```bash169 : > /path/to/project/.debug/debug-$SESSION_ID.log170 ```1711722. Provide reproduction steps:173 ```xml174 <reproduction_steps>175 1. Start app: yarn dev176 2. Navigate to /users177 3. Click "Calculate Score"178 4. Observe NaN displayed179 </reproduction_steps>180 ```1811823. User reproduces bug183184──────────185186### Phase 5: Analyze Logs187188Read and evaluate:189```bash190cat /path/to/project/.debug/debug-$SESSION_ID.log191```192193For each hypothesis:194195```196Hypothesis H1: userId is null197 Status: CONFIRMED198 Evidence: {"msg":"Function entry","data":{"userId":null}}199200Hypothesis H2: score is string201 Status: REJECTED202 Evidence: {"data":{"typeScore":"number"}}203```204205**Status options:**206- **CONFIRMED**: Logs prove it207- **REJECTED**: Logs disprove it208- **INCONCLUSIVE**: Need more instrumentation209210**If all INCONCLUSIVE/REJECTED**: Generate new hypotheses, add more logs, iterate.211212──────────213214### Phase 6: Fix215216**Only fix when logs confirm root cause.**217218Keep instrumentation active (don't remove yet).219220Tag verification logs with `runId: "post-fix"`:221```javascript222debugLog('Function entry', { userId, runId: 'post-fix' }, 'H1');223```224225──────────226227### Phase 7: Verify2282291. Clear logs2302. User reproduces (bug should be gone)2313. Compare before/after:232 ```233 Before: {"data":{"userId":null},"runId":"run1"}234 After: {"data":{"userId":5},"runId":"post-fix"}235 ```2364. Confirm with log evidence237238**If still broken**: New hypotheses, more logs, iterate.239240──────────241242### Phase 8: Five Whys (Optional)243244**When to run:** Recurring bug, prod incident, security issue, or "this keeps happening".245246After fixing, ask "Why did this bug exist?" to find systemic causes:247248```249Bug: API returns NaN250251Why 1: userId was null → Code fix: null check252Why 2: No input validation → Add validation253Why 3: No test for null case → Add test254Why 4: Review didn't catch → (one-off, acceptable)255```256257**Categories:**258| Type | Action |259|------|--------|260| CODE | Fix immediately |261| TEST | Add test |262| PROCESS | Update checklist/review |263| SYSTEMIC | Document patterns |264265**Skip if:** Simple one-off bug, low impact, not recurring.266267──────────268269### Phase 9: Clean Up270271Remove instrumentation only after:272- Post-fix logs prove success273- User confirms resolved274275Search for `#region debug` and remove all debug code.276277## Log Format278279Each line is NDJSON:280```json281{"ts":"2024-01-03T12:00:00.000Z","msg":"Button clicked","data":{"id":5},"hypothesisId":"H1","loc":"app.js:42"}282```283284## Critical Rules2852861. **NEVER fix without runtime evidence** - Always collect logs first2872. **NEVER remove instrumentation before verification** - Keep until fix confirmed2883. **NEVER guess** - If unsure, add more logs2894. **If all hypotheses rejected** - Generate new ones from different subsystems290291## Troubleshooting292293| Issue | Solution |294|-------|----------|295| Server won't start | Check port 8787 not in use: `lsof -i :8787` |296| Logs empty | Check browser blocks (mixed content/CSP/CORS), firewall |297| Wrong log file | Verify session ID matches |298| Too many logs | Filter by hypothesisId, use state-change logging |299| Can't reproduce | Ask user for exact steps, check environment |300301### CORS / Mixed Content Workarounds302303If logs aren't arriving, it’s usually one of:304- **Mixed content**: HTTPS app → `http://localhost:8787` is blocked. Use a dev-server proxy (same origin) or serve the log endpoint over HTTPS.305- **CSP**: `connect-src` blocks the log URL. Use a dev-server proxy or update CSP.306- **CORS preflight**: `Content-Type: application/json` triggers `OPTIONS`. Use a “simple” request (`text/plain`) or `sendBeacon`.307308**1. `sendBeacon` (avoids preflight; fire-and-forget)**:309```javascript310const DEBUG_LOG_URL = 'http://localhost:8787/log';311const debugLog = (msg, data = {}, hypothesisId = null) => {312 const payload = JSON.stringify({ sessionId: SESSION_ID, msg, data, hypothesisId });313 if (navigator.sendBeacon?.(DEBUG_LOG_URL, payload)) return;314 fetch(DEBUG_LOG_URL, { method: 'POST', body: payload }).catch(() => {});315};316```317Note: still blocked by mixed content + CSP.318319**2. Dev server proxy (Vite example)** - same-origin `/__log` → `http://localhost:8787/log`:320```javascript321// vite.config.js322export default {323 server: {324 proxy: {325 '/__log': {326 target: 'http://localhost:8787',327 changeOrigin: true,328 rewrite: (path) => path.replace(/^\/__log/, '/log'),329 },330 },331 },332};333334// Then POST to /__log instead of localhost:8787/log335```336337**3. Last resort (local only)** - allow insecure content / disable mixed-content blocking in browser settings338339## Checklist340341- [ ] Server running (started or already_running)342- [ ] Session created via `POST /session` - save the returned `session_id`343- [ ] 3-5 hypotheses generated344- [ ] 3-8 logs added, tagged with hypothesisId345- [ ] Logs cleared before reproduction346- [ ] Reproduction steps provided347- [ ] Each hypothesis evaluated (CONFIRMED/REJECTED/INCONCLUSIVE)348- [ ] Fix based on evidence only349- [ ] Before/after comparison done350- [ ] Instrumentation removed after confirmation351
Full transparency — inspect the skill content before installing.