proagents 1.6.8 → 1.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1130 @@
1
+ # Phase 10: Debug & Log Management
2
+
3
+ ## Command
4
+ ```
5
+ pa:debug
6
+ pa:logs
7
+ ```
8
+
9
+ ## Aliases
10
+ - `pa:debug` → Full debug workflow
11
+ - `pa:logs` → View/analyze logs
12
+ - `pa:log` → Quick log check
13
+
14
+ ---
15
+
16
+ ## Overview
17
+
18
+ Debug and log management across all platforms:
19
+ - **Web**: Browser console, network logs
20
+ - **React Native**: Metro bundler, device logs
21
+ - **Android Native**: Logcat, ADB logs
22
+ - **iOS Native**: Xcode console, device logs
23
+
24
+ ---
25
+
26
+ ## Commands Reference
27
+
28
+ | Command | Action |
29
+ |---------|--------|
30
+ | `pa:debug` | Start debug session |
31
+ | `pa:debug-web` | Web console debugging |
32
+ | `pa:debug-rn` | React Native debugging |
33
+ | `pa:debug-android` | Android native debugging |
34
+ | `pa:debug-ios` | iOS native debugging |
35
+ | `pa:logs` | View recent logs |
36
+ | `pa:logs-filter "term"` | Filter logs by term |
37
+ | `pa:logs-clear` | Clear debug logs |
38
+ | `pa:logs-export` | Export logs to file |
39
+ | `pa:debug-clean` | Remove debug statements before production |
40
+ | `pa:debug-add` | Add debug logs to code |
41
+ | `pa:debug-add "file"` | Add logs to specific file |
42
+ | `pa:debug-trace "function"` | Add entry/exit logs to function |
43
+ | `pa:debug-var "variable"` | Track variable changes |
44
+ | `pa:debug-api` | Add API request/response logging |
45
+ | `pa:debug-state` | Add state change logging |
46
+ | `pa:debug-error` | Add error boundary/try-catch logging |
47
+
48
+ ---
49
+
50
+ ## Adding Debug Logs to Code
51
+
52
+ ### pa:debug-add
53
+
54
+ Intelligently add debug logs throughout code. AI analyzes the code and adds appropriate logging.
55
+
56
+ **What gets logged:**
57
+ - Function entry/exit with parameters
58
+ - Variable state changes
59
+ - API calls and responses
60
+ - Error conditions
61
+ - State mutations
62
+ - User interactions
63
+
64
+ **Log Markers:**
65
+ All added logs are marked for easy removal:
66
+ ```javascript
67
+ // DEBUG:START - Added by pa:debug
68
+ console.log('[DEBUG] functionName:', { param1, param2 });
69
+ // DEBUG:END
70
+ ```
71
+
72
+ ---
73
+
74
+ ### Platform-Specific Log Insertion
75
+
76
+ #### JavaScript / TypeScript / React / React Native
77
+
78
+ **Function Tracing:**
79
+ ```javascript
80
+ // DEBUG:START
81
+ const originalFunction = myFunction;
82
+ myFunction = function(...args) {
83
+ console.log('[DEBUG:ENTER] myFunction', { args, timestamp: Date.now() });
84
+ const result = originalFunction.apply(this, args);
85
+ console.log('[DEBUG:EXIT] myFunction', { result, timestamp: Date.now() });
86
+ return result;
87
+ };
88
+ // DEBUG:END
89
+ ```
90
+
91
+ **Variable Tracking:**
92
+ ```javascript
93
+ // DEBUG:START
94
+ let _debugValue = myVariable;
95
+ Object.defineProperty(window, 'myVariable', {
96
+ get: () => _debugValue,
97
+ set: (val) => {
98
+ console.log('[DEBUG:VAR] myVariable changed:', { from: _debugValue, to: val });
99
+ _debugValue = val;
100
+ }
101
+ });
102
+ // DEBUG:END
103
+ ```
104
+
105
+ **React Component Logging:**
106
+ ```javascript
107
+ // DEBUG:START
108
+ useEffect(() => {
109
+ console.log('[DEBUG:MOUNT] ComponentName mounted', { props });
110
+ return () => console.log('[DEBUG:UNMOUNT] ComponentName unmounted');
111
+ }, []);
112
+
113
+ useEffect(() => {
114
+ console.log('[DEBUG:STATE] state changed:', { stateName: value });
115
+ }, [value]);
116
+ // DEBUG:END
117
+ ```
118
+
119
+ **API Call Logging:**
120
+ ```javascript
121
+ // DEBUG:START
122
+ console.log('[DEBUG:API:REQ]', {
123
+ method: 'POST',
124
+ url: '/api/users',
125
+ body: requestData,
126
+ timestamp: new Date().toISOString()
127
+ });
128
+ // DEBUG:END
129
+
130
+ const response = await fetch('/api/users', { method: 'POST', body: requestData });
131
+
132
+ // DEBUG:START
133
+ console.log('[DEBUG:API:RES]', {
134
+ status: response.status,
135
+ data: responseData,
136
+ duration: `${Date.now() - startTime}ms`
137
+ });
138
+ // DEBUG:END
139
+ ```
140
+
141
+ **Error Logging:**
142
+ ```javascript
143
+ // DEBUG:START
144
+ try {
145
+ // DEBUG:END
146
+ // existing code
147
+ // DEBUG:START
148
+ } catch (error) {
149
+ console.error('[DEBUG:ERROR]', {
150
+ error: error.message,
151
+ stack: error.stack,
152
+ context: { functionName: 'myFunction', params }
153
+ });
154
+ throw error;
155
+ }
156
+ // DEBUG:END
157
+ ```
158
+
159
+ ---
160
+
161
+ #### Android (Kotlin)
162
+
163
+ **Function Tracing:**
164
+ ```kotlin
165
+ // DEBUG:START
166
+ fun myFunction(param1: String, param2: Int): Result {
167
+ Log.d("DEBUG", "[ENTER] myFunction: param1=$param1, param2=$param2")
168
+ val startTime = System.currentTimeMillis()
169
+ // DEBUG:END
170
+
171
+ // existing code
172
+
173
+ // DEBUG:START
174
+ Log.d("DEBUG", "[EXIT] myFunction: result=$result, duration=${System.currentTimeMillis() - startTime}ms")
175
+ return result
176
+ }
177
+ // DEBUG:END
178
+ ```
179
+
180
+ **Variable Tracking:**
181
+ ```kotlin
182
+ // DEBUG:START
183
+ var myVariable: String = ""
184
+ set(value) {
185
+ Log.d("DEBUG", "[VAR] myVariable: $field -> $value")
186
+ field = value
187
+ }
188
+ // DEBUG:END
189
+ ```
190
+
191
+ **API Call Logging:**
192
+ ```kotlin
193
+ // DEBUG:START
194
+ Log.d("DEBUG", "[API:REQ] POST /api/users: $requestBody")
195
+ // DEBUG:END
196
+
197
+ val response = apiService.createUser(requestBody)
198
+
199
+ // DEBUG:START
200
+ Log.d("DEBUG", "[API:RES] status=${response.code()}, body=${response.body()}")
201
+ // DEBUG:END
202
+ ```
203
+
204
+ **Lifecycle Logging:**
205
+ ```kotlin
206
+ // DEBUG:START
207
+ override fun onCreate(savedInstanceState: Bundle?) {
208
+ Log.d("DEBUG", "[LIFECYCLE] onCreate: ${this::class.simpleName}")
209
+ super.onCreate(savedInstanceState)
210
+ }
211
+
212
+ override fun onResume() {
213
+ Log.d("DEBUG", "[LIFECYCLE] onResume: ${this::class.simpleName}")
214
+ super.onResume()
215
+ }
216
+
217
+ override fun onDestroy() {
218
+ Log.d("DEBUG", "[LIFECYCLE] onDestroy: ${this::class.simpleName}")
219
+ super.onDestroy()
220
+ }
221
+ // DEBUG:END
222
+ ```
223
+
224
+ ---
225
+
226
+ #### iOS (Swift)
227
+
228
+ **Function Tracing:**
229
+ ```swift
230
+ // DEBUG:START
231
+ func myFunction(param1: String, param2: Int) -> Result {
232
+ let startTime = CFAbsoluteTimeGetCurrent()
233
+ print("[DEBUG:ENTER] myFunction: param1=\(param1), param2=\(param2)")
234
+ // DEBUG:END
235
+
236
+ // existing code
237
+
238
+ // DEBUG:START
239
+ let duration = CFAbsoluteTimeGetCurrent() - startTime
240
+ print("[DEBUG:EXIT] myFunction: result=\(result), duration=\(duration)s")
241
+ return result
242
+ }
243
+ // DEBUG:END
244
+ ```
245
+
246
+ **Variable Tracking:**
247
+ ```swift
248
+ // DEBUG:START
249
+ var myVariable: String = "" {
250
+ willSet {
251
+ print("[DEBUG:VAR] myVariable will change: \(myVariable) -> \(newValue)")
252
+ }
253
+ didSet {
254
+ print("[DEBUG:VAR] myVariable changed: \(oldValue) -> \(myVariable)")
255
+ }
256
+ }
257
+ // DEBUG:END
258
+ ```
259
+
260
+ **API Call Logging:**
261
+ ```swift
262
+ // DEBUG:START
263
+ print("[DEBUG:API:REQ] POST /api/users: \(requestBody)")
264
+ // DEBUG:END
265
+
266
+ let response = try await apiService.createUser(requestBody)
267
+
268
+ // DEBUG:START
269
+ print("[DEBUG:API:RES] status=\(response.statusCode), body=\(response.data)")
270
+ // DEBUG:END
271
+ ```
272
+
273
+ **SwiftUI View Logging:**
274
+ ```swift
275
+ // DEBUG:START
276
+ var body: some View {
277
+ VStack {
278
+ // existing content
279
+ }
280
+ .onAppear {
281
+ print("[DEBUG:VIEW] \(type(of: self)) appeared")
282
+ }
283
+ .onDisappear {
284
+ print("[DEBUG:VIEW] \(type(of: self)) disappeared")
285
+ }
286
+ .onChange(of: someState) { oldValue, newValue in
287
+ print("[DEBUG:STATE] someState: \(oldValue) -> \(newValue)")
288
+ }
289
+ }
290
+ // DEBUG:END
291
+ ```
292
+
293
+ **UIKit Lifecycle Logging:**
294
+ ```swift
295
+ // DEBUG:START
296
+ override func viewDidLoad() {
297
+ print("[DEBUG:LIFECYCLE] viewDidLoad: \(type(of: self))")
298
+ super.viewDidLoad()
299
+ }
300
+
301
+ override func viewWillAppear(_ animated: Bool) {
302
+ print("[DEBUG:LIFECYCLE] viewWillAppear: \(type(of: self))")
303
+ super.viewWillAppear(animated)
304
+ }
305
+
306
+ override func viewDidDisappear(_ animated: Bool) {
307
+ print("[DEBUG:LIFECYCLE] viewDidDisappear: \(type(of: self))")
308
+ super.viewDidDisappear(animated)
309
+ }
310
+ // DEBUG:END
311
+ ```
312
+
313
+ ---
314
+
315
+ ### pa:debug-trace "functionName"
316
+
317
+ Add detailed tracing to a specific function:
318
+
319
+ 1. Find the function in codebase
320
+ 2. Add entry log with all parameters
321
+ 3. Add exit log with return value
322
+ 4. Add timing measurement
323
+ 5. Add error catching with stack trace
324
+
325
+ **Example Usage:**
326
+ ```
327
+ pa:debug-trace "processPayment"
328
+ pa:debug-trace "UserService.authenticate"
329
+ pa:debug-trace "handleSubmit"
330
+ ```
331
+
332
+ ---
333
+
334
+ ### pa:debug-var "variableName"
335
+
336
+ Track all changes to a specific variable:
337
+
338
+ 1. Find variable declaration
339
+ 2. Add change tracking
340
+ 3. Log old value, new value, and call stack
341
+ 4. Works with state, props, class properties
342
+
343
+ **Example Usage:**
344
+ ```
345
+ pa:debug-var "isLoading"
346
+ pa:debug-var "user.email"
347
+ pa:debug-var "cartItems"
348
+ ```
349
+
350
+ ---
351
+
352
+ ### pa:debug-api
353
+
354
+ Add logging to all API calls:
355
+
356
+ 1. Find API service/fetch calls
357
+ 2. Add request logging (method, url, headers, body)
358
+ 3. Add response logging (status, data, timing)
359
+ 4. Add error logging with full details
360
+
361
+ ---
362
+
363
+ ### pa:debug-state
364
+
365
+ Add state change logging:
366
+
367
+ **React/React Native:**
368
+ - Wrap useState with logging
369
+ - Add useEffect to track changes
370
+ - Log Redux/Zustand/MobX actions
371
+
372
+ **Android:**
373
+ - Log ViewModel state changes
374
+ - Log LiveData updates
375
+ - Log StateFlow emissions
376
+
377
+ **iOS:**
378
+ - Log @State changes
379
+ - Log @Published property updates
380
+ - Log ObservableObject changes
381
+
382
+ ---
383
+
384
+ ### pa:debug-error
385
+
386
+ Add comprehensive error logging:
387
+
388
+ 1. Wrap code sections in try-catch
389
+ 2. Add error boundaries (React)
390
+ 3. Log error message, stack trace, context
391
+ 4. Add breadcrumb trail for debugging
392
+
393
+ ---
394
+
395
+ ## Web Debugging
396
+
397
+ ### Browser Console Logs
398
+
399
+ **View Console Logs:**
400
+ ```javascript
401
+ // Common log levels
402
+ console.log('Info message');
403
+ console.warn('Warning message');
404
+ console.error('Error message');
405
+ console.debug('Debug message');
406
+ console.info('Info message');
407
+
408
+ // Grouped logs
409
+ console.group('User Auth');
410
+ console.log('Step 1: Validate input');
411
+ console.log('Step 2: API call');
412
+ console.groupEnd();
413
+
414
+ // Table format
415
+ console.table([{name: 'John', age: 30}, {name: 'Jane', age: 25}]);
416
+
417
+ // Time tracking
418
+ console.time('API Call');
419
+ // ... code ...
420
+ console.timeEnd('API Call');
421
+ ```
422
+
423
+ **Debug Patterns to Search:**
424
+ ```
425
+ console.log
426
+ console.warn
427
+ console.error
428
+ console.debug
429
+ debugger
430
+ ```
431
+
432
+ ### Network Debugging
433
+ ```javascript
434
+ // Intercept fetch for debugging
435
+ const originalFetch = window.fetch;
436
+ window.fetch = async (...args) => {
437
+ console.log('Fetch:', args[0]);
438
+ const response = await originalFetch(...args);
439
+ console.log('Response:', response.status);
440
+ return response;
441
+ };
442
+ ```
443
+
444
+ ---
445
+
446
+ ## React Native Debugging
447
+
448
+ ### Metro Bundler Logs
449
+
450
+ **View Metro Logs:**
451
+ ```bash
452
+ # Start Metro with verbose logging
453
+ npx react-native start --verbose
454
+
455
+ # View specific log levels
456
+ npx react-native start --verbose 2>&1 | grep -E "(error|warn)"
457
+ ```
458
+
459
+ ### Device Logs
460
+
461
+ **Console Logs in RN:**
462
+ ```javascript
463
+ // Standard console (appears in Metro)
464
+ console.log('Debug:', data);
465
+ console.warn('Warning:', message);
466
+ console.error('Error:', error);
467
+
468
+ // Conditional logging
469
+ if (__DEV__) {
470
+ console.log('Development only log');
471
+ }
472
+
473
+ // Structured logging
474
+ const logger = {
475
+ debug: (tag, message, data) => {
476
+ if (__DEV__) {
477
+ console.log(`[${tag}]`, message, data || '');
478
+ }
479
+ },
480
+ error: (tag, message, error) => {
481
+ console.error(`[${tag}] ERROR:`, message, error);
482
+ // Could also send to crash reporting
483
+ }
484
+ };
485
+ ```
486
+
487
+ ### React Native Debugger Tools
488
+
489
+ **Flipper (Recommended):**
490
+ ```bash
491
+ # Install Flipper
492
+ brew install --cask flipper
493
+
494
+ # In your app, logs appear automatically
495
+ # Network requests visible in Network tab
496
+ # React DevTools integrated
497
+ ```
498
+
499
+ **Reactotron:**
500
+ ```javascript
501
+ // reactotron.config.js
502
+ import Reactotron from 'reactotron-react-native';
503
+
504
+ Reactotron
505
+ .configure({ name: 'MyApp' })
506
+ .useReactNative({
507
+ networking: { ignoreUrls: /symbolicate/ },
508
+ errors: { veto: (frame) => false },
509
+ })
510
+ .connect();
511
+
512
+ // Usage
513
+ Reactotron.log('Hello');
514
+ Reactotron.warn('Warning');
515
+ Reactotron.error('Error');
516
+ Reactotron.display({
517
+ name: 'API Response',
518
+ value: response,
519
+ preview: 'User data received'
520
+ });
521
+ ```
522
+
523
+ ### ADB Logs for React Native (Android)
524
+ ```bash
525
+ # View all React Native logs
526
+ adb logcat *:S ReactNative:V ReactNativeJS:V
527
+
528
+ # Filter by tag
529
+ adb logcat -s ReactNativeJS
530
+
531
+ # Clear and view fresh logs
532
+ adb logcat -c && adb logcat *:S ReactNativeJS:V
533
+
534
+ # Save to file
535
+ adb logcat -d > rn_logs.txt
536
+ ```
537
+
538
+ ### iOS Simulator Logs for React Native
539
+ ```bash
540
+ # View logs in Terminal
541
+ xcrun simctl spawn booted log stream --predicate 'subsystem == "com.apple.UIKit"'
542
+
543
+ # React Native specific
544
+ xcrun simctl spawn booted log stream | grep -i "react"
545
+
546
+ # Or use Console.app
547
+ # Open Console.app → Select simulator → Filter by process
548
+ ```
549
+
550
+ ---
551
+
552
+ ## Android Native Debugging
553
+
554
+ ### Logcat Commands
555
+
556
+ **Basic Logcat:**
557
+ ```bash
558
+ # View all logs
559
+ adb logcat
560
+
561
+ # Clear logs
562
+ adb logcat -c
563
+
564
+ # View logs with timestamp
565
+ adb logcat -v time
566
+
567
+ # Filter by priority (V, D, I, W, E, F, S)
568
+ adb logcat *:E # Errors only
569
+ adb logcat *:W # Warnings and above
570
+
571
+ # Filter by tag
572
+ adb logcat -s MyApp:D
573
+
574
+ # Multiple tags
575
+ adb logcat -s MyApp:D NetworkManager:I
576
+
577
+ # Exclude tags
578
+ adb logcat MyApp:D *:S
579
+ ```
580
+
581
+ **Advanced Filtering:**
582
+ ```bash
583
+ # Filter by package name
584
+ adb logcat --pid=$(adb shell pidof -s com.myapp)
585
+
586
+ # Filter with grep
587
+ adb logcat | grep -E "(ERROR|CRASH|Exception)"
588
+
589
+ # Save to file
590
+ adb logcat -d > android_logs.txt
591
+
592
+ # Continuous save
593
+ adb logcat > android_logs.txt &
594
+ ```
595
+
596
+ ### Android Log Levels
597
+
598
+ ```kotlin
599
+ // In Kotlin/Java code
600
+ import android.util.Log
601
+
602
+ Log.v("MyApp", "Verbose message") // Lowest priority
603
+ Log.d("MyApp", "Debug message") // Debug
604
+ Log.i("MyApp", "Info message") // Info
605
+ Log.w("MyApp", "Warning message") // Warning
606
+ Log.e("MyApp", "Error message") // Error
607
+ Log.wtf("MyApp", "Assert message") // Critical
608
+
609
+ // With exception
610
+ try {
611
+ // code
612
+ } catch (e: Exception) {
613
+ Log.e("MyApp", "Error occurred", e)
614
+ }
615
+ ```
616
+
617
+ ### Android Studio Logcat
618
+ ```
619
+ 1. Open Android Studio
620
+ 2. View → Tool Windows → Logcat
621
+ 3. Select device/emulator
622
+ 4. Filter by:
623
+ - Package name
624
+ - Log level
625
+ - Custom regex
626
+ ```
627
+
628
+ ### Crashlytics/Firebase Logs
629
+ ```kotlin
630
+ // Add breadcrumb logs
631
+ FirebaseCrashlytics.getInstance().log("User clicked button X")
632
+
633
+ // Set custom keys
634
+ FirebaseCrashlytics.getInstance().setCustomKey("screen", "home")
635
+
636
+ // Record exception
637
+ FirebaseCrashlytics.getInstance().recordException(e)
638
+ ```
639
+
640
+ ---
641
+
642
+ ## iOS Native Debugging
643
+
644
+ ### Xcode Console
645
+
646
+ **View Logs:**
647
+ ```
648
+ 1. Run app from Xcode
649
+ 2. View → Debug Area → Activate Console
650
+ 3. Or: ⌘ + Shift + C
651
+ ```
652
+
653
+ **NSLog / print:**
654
+ ```swift
655
+ // Swift
656
+ print("Debug message") // Basic print
657
+ print("User: \(userName)") // With interpolation
658
+ debugPrint(object) // Detailed output
659
+
660
+ // Objective-C
661
+ NSLog(@"Debug message");
662
+ NSLog(@"User: %@", userName);
663
+ ```
664
+
665
+ ### os_log (Recommended for iOS)
666
+
667
+ ```swift
668
+ import os.log
669
+
670
+ // Create logger
671
+ let logger = Logger(subsystem: "com.myapp", category: "network")
672
+
673
+ // Log levels
674
+ logger.trace("Trace message") // Lowest (not persisted)
675
+ logger.debug("Debug message") // Debug (not persisted in release)
676
+ logger.info("Info message") // Info
677
+ logger.notice("Notice message") // Notice
678
+ logger.warning("Warning message") // Warning
679
+ logger.error("Error message") // Error
680
+ logger.critical("Critical message") // Critical (always persisted)
681
+
682
+ // With formatting
683
+ logger.info("User \(userId, privacy: .private) logged in")
684
+ logger.error("Error code: \(errorCode)")
685
+ ```
686
+
687
+ ### Console.app for iOS
688
+
689
+ ```
690
+ 1. Open Console.app (in Applications/Utilities)
691
+ 2. Select your device or simulator
692
+ 3. Filter by:
693
+ - Process name
694
+ - Subsystem
695
+ - Category
696
+ - Message content
697
+ ```
698
+
699
+ ### iOS Simulator Logs via Terminal
700
+ ```bash
701
+ # Stream logs
702
+ xcrun simctl spawn booted log stream
703
+
704
+ # With predicate
705
+ xcrun simctl spawn booted log stream --predicate 'subsystem == "com.myapp"'
706
+
707
+ # Filter by category
708
+ xcrun simctl spawn booted log stream --predicate 'category == "network"'
709
+
710
+ # Save to file
711
+ xcrun simctl spawn booted log collect --output ~/Desktop/logs.logarchive
712
+ ```
713
+
714
+ ### Device Logs (Physical iOS Device)
715
+ ```bash
716
+ # Using idevicesyslog (install via brew install libimobiledevice)
717
+ idevicesyslog
718
+
719
+ # Filter
720
+ idevicesyslog | grep "MyApp"
721
+
722
+ # Using Xcode
723
+ # Window → Devices and Simulators → Select device → Open Console
724
+ ```
725
+
726
+ ---
727
+
728
+ ## Debug Cleanup Before Production
729
+
730
+ ### Find Debug Statements
731
+
732
+ **Web/React:**
733
+ ```bash
734
+ # Find console.log statements
735
+ grep -rn "console\.\(log\|debug\|warn\)" src/
736
+
737
+ # Find debugger statements
738
+ grep -rn "debugger" src/
739
+
740
+ # Count occurrences
741
+ grep -rc "console\.log" src/ | grep -v ":0$"
742
+ ```
743
+
744
+ **React Native:**
745
+ ```bash
746
+ # Find all debug statements
747
+ grep -rn "console\.\|__DEV__\|debugger" src/
748
+
749
+ # Find Reactotron usage
750
+ grep -rn "Reactotron" src/
751
+ ```
752
+
753
+ **Android (Kotlin/Java):**
754
+ ```bash
755
+ # Find Log statements
756
+ grep -rn "Log\.[vdiwef]" app/src/
757
+
758
+ # Find System.out
759
+ grep -rn "System\.out\.print" app/src/
760
+ ```
761
+
762
+ **iOS (Swift):**
763
+ ```bash
764
+ # Find print/NSLog statements
765
+ grep -rn "print(\|NSLog\|debugPrint" */
766
+
767
+ # Find os_log debug level
768
+ grep -rn "logger\.debug\|logger\.trace" */
769
+ ```
770
+
771
+ ### Auto-Remove Debug Statements
772
+
773
+ **For JavaScript/TypeScript (using eslint):**
774
+ ```json
775
+ // .eslintrc.json
776
+ {
777
+ "rules": {
778
+ "no-console": ["error", { "allow": ["warn", "error"] }],
779
+ "no-debugger": "error"
780
+ }
781
+ }
782
+ ```
783
+
784
+ **Babel Plugin (strips in production):**
785
+ ```javascript
786
+ // babel.config.js
787
+ module.exports = {
788
+ presets: ['module:metro-react-native-babel-preset'],
789
+ env: {
790
+ production: {
791
+ plugins: ['transform-remove-console']
792
+ }
793
+ }
794
+ };
795
+ ```
796
+
797
+ **For Android (ProGuard/R8):**
798
+ ```proguard
799
+ # proguard-rules.pro
800
+ -assumenosideeffects class android.util.Log {
801
+ public static int v(...);
802
+ public static int d(...);
803
+ public static int i(...);
804
+ }
805
+ ```
806
+
807
+ **For iOS (Compiler Flag):**
808
+ ```swift
809
+ // Use #if DEBUG
810
+ #if DEBUG
811
+ print("Debug only message")
812
+ #endif
813
+
814
+ // Or disable in scheme
815
+ // Edit Scheme → Run → Arguments → Add: -DDISABLE_LOGGING
816
+ ```
817
+
818
+ ---
819
+
820
+ ## Structured Logging Pattern
821
+
822
+ ### Universal Logger Implementation
823
+
824
+ **React Native / JavaScript:**
825
+ ```javascript
826
+ // utils/logger.js
827
+ const LOG_LEVELS = {
828
+ DEBUG: 0,
829
+ INFO: 1,
830
+ WARN: 2,
831
+ ERROR: 3,
832
+ NONE: 4
833
+ };
834
+
835
+ class Logger {
836
+ constructor(tag = 'App') {
837
+ this.tag = tag;
838
+ this.level = __DEV__ ? LOG_LEVELS.DEBUG : LOG_LEVELS.WARN;
839
+ }
840
+
841
+ setLevel(level) {
842
+ this.level = level;
843
+ }
844
+
845
+ debug(message, data) {
846
+ if (this.level <= LOG_LEVELS.DEBUG) {
847
+ console.log(`[${this.tag}:DEBUG]`, message, data || '');
848
+ }
849
+ }
850
+
851
+ info(message, data) {
852
+ if (this.level <= LOG_LEVELS.INFO) {
853
+ console.info(`[${this.tag}:INFO]`, message, data || '');
854
+ }
855
+ }
856
+
857
+ warn(message, data) {
858
+ if (this.level <= LOG_LEVELS.WARN) {
859
+ console.warn(`[${this.tag}:WARN]`, message, data || '');
860
+ }
861
+ }
862
+
863
+ error(message, error) {
864
+ if (this.level <= LOG_LEVELS.ERROR) {
865
+ console.error(`[${this.tag}:ERROR]`, message, error || '');
866
+ // Send to crash reporting in production
867
+ if (!__DEV__ && typeof Crashlytics !== 'undefined') {
868
+ Crashlytics.recordError(error);
869
+ }
870
+ }
871
+ }
872
+ }
873
+
874
+ export const logger = new Logger('MyApp');
875
+ export const createLogger = (tag) => new Logger(tag);
876
+ ```
877
+
878
+ **Android (Kotlin):**
879
+ ```kotlin
880
+ // utils/Logger.kt
881
+ object Logger {
882
+ private const val TAG = "MyApp"
883
+ private var isDebugEnabled = BuildConfig.DEBUG
884
+
885
+ fun d(message: String, tag: String = TAG) {
886
+ if (isDebugEnabled) Log.d(tag, message)
887
+ }
888
+
889
+ fun i(message: String, tag: String = TAG) {
890
+ Log.i(tag, message)
891
+ }
892
+
893
+ fun w(message: String, tag: String = TAG) {
894
+ Log.w(tag, message)
895
+ }
896
+
897
+ fun e(message: String, throwable: Throwable? = null, tag: String = TAG) {
898
+ Log.e(tag, message, throwable)
899
+ // Send to Crashlytics in production
900
+ if (!BuildConfig.DEBUG) {
901
+ FirebaseCrashlytics.getInstance().recordException(throwable ?: Exception(message))
902
+ }
903
+ }
904
+ }
905
+ ```
906
+
907
+ **iOS (Swift):**
908
+ ```swift
909
+ // Utils/Logger.swift
910
+ import os.log
911
+
912
+ struct Logger {
913
+ private let subsystem: String
914
+ private let category: String
915
+ private let logger: os.Logger
916
+
917
+ init(category: String, subsystem: String = Bundle.main.bundleIdentifier ?? "com.myapp") {
918
+ self.subsystem = subsystem
919
+ self.category = category
920
+ self.logger = os.Logger(subsystem: subsystem, category: category)
921
+ }
922
+
923
+ func debug(_ message: String) {
924
+ #if DEBUG
925
+ logger.debug("\(message)")
926
+ #endif
927
+ }
928
+
929
+ func info(_ message: String) {
930
+ logger.info("\(message)")
931
+ }
932
+
933
+ func warning(_ message: String) {
934
+ logger.warning("\(message)")
935
+ }
936
+
937
+ func error(_ message: String, error: Error? = nil) {
938
+ logger.error("\(message) - \(error?.localizedDescription ?? "")")
939
+ // Send to Crashlytics in production
940
+ #if !DEBUG
941
+ Crashlytics.crashlytics().record(error: error ?? NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: message]))
942
+ #endif
943
+ }
944
+ }
945
+
946
+ // Usage
947
+ let networkLogger = Logger(category: "Network")
948
+ networkLogger.debug("Request started")
949
+ ```
950
+
951
+ ---
952
+
953
+ ## CRITICAL: AI Must Check Logs Itself
954
+
955
+ **NEVER tell user to "check the logs" or "look for X in console".**
956
+
957
+ The AI MUST:
958
+ 1. **RUN** the log viewing commands itself
959
+ 2. **CAPTURE** the output
960
+ 3. **ANALYZE** the results
961
+ 4. **REPORT** findings to user
962
+
963
+ ### WRONG (Passive):
964
+ ```
965
+ "Run the app and check Metro console for the logs.
966
+ Look for: === DEBUG === in the output.
967
+ Let me know what you see."
968
+ ```
969
+
970
+ ### RIGHT (Active):
971
+ ```
972
+ Let me capture the logs and analyze them.
973
+
974
+ [AI runs: adb logcat -d | grep -i "DEBUG\|ERROR" ]
975
+
976
+ Found in logs:
977
+ - ERROR at line 45: area_allow_in_schedule is undefined
978
+ - API response missing expected field
979
+ - Root cause: Backend not returning area_allow_in_schedule
980
+
981
+ Fix: Add fallback in CLA API handler...
982
+ ```
983
+
984
+ ---
985
+
986
+ ## pa:debug Workflow
987
+
988
+ ### When AI receives `pa:debug`:
989
+
990
+ 1. **Detect Platform:**
991
+ ```
992
+ Check project type:
993
+ - package.json with react-native → React Native
994
+ - build.gradle → Android Native
995
+ - *.xcodeproj → iOS Native
996
+ - package.json with web framework → Web
997
+ ```
998
+
999
+ 2. **Identify Debug Issue:**
1000
+ - Read error from user description
1001
+ - Check recent git changes
1002
+ - Look for crash reports in project
1003
+
1004
+ 3. **RUN Log Commands (AI executes these):**
1005
+
1006
+ **React Native:**
1007
+ ```bash
1008
+ # AI runs this and captures output
1009
+ adb logcat -d *:S ReactNativeJS:V | tail -100
1010
+ ```
1011
+
1012
+ **Android Native:**
1013
+ ```bash
1014
+ # AI runs this and captures output
1015
+ adb logcat -d -s MyApp:D | tail -100
1016
+ ```
1017
+
1018
+ **iOS (if accessible):**
1019
+ ```bash
1020
+ # AI runs this and captures output
1021
+ xcrun simctl spawn booted log show --last 5m | grep -i "error\|warn\|debug"
1022
+ ```
1023
+
1024
+ 4. **ANALYZE Output:**
1025
+ - Parse log output
1026
+ - Find errors, warnings, exceptions
1027
+ - Identify patterns
1028
+ - Trace execution flow
1029
+
1030
+ 5. **REPORT & FIX:**
1031
+ - Show relevant log entries to user
1032
+ - Explain what the logs mean
1033
+ - Implement the fix directly
1034
+
1035
+ ---
1036
+
1037
+ ## AI Log Capture Commands
1038
+
1039
+ **AI MUST run these commands to capture logs - never ask user to check manually.**
1040
+
1041
+ ### React Native (Android device/emulator)
1042
+ ```bash
1043
+ # Capture recent JS logs
1044
+ adb logcat -d *:S ReactNativeJS:V | tail -200
1045
+
1046
+ # Capture with timestamps
1047
+ adb logcat -d -v time *:S ReactNativeJS:V | tail -200
1048
+
1049
+ # Filter for errors only
1050
+ adb logcat -d *:S ReactNativeJS:V | grep -i "error\|exception\|fail"
1051
+
1052
+ # Filter for specific tag
1053
+ adb logcat -d | grep -i "CLA\|area_allow"
1054
+ ```
1055
+
1056
+ ### React Native (iOS Simulator)
1057
+ ```bash
1058
+ # Recent logs
1059
+ xcrun simctl spawn booted log show --last 5m --predicate 'subsystem CONTAINS "react"' 2>/dev/null | tail -200
1060
+
1061
+ # Or use system log
1062
+ log show --last 5m --predicate 'process == "YourAppName"' | tail -200
1063
+ ```
1064
+
1065
+ ### Android Native
1066
+ ```bash
1067
+ # App logs
1068
+ adb logcat -d -s MyApp:D | tail -200
1069
+
1070
+ # All errors
1071
+ adb logcat -d *:E | tail -100
1072
+
1073
+ # Specific search
1074
+ adb logcat -d | grep -i "your_search_term"
1075
+ ```
1076
+
1077
+ ### iOS Native
1078
+ ```bash
1079
+ # Simulator logs
1080
+ xcrun simctl spawn booted log show --last 5m | grep -i "error\|warn" | tail -100
1081
+
1082
+ # Device logs (if connected)
1083
+ idevicesyslog 2>/dev/null | head -200
1084
+ ```
1085
+
1086
+ ### Web (Node.js backend logs)
1087
+ ```bash
1088
+ # If running in background, check pm2/docker logs
1089
+ pm2 logs --lines 100 2>/dev/null || docker logs app --tail 100 2>/dev/null
1090
+
1091
+ # Check log files
1092
+ tail -100 logs/error.log 2>/dev/null
1093
+ ```
1094
+
1095
+ ---
1096
+
1097
+ ## Command Quick Reference
1098
+
1099
+ | Platform | AI Runs | Filter | Clear | Export |
1100
+ |----------|---------|--------|-------|--------|
1101
+ | **React Native** | `adb logcat -d *:S ReactNativeJS:V` | `\| grep "term"` | `adb logcat -c` | `> file.txt` |
1102
+ | **Android** | `adb logcat -d -s TAG:D` | `\| grep "term"` | `adb logcat -c` | `> file.txt` |
1103
+ | **iOS Sim** | `xcrun simctl spawn booted log show` | `--predicate` | N/A | `log collect` |
1104
+ | **Node.js** | `pm2 logs` or `docker logs` | `\| grep "term"` | N/A | `> file.txt` |
1105
+
1106
+ ---
1107
+
1108
+ ## Output Format
1109
+
1110
+ ```
1111
+ Debug Session
1112
+ ═════════════
1113
+ Platform: [detected platform]
1114
+ Issue: [user's issue description]
1115
+
1116
+ Log Analysis
1117
+ ────────────
1118
+ Recent Errors:
1119
+ • [timestamp] [level] [message]
1120
+ • [timestamp] [level] [message]
1121
+
1122
+ Pattern Detected:
1123
+ [description of error pattern]
1124
+
1125
+ Suggested Fix:
1126
+ [specific fix based on log analysis]
1127
+
1128
+ Debug Commands:
1129
+ [platform-specific commands to run]
1130
+ ```