forked from FastLED/FastLED
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path.cursorrules
More file actions
2683 lines (2111 loc) · 98.8 KB
/
.cursorrules
File metadata and controls
2683 lines (2111 loc) · 98.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# FastLED Project Rules for Cursor
## 🚨 CRITICAL: PYTHON EXECUTION REQUIREMENTS - NO EXCEPTIONS! 🚨
### MANDATORY COMMAND EXECUTION RULES - ALL AGENTS MUST FOLLOW
**🚨 ABSOLUTELY FORBIDDEN: Direct python/python3 execution**
- ❌ **NEVER use:** `python3 <command>`
- ❌ **NEVER use:** `python <command>`
- ❌ **NEVER use:** `./python`
- ❌ **NEVER use:** Direct Python interpreter calls
**✅ MANDATORY: Always use uv run**
- ✅ **ALWAYS use:** `uv run python <command>`
- ✅ **ALWAYS use:** `uv run python -c "..."`
- ✅ **ALWAYS use:** `uv run python script.py`
**NO EXCEPTIONS - ALL PYTHON CODE MUST RUN THROUGH UV:**
```bash
# ✅ CORRECT - Use uv run python
uv run python test.py
uv run python ci/ci-compile.py uno --examples Blink
uv run python -c "from ci.ci.module import func; func()"
uv run python ci/ci/build_info_analyzer.py --board uno --show-defines
# ❌ FORBIDDEN - Direct python execution
python3 test.py # NO!
python ci/ci-compile.py # NO!
python3 -c "import something" # NO!
python3 script.py # NO!
```
**THIS RULE APPLIES TO:**
- 🚨 **All test execution**
- 🚨 **All script execution**
- 🚨 **All build commands**
- 🚨 **All analysis tools**
- 🚨 **All development commands**
- 🚨 **ALL Python code execution without exception**
**WHY:** The project uses UV for dependency management and execution environment. Direct python3 calls bypass the controlled environment and may use wrong Python versions or missing dependencies.
**ENFORCEMENT:** Any agent using direct python3/python commands is in violation of project requirements.
### 🚨 UV RUN MANDATE - FINAL WARNING 🚨
**IF YOU SEE ANY COMMANDS IN THIS PROJECT DOCUMENTATION THAT USE `python3` OR `python` DIRECTLY:**
1. **🚫 DO NOT COPY THEM** - They are legacy commands that must be updated
2. **✅ ALWAYS REPLACE** `python3` with `uv run python`
3. **✅ ALWAYS REPLACE** `python` with `uv run python`
4. **📝 UPDATE DOCUMENTATION** when you find python3 commands
**EXAMPLES OF MANDATORY REPLACEMENTS:**
```bash
# ❌ If you see this in docs (WRONG):
python3 script.py
# ✅ Always use this instead (CORRECT):
uv run python script.py
# ❌ If you see this in docs (WRONG):
python -c "import something"
# ✅ Always use this instead (CORRECT):
uv run python -c "import something"
```
**UV RUN IS NOT OPTIONAL - IT IS MANDATORY FOR ALL PYTHON EXECUTION.**
## 🚨 CRITICAL: NO DEFAULT VALUES POLICY 🚨
### MANDATORY: Explicit Parameter Policy - NO DEFAULTS ALLOWED
**🚨 ABSOLUTELY FORBIDDEN: Default values in dataclasses and function parameters**
**❌ NEVER USE DEFAULT VALUES:**
- Function parameters with defaults
- Dataclass fields with default values
- Method parameters with defaults
- Optional parameters with fallback values
**✅ ALWAYS REQUIRE EXPLICIT VALUES:**
- All function parameters must be explicitly provided by caller
- All dataclass fields must be explicitly specified
- Use Optional types for truly optional parameters, but no defaults
- Force callers to handle every parameter consciously
**WHY NO DEFAULTS:**
- **Signature changes break compilation** - Adding/removing parameters forces all callers to update
- **Prevents silent bugs** - Missing parameter updates become compile-time errors
- **Explicit intent** - Every call site shows exactly what values are being passed
- **Refactoring safety** - Internal changes are caught immediately by type checker
- **Code clarity** - No hidden behavior from default values
**EXAMPLES:**
```python
# ❌ FORBIDDEN - Default values hide signature changes
@dataclass
class Config:
name: str = "default"
enabled: bool = True
timeout: int = 30
def process_data(data: bytes, validate: bool = True, timeout: int = 30):
pass
# ✅ CORRECT - Explicit values required
@dataclass
class Config:
name: str
enabled: bool
timeout: int
def process_data(data: bytes, validate: bool, timeout: int):
pass
# Usage requires all parameters
config = Config(name="test", enabled=True, timeout=60)
process_data(data=my_data, validate=False, timeout=30)
```
**BENEFITS:**
- **Immediate feedback** when function signatures change
- **No silent failures** from missed parameter updates
- **Self-documenting code** - all parameters visible at call sites
- **Safer refactoring** - type checker catches all usage sites
- **Consistent behavior** - no surprising default value interactions
**EXCEPTIONS (Use Sparingly):**
- Constructor overloads where defaults truly make sense for usability
- Public API methods where backwards compatibility is critical
- BUT: Internal/private functions should NEVER have defaults
**ENFORCEMENT:**
This policy should be enforced by linters and code review. Adding defaults to existing code without explicit justification is not allowed.
## 🚨 CRITICAL: STRICT ENVIRONMENT HANDLING - NO SILENT FAILURES 🚨
### MANDATORY: Fail Fast on Missing Environment Dependencies - NO EXCEPTIONS
**🚨 ABSOLUTELY FORBIDDEN: Silent fallbacks for missing critical resources**
**❌ NEVER DO SILENT FALLBACKS:**
- Missing configuration files → throw error, don't use defaults
- Missing environment variables → throw error, don't substitute defaults
- Missing build flags → throw error, don't continue with partial config
- Missing required paths → throw error, don't create alternatives
- Missing dependencies → throw error, don't skip functionality
**✅ ALWAYS FAIL FAST AND EXPLICIT:**
- Throw descriptive RuntimeError/ValueError for missing resources
- Include the expected path/location in error message
- Explain why the resource is required
- Provide clear instructions for fixing the issue
- Use explicit checks before proceeding with operations
**WHY NO SILENT FALLBACKS:**
- **Hidden failures** - Silent fallbacks mask configuration problems
- **Inconsistent behavior** - Code works differently in different environments
- **Hard to debug** - Missing configs cause subtle bugs hours later
- **Security risks** - Default values may be insecure or inappropriate
- **Configuration drift** - Systems diverge silently when configs are missing
**EXAMPLES:**
```python
# ❌ FORBIDDEN - Silent fallback hides missing config
def load_config(config_path: str) -> Dict[str, Any]:
try:
with open(config_path) as f:
return json.load(f)
except FileNotFoundError:
print(f"Warning: {config_path} not found, using defaults")
return {"timeout": 30, "retries": 3} # BAD: Silent defaults
# ✅ CORRECT - Fail fast with clear error
def load_config(config_path: str) -> Dict[str, Any]:
try:
with open(config_path) as f:
return json.load(f)
except FileNotFoundError:
raise RuntimeError(
f"CRITICAL: Configuration file not found at {config_path}. "
f"This file is required for proper operation. "
f"Please ensure the file exists and is readable."
)
# ❌ FORBIDDEN - Silent environment variable fallback
def get_build_dir() -> str:
return os.environ.get("BUILD_DIR", "/tmp/default") # BAD: Hidden default
# ✅ CORRECT - Explicit environment requirement
def get_build_dir() -> str:
build_dir = os.environ.get("BUILD_DIR")
if not build_dir:
raise RuntimeError(
"CRITICAL: BUILD_DIR environment variable is required but not set. "
"Please set BUILD_DIR to the target build directory."
)
return build_dir
```
**STRICT ENFORCEMENT AREAS:**
- **Build configuration files** (build_flags.toml, CMakeLists.txt, etc.)
- **Environment variables** required for compilation/testing
- **Tool dependencies** (compilers, archivers, etc.)
- **Input file paths** passed as parameters
- **Required directories** for output/temporary files
**RARE EXCEPTIONS (Require Explicit Justification):**
- User-facing CLI tools where missing optional config is acceptable
- Graceful degradation for non-critical features only
- BUT: Core build/compilation functionality must NEVER have silent fallbacks
**ERROR MESSAGE REQUIREMENTS:**
- Start with "CRITICAL:" prefix for build/config errors
- Include the exact path/variable name that was expected
- Explain what the missing resource is used for
- Provide actionable steps to fix the issue
**ENFORCEMENT:**
Any function that silently handles missing critical resources without throwing an explicit error is in violation of project requirements. Code review must catch and reject such patterns.
## Cursor Configuration
### Post-Change Hooks
Run linting after every code change:
```yaml
post_change_hooks:
- command: "bash lint"
description: "Run code formatting and linting"
working_directory: "."
```
## MCP Server Configuration
This project includes a custom MCP server (`mcp_server.py`) that provides tools for:
- Running tests with various options
- Compiling examples for different platforms
- Code fingerprinting and change detection
- Linting and formatting
- Project information and status
- **Build info analysis for platform-specific defines, compiler flags, and toolchain information**
- **Symbol analysis for binary optimization (all platforms)**
- Stack trace setup for enhanced debugging
- **🌐 FastLED Web Compiler with Playwright (FOREGROUND AGENTS ONLY)**
- **🚨 CRITICAL: `validate_completion` tool for background agents**
To use the MCP server, run: `uv run mcp_server.py`
**BACKGROUND AGENTS:** The MCP server includes a mandatory `validate_completion` tool that MUST be used before indicating task completion. This tool runs `bash test` and ensures all tests pass.
### FastLED Web Compiler (FOREGROUND AGENTS ONLY)
**🌐 FOR INTERACTIVE DEVELOPMENT:** The MCP server includes a `run_fastled_web_compiler` tool that:
**Note:** For direct command-line WASM compilation, see the **WASM Sketch Compilation** section below.
- **Compiles Arduino sketches to WASM** for browser execution
- **Captures console.log output** with playwright automation
- **Takes screenshots** of running visualizations
- **Monitors FastLED_onFrame calls** to verify proper initialization
- **Provides detailed analysis** of errors and performance
**PREREQUISITES:**
- `pip install fastled` - FastLED web compiler
- `pip install playwright` - Browser automation (included in pyproject.toml)
- Docker (optional, for faster compilation)
**USAGE EXAMPLES:**
```python
# Via MCP Server - Basic usage
use run_fastled_web_compiler tool with:
- example_path: "examples/Audio"
- capture_duration: 30
- headless: false
- save_screenshot: true
# Via MCP Server - Different examples
use run_fastled_web_compiler tool with:
- example_path: "examples/Blink"
- capture_duration: 15
- headless: true
# Via MCP Server - Quick test
use run_fastled_web_compiler tool with:
- example_path: "examples/wasm"
- capture_duration: 10
```
**KEY FEATURES:**
- **Automatic browser installation:** Installs Chromium via playwright
- **Console.log capture:** Records all browser console output with timestamps
- **Error detection:** Identifies compilation failures and runtime errors
- **FastLED monitoring:** Tracks `FastLED_onFrame` calls to verify functionality
- **Screenshot capture:** Saves visualization images with timestamps
- **Docker detection:** Checks for Docker availability for faster builds
- **Background agent protection:** Automatically disabled for CI/background environments
**🚫 BACKGROUND AGENT RESTRICTION:**
This tool is **COMPLETELY DISABLED** for background agents and CI environments. Background agents attempting to use this tool will receive an error message. This is intentional to prevent:
- Hanging processes in automated environments
- Resource conflicts in CI/CD pipelines
- Interactive browser windows in headless environments
**CONSOLE.LOG CAPTURE PATTERN:**
The tool follows the pattern established in `ci/wasm_test.py` and `ci/ci/scrapers/`:
```javascript
// Example captured console.log patterns:
[14:25:30] log: FastLED_onFrame called: {"frame":1,"leds":100}
[14:25:30] log: Audio worklet initialized
[14:25:31] error: Missing audio_worklet_processor.js
[14:25:31] warning: WebGL context lost
```
**INTEGRATION WITH EXISTING CI:**
- Complements existing `ci/wasm_test.py` functionality
- Uses same playwright patterns as `ci/ci/scrapers/`
- Leverages existing pyproject.toml dependencies
- Compatible with existing Docker-based compilation workflow
## Project Structure
- `src/` - Main FastLED library source code
- `examples/` - Arduino examples demonstrating FastLED usage
- `tests/` - Test files and infrastructure
- `ci/` - Continuous integration scripts
- `docs/` - Documentation
## Key Commands
- `uv run test.py` - Run all tests
- `uv run test.py --cpp` - Run C++ tests only
- `uv run test.py TestName` - Run specific C++ test
- For example: running test_xypath.cpp would be uv run test.py xypath
- `./lint` - Run code formatting/linting
- `uv run ci/ci-compile.py uno --examples Blink` - Compile examples for specific platform
- For example (uno): `uv run ci/ci-compile.py uno --examples Blink`
- For example (esp32dev): `uv run ci/ci-compile.py esp32dev --examples Blink`
- For example (esp8266): `uv run ci/ci-compile.py esp8266 --examples Blink`
- For example (teensy31): `uv run ci/ci-compile.py teensy31 --examples Blink`
- **WASM Compilation** - Compile Arduino sketches to run in web browsers:
- `uv run ci/wasm_compile.py examples/Blink -b --open` - Compile Blink to WASM and open browser
- `uv run ci/wasm_compile.py path/to/your/sketch -b --open` - Compile any sketch to WASM
- **Symbol Analysis** - Analyze binary size and optimization opportunities:
- `uv run ci/ci/symbol_analysis.py --board uno` - Analyze UNO platform
- `uv run ci/ci/symbol_analysis.py --board esp32dev` - Analyze ESP32 platform
- `uv run ci/demo_symbol_analysis.py` - Analyze all available platforms
## 🤖 AI AGENT LINTING GUIDELINES
### FOREGROUND AGENTS (Interactive Development)
**🚨 ALWAYS USE `bash lint` - DO NOT RUN INDIVIDUAL LINTING SCRIPTS**
- **✅ CORRECT:** `bash lint`
- **❌ FORBIDDEN:** `./lint-js`, `./check-js`, `uv run python scripts/enhance-js-typing.py`
- **❌ FORBIDDEN:** `uv run ruff check`, `uv run black`, individual tools
**WHY:** `bash lint` provides:
- **Comprehensive coverage** - Python, C++, JavaScript, and enhancement analysis
- **Consistent workflow** - Single command for all linting needs
- **Proper sequencing** - Runs tools in the correct order with dependencies
- **Clear output** - Organized sections showing what's being checked
- **Agent guidance** - Shows proper usage for AI agents
### BACKGROUND AGENTS (Automated/CI Environments)
**CAN USE FINE-GRAINED LINTING FOR SPECIFIC NEEDS**
Background agents may use individual linting scripts when needed:
- `./lint-js` - JavaScript-only linting
- `./check-js` - JavaScript type checking
- `uv run python scripts/enhance-js-typing.py` - JavaScript enhancement analysis
- `uv run ruff check` - Python linting only
- MCP server `lint_code` tool - Programmatic access
**BUT STILL PREFER `bash lint` FOR COMPREHENSIVE CHECKING**
### Linting Script Integration
The `bash lint` command now includes:
1. **📝 Python Linting** - ruff, black, isort, pyright
2. **🔧 C++ Linting** - clang-format (when enabled)
3. **🌐 JavaScript Linting** - Deno lint, format check, type checking
4. **🔍 JavaScript Enhancement** - Analysis and recommendations
5. **💡 AI Agent Guidance** - Clear instructions for proper usage
### When to Use Individual Scripts
**FOREGROUND AGENTS:** Never. Always use `bash lint`.
**BACKGROUND AGENTS:** Only when:
- **Debugging specific issues** with one language/tool
- **Testing incremental changes** to linting configuration
- **Running targeted analysis** for specific files
- **Integrating with automated workflows** via MCP server
## Development Guidelines
- Follow existing code style and patterns
- Run tests before committing changes
- Use the MCP server tools for common tasks
- Check examples when making API changes
## 🚨 CRITICAL: .INO FILE CREATION RULES 🚨
### ⚠️ THINK BEFORE CREATING .INO FILES ⚠️
**.ino files should be created SPARINGLY and ONLY when truly justified.**
### 🚫 WHEN NOT TO CREATE .INO FILES:
- **Testing minor code changes** - Use existing test files or unit tests
- **Quick API validation** - Use unit tests or modify existing examples
- **Debugging specific functions** - Use test files, not new sketches
- **One-off experiments** - Create temporary test files instead
- **Small feature tests** - Extend existing relevant examples
### ✅ WHEN TO CREATE .INO FILES:
#### 1. **Temporary Testing (.ino)**
**Use Pattern:** `temp_<feature>.ino` or `test_<api>.ino`
```cpp
// temp_json_api.ino - Testing new JSON fetch functionality
// test_networking.ino - Validating network stack changes
```
- ✅ **FOR:** Testing new APIs during development
- ✅ **FOR:** Quick prototyping and validation
- ✅ **DELETE AFTER USE** - These are temporary by design
#### 2. **Significant New Feature Examples**
**Use Pattern:** `examples/<FeatureName>/<FeatureName>.ino`
```cpp
// examples/JsonFetchApi/JsonFetchApi.ino - Comprehensive JSON API example
// examples/NetworkStack/NetworkStack.ino - Major networking features
```
- ✅ **FOR:** Large, comprehensive new features
- ✅ **FOR:** APIs that warrant dedicated examples
- ✅ **FOR:** Features that users will commonly implement
- ✅ **PERMANENT** - These become part of the example library
### 📋 CREATION CHECKLIST:
**Before creating ANY .ino file, ask:**
1. **🤔 Is this testing a new API?**
- YES → Create `temp_<name>.ino`, delete after testing
- NO → Consider alternatives
2. **🤔 Is this a significant new feature that users will commonly use?**
- YES → Create `examples/<FeatureName>/<FeatureName>.ino`
- NO → Use existing examples or test files
3. **🤔 Can I modify an existing example instead?**
- YES → Extend existing example rather than creating new
- NO → Proceed with creation
4. **🤔 Is this just for debugging/validation?**
- YES → Use unit tests or temporary test files
- NO → Consider if it meets the "significant feature" criteria
### 🔍 REVIEW CRITERIA:
**For Feature Examples (.ino files that stay):**
- ✅ **Demonstrates complete, real-world usage patterns**
- ✅ **Covers multiple aspects of the feature comprehensively**
- ✅ **Provides educational value for users**
- ✅ **Shows best practices and common use cases**
- ✅ **Is likely to be referenced by multiple users**
**For Temporary Testing (.ino files that get deleted):**
- ✅ **Clearly named as temporary (temp_*, test_*)**
- ✅ **Focused on specific API validation**
- ✅ **Will be deleted after development cycle**
- ✅ **Too complex for unit test framework**
### ❌ EXAMPLES OF WHAT NOT TO CREATE:
- `test_basic_led.ino` - Use existing Blink example
- `debug_colors.ino` - Use existing ColorPalette example
- `quick_brightness.ino` - Use unit tests or modify existing example
- `validate_pins.ino` - Use PinTest example or unit tests
### ✅ EXAMPLES OF JUSTIFIED CREATIONS:
- `temp_new_wifi_api.ino` - Testing major new WiFi functionality (temporary)
- `examples/MachineLearning/MachineLearning.ino` - New ML integration feature (permanent)
- `temp_performance_test.ino` - Validating optimization changes (temporary)
### 🧹 CLEANUP RESPONSIBILITY:
- **Temporary files:** Creator must delete when testing is complete
- **Feature examples:** Must be maintained and updated as API evolves
- **Abandoned files:** Regular cleanup reviews to remove unused examples
**Remember: The examples directory is user-facing documentation. Every .ino file should provide clear value to FastLED users.**
### Memory Management with Smart Pointers and Moveable Objects
**🚨 CRITICAL: Always use proper RAII patterns - smart pointers, moveable objects, or wrapper classes instead of raw pointers for resource management.**
**Resource Management Options:**
- ✅ **PREFERRED**: `fl::shared_ptr<T>` for shared ownership (multiple references to same object)
- ✅ **PREFERRED**: `fl::unique_ptr<T>` for exclusive ownership (single owner, automatic cleanup)
- ✅ **PREFERRED**: Moveable wrapper objects (like `fl::promise<T>`) for safe copying and transferring of unique resources
- ✅ **ACCEPTABLE**: `fl::vector<T>` storing objects by value when objects support move/copy semantics
- ❌ **AVOID**: `fl::vector<T*>` storing raw pointers - use `fl::vector<fl::shared_ptr<T>>` or `fl::vector<fl::unique_ptr<T>>`
- ❌ **AVOID**: Manual `new`/`delete` - use `fl::make_shared<T>()` or `fl::make_unique<T>()`
**Moveable Wrapper Pattern:**
When you have a unique resource (like a future, file handle, or network connection) that needs to be passed around easily, create a moveable wrapper class that:
- Internally manages the unique resource (often with `fl::unique_ptr<T>` or similar)
- Provides copy semantics through shared implementation details
- Maintains clear ownership semantics
- Allows safe transfer between contexts
**Examples:**
```cpp
// ✅ GOOD - Using smart pointers
fl::vector<fl::shared_ptr<HttpClient>> mActiveClients;
auto client = fl::make_shared<HttpClient>();
mActiveClients.push_back(client);
// ✅ GOOD - Using unique_ptr for exclusive ownership
fl::unique_ptr<HttpClient> client = fl::make_unique<HttpClient>();
// ✅ GOOD - Moveable wrapper objects (fl::promise example)
fl::vector<fl::promise<Response>> mActivePromises; // Copyable wrapper around unique future
fl::promise<Response> promise = fetch.get(url).execute();
mActivePromises.push_back(promise); // Safe copy, shared internal state
// ✅ GOOD - Objects stored by value (if copyable/moveable)
fl::vector<Request> mRequests; // When Request supports copy/move
// ❌ BAD - Raw pointers require manual memory management
fl::vector<Promise*> mActivePromises; // Memory leaks possible
Promise* promise = new Promise(); // Who calls delete?
```
**fl::promise<T> as Moveable Wrapper Example:**
```cpp
// fl::promise<T> wraps a unique fl::future<T> but provides copyable semantics
class promise<T> {
fl::shared_ptr<future<T>> mImpl; // Shared wrapper around unique resource
public:
promise(const promise& other) : mImpl(other.mImpl) {} // Safe copying
promise(promise&& other) : mImpl(fl::move(other.mImpl)) {} // Move support
// ... wrapper delegates to internal future
};
// Usage - can be copied and passed around safely
fl::promise<Response> promise = http_get_promise("https://api.example.com");
someContainer.push_back(promise); // Copy is safe
processAsync(promise); // Can pass to multiple places
```
**Why This Pattern:**
- **Automatic cleanup** - No memory leaks from forgotten `delete` calls
- **Exception safety** - Resources automatically freed even if exceptions occur
- **Clear ownership** - Code clearly shows who owns what objects
- **Thread safety** - Smart pointers provide atomic reference counting
- **Easy sharing** - Moveable wrappers allow safe copying of unique resources
- **API flexibility** - Can pass resources between different contexts safely
## 🚨 CRITICAL REQUIREMENTS FOR ALL AGENTS (FOREGROUND & BACKGROUND) 🚨
## 🚨 MANDATORY COMMAND EXECUTION RULES 🚨
### FOREGROUND AGENTS (Interactive Development)
**FOREGROUND AGENTS MUST FOLLOW THESE COMMAND EXECUTION PATTERNS:**
#### Python Code Execution:
- ❌ **NEVER run Python code directly**
- ❌ **NEVER cd to subdirectories like ci/ - ALWAYS stay in project root**
- ✅ **ALWAYS create/modify tmp.py** with your code
- ✅ **ALWAYS run: `uv run python tmp.py`** (use full `uv run python`, not just `python`)
- ✅ **ALWAYS use correct import paths: `from ci.ci.module` for ci.ci modules, `from ci.module` for top-level ci modules**
#### Shell Command Execution:
- ❌ **NEVER run shell commands directly**
- ❌ **NEVER cd to subdirectories** - commands should work from project root
- ✅ **ALWAYS create/modify tmp.sh** with your commands
- ✅ **ALWAYS run: `bash tmp.sh`**
#### Command Execution Examples:
**Python Code Pattern:**
```python
# tmp.py (created in project root, NOT in subdirectories)
from ci.ci.clang_compiler import Compiler # CORRECT import path for ci.ci modules
import subprocess
result = subprocess.run(['git', 'status'], capture_output=True, text=True)
print(result.stdout)
```
Then run: `uv run python tmp.py` (from project root)
**Shell Commands Pattern:**
```bash
# tmp.sh (created in project root)
#!/bin/bash
git status
ls -la
uv run ci/ci-compile.py uno --examples Blink # Use full paths from root
```
Then run: `bash tmp.sh` (from project root)
### BACKGROUND AGENTS (Automated/CI Environments)
**BACKGROUND AGENTS MUST FOLLOW THESE RESTRICTED COMMAND EXECUTION PATTERNS:**
#### Python Code Execution:
- ❌ **NEVER run Python code directly**
- ❌ **NEVER create/use tmp.py files** (forbidden for background agents)
- ❌ **NEVER cd to subdirectories like ci/ - ALWAYS stay in project root**
- ✅ **ALWAYS use `uv run python` with existing scripts** (e.g., `uv run python test.py`, `uv run python ci/ci-compile.py`)
- ✅ **ALWAYS use correct import paths: `from ci.ci.module` for ci.ci modules, `from ci.module` for top-level ci modules** when testing
- ✅ **ALWAYS use MCP server tools** for programmatic operations when available
#### Shell Command Execution:
- ❌ **NEVER run shell commands directly**
- ❌ **NEVER create/use tmp.sh files** (forbidden for background agents)
- ❌ **NEVER cd to subdirectories** - commands should work from project root
- ✅ **ALWAYS use existing bash scripts** (e.g., `bash test`, `bash lint`)
- ✅ **ALWAYS use `uv run python` for Python scripts** with proper arguments from project root
- ✅ **ALWAYS use MCP server tools** for complex operations when available
#### Background Agent Command Examples:
**✅ ALLOWED - Using existing scripts from project root:**
```bash
bash test
bash lint
uv run python test.py audio_json_parsing
uv run python ci/ci-compile.py uno --examples Blink
```
**❌ FORBIDDEN - Creating temporary files:**
```bash
# DON'T DO THIS - tmp.sh is forbidden for background agents
echo "git status" > tmp.sh
bash tmp.sh
```
**✅ PREFERRED - Using MCP server tools:**
```bash
uv run python mcp_server.py
# Then use appropriate MCP tools like: validate_completion, symbol_analysis, etc.
```
### 🚨 CRITICAL CORRECTIONS FROM USER FEEDBACK 🚨
**These corrections were identified through direct user feedback and MUST be followed:**
#### 1. **Always Use `uv run python` - NEVER just `python` or `uv run`**
- ❌ **WRONG**: `python -c "..."`
- ❌ **WRONG**: `uv run -c "..."`
- ✅ **CORRECT**: `uv run python -c "..."`
#### 2. **Correct Import Paths - Use Appropriate Module Structure**
- ✅ **CORRECT**: `from ci.ci.clang_compiler import ...` (for ci.ci modules)
- ✅ **CORRECT**: `from ci.clang_compiler import ...` (for top-level ci modules, if they exist)
#### 3. **Never Change Directory - Always Work from Project Root**
- ❌ **WRONG**: `cd ci && python ...`
- ❌ **WRONG**: `cd ci/ci && python ...`
- ✅ **CORRECT**: Stay in project root, use full paths: `uv run python ci/script.py`
#### 4. **Testing Commands Must Use Correct Format**
- ❌ **WRONG**: `python -c "from ci.ci.module import func; func()"` (missing uv run python)
- ✅ **CORRECT**: `uv run python -c "from ci.ci.module import func; func()"` (for ci.ci modules)
**Example of CORRECT Command Pattern:**
```bash
# From project root directory
uv run python -c "from ci.ci.clang_compiler import detect_linker; print('Linker:', detect_linker())"
```
**These patterns were corrected through direct user feedback and must be followed exactly.**
### DELETE Operations - DANGER ZONE (ALL AGENTS):
- 🚨 **STOP and ask for permission** before ANY delete operations
- ✅ **EXCEPTION:** Single files that you just created are OK to delete
- ❌ **NEVER delete multiple files** without explicit permission
- ❌ **NEVER delete directories** without explicit permission
- ❌ **NEVER delete system files or project files** without permission
### Git-Bash Terminal Truncation Issue
**🚨 IMPORTANT: Git-Bash terminal may truncate the first character of commands**
**Problem:** The git-bash terminal on Windows sometimes truncates the first character of commands, causing them to fail or execute incorrectly.
**Solution:** Pre-pend commands with an additional space when using git-bash:
- ✅ **CORRECT**: ` bash test` (note the leading space)
- ❌ **INCORRECT**: `bash test` (may get truncated to `ash test`)
**Examples:**
```bash
# Good - with leading space for git-bash compatibility
bash test
uv run python test.py
bash lint
# Bad - may get truncated in git-bash
bash test
uv run python test.py
bash lint
```
**Why:** This ensures commands work reliably across all terminal environments, especially git-bash on Windows systems.
### Why These Rules Exist:
- **Ensures all operations are reviewable and traceable**
- **Prevents accidental destructive operations in automated environments**
- **Allows for better debugging and error handling**
- **Maintains consistency across different agent types**
- **Provides audit trail for all system modifications**
- **Prevents background agents from creating unnecessary temporary files**
### 📋 QUICK REFERENCE: CORRECTED COMMAND PATTERNS
**User-Corrected Patterns (MANDATORY):**
✅ **Python Testing**: `uv run python -c "from ci.module import func; func()"`
✅ **Script Execution**: `uv run python ci/script.py` (from project root)
✅ **Import Paths**: `from ci.clang_compiler import ...` (NOT `ci.ci.clang_compiler`)
✅ **Working Directory**: Always stay in project root - never cd to subdirectories
✅ **Git-Bash**: Use leading space: ` uv run python test.py`
❌ **Never Do**: cd to ci/, python directly, wrong import paths, uv run without python
**These command execution rules apply to ALL operations including but not limited to:**
- File system operations (creating, modifying, deleting files)
- Git operations (commits, pushes, branch changes)
- Package installations and updates
- Build and compilation commands
- Test execution and validation
- System configuration changes
### MANDATORY MEMORY REFRESH BEFORE COMPLETION
**🚨 ALL AGENTS MUST REFRESH THEIR MEMORY BEFORE CONCLUDING WORK:**
- **The AI shall read the cursor rules again to find out what to do before task is considered complete**
- This is MANDATORY for both foreground and background agents
- Reading the cursor rules refreshes your memory about the latest project rules, coding standards, and requirements
- This ensures you have current information about testing procedures, validation tools, and completion requirements
- Do NOT indicate your work is "done" until you have refreshed your memory by reading the cursor rules
## 🚨 CRITICAL REQUIREMENTS FOR BACKGROUND AGENTS 🚨
### MANDATORY PRE-COMPLETION VALIDATION
**ALL BACKGROUND AGENTS MUST FOLLOW THESE REQUIREMENTS BEFORE INDICATING COMPLETION:**
1. **🚨 ALWAYS RUN `bash test` BEFORE INDICATING COMPLETION**
- This is MANDATORY and NON-NEGOTIABLE for all background agents
- The command `bash test` runs the full test suite including unit tests and compilation checks
- Background agents MUST NOT indicate they are "done" until ALL tests pass
2. **🚨 USE MCP SERVER VALIDATION TOOL**
- Use the `validate_completion` tool from the MCP server: `uv run mcp_server.py`
- This tool runs `bash test` and validates that all tests pass
- Only indicate completion if this validation tool returns success
3. **🚨 ZERO TOLERANCE FOR TEST FAILURES**
- If ANY test fails, the background agent MUST fix the issues before completion
- Do NOT indicate completion with failing tests
- Do NOT ignore test errors or warnings
### Background Agent Completion Checklist:
- [ ] All code changes have been made
- [ ] `bash test` has been run and ALL tests pass
- [ ] No compilation errors or warnings
- [ ] MCP server `validate_completion` tool shows success
- [ ] Only then indicate task completion
**FAILURE TO FOLLOW THESE REQUIREMENTS WILL RESULT IN BROKEN CODE SUBMISSIONS.**
### C++ Design Patterns
**Shared Implementation Pattern:** When writing a lot of code that applies the same operation on a bunch of C++ objects, try and determine if those objects share a common base class or internal object. If so consider whether it's appropriate to move the implementation into a shared space.
## Code Standards
### Python List Comprehensions
**🚨 AVOID: List comprehensions in favor of explicit loops**
**❌ WRONG - Using list comprehensions:**
```python
# Hard to read and debug
files = [f for f in os.listdir() if f.endswith('.py')]
results = [process(x) for x in data if is_valid(x)]
nested = [(x, y) for x in range(5) for y in range(3)]
```
**✅ CORRECT - Using explicit loops:**
```python
# Clear and debuggable
files = []
for f in os.listdir():
if f.endswith('.py'):
files.append(f)
results = []
for x in data:
if is_valid(x):
results.append(process(x))
nested = []
for x in range(5):
for y in range(3):
nested.append((x, y))
```
**Why avoid list comprehensions:**
- ✅ **Readability** - Explicit loops are easier to read and understand
- ✅ **Debuggability** - Can set breakpoints and inspect variables in loops
- ✅ **Maintainability** - Easier to modify and extend loop logic
- ✅ **Error handling** - Can add try/except blocks in loops
- ✅ **Step-by-step clarity** - Operations are clearly separated and ordered
**When list comprehensions ARE acceptable:**
- ✅ **Simple transformations**: `squares = [x * x for x in numbers]`
- ✅ **Basic filtering**: `evens = [x for x in numbers if x % 2 == 0]`
- ✅ **Single-purpose operations**: `names = [user.name for user in users]`
**Key principle:** If the operation involves multiple conditions, transformations, or would benefit from step-by-step debugging, use an explicit loop instead.
### Python Function Parameter and Return Types
**🚨 MANDATORY: ALL function parameters MUST have explicit type annotations - NO EXCEPTIONS!**
**🚨 MANDATORY: ALL function return types MUST have explicit type annotations - NO EXCEPTIONS!**
**🚨 MANDATORY: NO DEFAULT VALUES in function parameters - NO EXCEPTIONS!**
This rule applies to:
- ✅ Regular function parameters (no defaults) AND return types
- ✅ Method parameters (including self/cls, no defaults) AND return types
- ✅ Lambda parameters (no defaults) AND return types
- ✅ Callback function parameters (no defaults) AND return types
- ✅ Generator function parameters (no defaults) AND return types
- ✅ Async function parameters (no defaults) AND return types
- ✅ Protocol method parameters (no defaults) AND return types
**Examples:**
```python
# ❌ WRONG - Missing parameter types
def process_data(data):
return data
# ❌ WRONG - Missing return type annotation
def run_tests():
pass
# ❌ WRONG - Partial typing and defaults
def validate_user(name: str, age, enabled: bool = True):
return True
# ❌ WRONG - Has default values (even with types)
def process_data(data: bytes, validate: bool = True) -> bytes:
return data
# ✅ CORRECT - All parameters typed, no defaults, explicit return type
def process_data(data: bytes, validate: bool) -> bytes:
return data
# ✅ CORRECT - Explicit return type for functions returning None
def run_tests() -> None:
pass
# ✅ CORRECT - Method parameters typed including self
class DataProcessor:
def process(self, data: bytes) -> bytes:
return data
# ✅ CORRECT - Lambda parameters typed
callback: Callable[[int], None] = lambda x: None
# ✅ CORRECT - Async function parameters typed
async def fetch_data(url: str) -> bytes:
return await download(url)
```
**Return Type Requirements:**
- ✅ Functions that return nothing: `-> None`
- ✅ Functions that return a value: `-> ReturnType`
- ✅ Functions that return optional values: `-> Optional[ReturnType]` or `-> ReturnType | None`
- ✅ Functions that return multiple types: `-> Union[Type1, Type2]` or `-> Type1 | Type2`
- ✅ Generator functions: `-> Generator[YieldType, SendType, ReturnType]`
- ✅ Async functions: `-> Awaitable[ReturnType]` or `async def func() -> ReturnType`
**ABSOLUTELY FORBIDDEN:**
- ❌ Functions without return type annotations: `def function():`
- ❌ Methods without return type annotations: `def method(self):`
**Protocol Method Parameters:**
```python
# ❌ WRONG - Protocol methods missing parameter types
class DataHandler(Protocol):
def handle(self, data): ...
def process(self, input, count): ...
# ✅ CORRECT - All Protocol method parameters typed
class DataHandler(Protocol):
def handle(self, data: bytes) -> None: ...
def process(self, input: str, count: int) -> bool: ...
```
**Why This Rule Exists:**
- Enables complete static type checking
- Prevents type-related bugs
- Improves code clarity and maintainability
- Makes refactoring safer
- Provides better IDE support
- Ensures Protocol interfaces are fully typed
### Python Variable Types and Type Safety
**🚨 FORBIDDEN: Partially unknown types - All variables must have explicit type annotations**
**❌ WRONG - Implicit typing creates partially unknown types:**
```python
all_files = [] # Type: list[Unknown]
config = {} # Type: dict[Unknown, Unknown]
result = None # Type: None (loses type info)
data = get_some_data() # Type: Unknown
```
**✅ CORRECT - Explicit type annotations prevent unknown types:**
```python
all_files: list[str] = [] # Type: list[str]
config: dict[str, Any] = {} # Type: dict[str, Any]
result: Optional[str] = None # Type: str | None
data: ResponseData = get_some_data() # Type: ResponseData
```
**🚨 CRITICAL: Lists MUST be properly and fully typed**
**❌ WRONG - Implicit list typing:**
```python
mylist = [] # Type: list[Unknown] - BAD!
items = [] # Type: list[Unknown] - BAD!
results = [] # Type: list[Unknown] - BAD!
```
**✅ CORRECT - Explicit list typing:**
```python
mylist: list[str] = [] # Type: list[str] - GOOD!
items: list[int] = [] # Type: list[int] - GOOD!
results: list[dict[str, Any]] = [] # Type: list[dict[str, Any]] - GOOD!
```
**Why explicit types are mandatory:**
- ✅ **IDE support** - Better autocomplete and error detection
- ✅ **Type safety** - Catches type errors at development time
- ✅ **Documentation** - Code is self-documenting with clear types
- ✅ **Refactoring safety** - Type changes are caught throughout codebase
- ✅ **Runtime validation** - Works with `@typechecked` decorator
**Function signatures must also have explicit types:**
```python
# ❌ WRONG - Missing type annotations
def process_files(files, config):
return []
# ✅ CORRECT - Complete type annotations
def process_files(files: list[str], config: dict[str, Any]) -> list[str]:
return []
# ✅ CORRECT - With Optional and complex types
from typing import Optional, Union
def parse_data(data: str, timeout: Optional[int] = None) -> Union[dict[str, Any], None]:
return {}
```
**🚨 CRITICAL: TUPLES FOR MULTIPLE RETURN VALUES ARE FORBIDDEN**
**NEVER use tuples for multiple return values - use dataclass structs instead:**
**❌ WRONG - Tuples have no named fields:**
```python
def compile_examples() -> tuple[int, int, float]:
return successful_count, failed_count, compile_time
def link_programs() -> tuple[int, int]:
return linked_count, failed_count
# Usage becomes unclear and error-prone
success, failed, time = compile_examples() # Which is which?
a, b = link_programs() # What do a and b represent?
```
**✅ CORRECT - Dataclass structs with named fields:**
```python
@dataclass
class CompilationResult:
successful_count: int
failed_count: int
compile_time: float
@dataclass
class LinkingResult:
linked_count: int
failed_count: int
def compile_examples() -> CompilationResult:
return CompilationResult(