-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakefile
More file actions
900 lines (823 loc) · 46.4 KB
/
Copy pathMakefile
File metadata and controls
900 lines (823 loc) · 46.4 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
# Makefile wrapper for engine-sim-cli
# Handles both fresh clone and development builds
#
# IMPORTANT: Always use 'make' from project root, never run 'cmake' directly.
# Running 'cmake -S . -B .' will overwrite this Makefile and break the build.
#
# Build cascade: make build -> cmake -> compile -> presets -> sync-es
# Test cascade: make test -> build -> bridge tests + CLI tests
# Full pipeline: make all -> build + test
BUILD_DIR ?= build
BUILD_TYPE ?= RelWithDebInfo
BUILD_PHASE0_SPIKES ?= OFF
# Set to 1 to allow Debug builds (needed for coverage instrumentation).
ALLOW_DEBUG_BUILD ?= 0
CTEST_JOBS ?= $(shell sysctl -n hw.ncpu 2>/dev/null || echo 4)
BUILD_PARALLEL_LEVEL ?= $(shell sysctl -n hw.ncpu 2>/dev/null || echo 4)
CTEST_VERBOSE ?= 0
CTEST_UI_FLAGS := $(if $(filter 1,$(CTEST_VERBOSE)),-V,--progress)
SUBMODULE_STAMP = $(BUILD_DIR)/.submodule-stamp
SONAR_STAMP := $(BUILD_DIR)/.sonar-scan.stamp
SONAR_PROJECT_PROPERTIES := sonar-project.properties
COMPILE_DB := $(BUILD_DIR)/compile_commands.json
# Separate build-cov directory for coverage/sonar. RelWithDebInfo + llvm-cov
# instrumentation. Has its own CMakeCache so coverage reconfigure does NOT
# invalidate the test build in $(BUILD_DIR). Mirrors the bridge's model.
BUILD_COV_DIR ?= build-cov
BUILD_TYPE_COV ?= RelWithDebInfo
SONAR_PROJECT_PROPERTIES := sonar-project.properties
COMPILE_DB := $(BUILD_COV_DIR)/compile_commands.json
COVERAGE_REPORT := $(BUILD_COV_DIR)/coverage.txt
# SonarCloud generic coverage XML (lcov -> XML via the bridge's
# scripts/lcov_to_xml.py). Read by the scanner via sonar.coverageReportPaths.
COVERAGE_XML := $(BUILD_COV_DIR)/coverage-sonar.xml
SONAR_REPORT := $(BUILD_COV_DIR)/sonar-report.json
# sonar-summary's LIVE curl output. Deliberately a DIFFERENT file from
# SONAR_REPORT: the report is the sonar-scan stamp (its presence means
# "scanned"); writing the summary GET into it made every later sonar-scan
# a permanent no-op ("Nothing to be done"). Same fix as bridge 6a5482d.
SONAR_LIVE := $(BUILD_COV_DIR)/sonar-live.json
# Cached SonarCloud measures (coverage headline) + REMOVED-facet (issues whose
# source was deleted). Both curled by sonar-summary so build_summary.py reads
# the SAME numbers sonar_summary.py shows -- total = open + removed (OPEN union
# REMOVED, matching the dashboard severity widget). Mirrors the bridge.
SONAR_MEASURES := $(BUILD_COV_DIR)/sonar-measures.json
SONAR_REMOVED_FACET := $(BUILD_COV_DIR)/sonar-removed-facet.json
# Real artefact dependencies replace .stamp files (KISS — Make's natural
# mtime check is sufficient; no .stamp bookkeeping required). The CLI
# binary is the real artefact produced by `cmake --build`. (The previous
# BUILD_STAMP := $(BUILD_DIR)/.build-ready.stamp was an unused ghost
# declaration; the `build:` target depends on the test + bridge deps,
# not a stamp file.)
BUILD_COV_STAMP := $(BUILD_COV_DIR)/engine-sim-cli
# Bridge's instrumented coverage archive. The CLI build-cov configures with
# -DBRIDGE_BUILD_DIR pointing here, so the CLI links the bridge's INSTRUMENTED
# build-cov libenginesim.a — coverage then attributes bridge source lines.
BRIDGE_DIR := engine-sim-bridge
BRIDGE_BUILD_COV_LIB := $(BRIDGE_DIR)/build-cov/libenginesim.a
# LLVM coverage tools: Xcode toolchain first, plain which() fallback.
LLVM_COV := $(shell xcrun --find llvm-cov 2>/dev/null || which llvm-cov 2>/dev/null)
LLVM_PROFDATA := $(shell xcrun --find llvm-profdata 2>/dev/null || which llvm-profdata 2>/dev/null)
# Source inputs that affect the coverage build. Invalidation on change.
# Note: engine-sim-bridge is NOT listed here. The bridge is linked as a static
# archive, so its invalidation is tracked once (DRY) via the archive dependency
# chain (BRIDGE_BUILD_COV_LIB -> CMakeCache.txt -> BUILD_COV_STAMP), not by
# enumerating its source mtimes here. Listing it caused the coverage report to
# rebuild on every bridge file touch and bloated lcov scope.
BUILD_INPUTS := $(shell find Makefile CMakeLists.txt src include test tools engine-sim -type f \( -name '*.c' -o -name '*.cc' -o -name '*.cpp' -o -name '*.cxx' -o -name '*.h' -o -name '*.hh' -o -name '*.hpp' -o -name '*.cmake' \) 2>/dev/null | sort)
# Bridge changes must invalidate the test cache WITHOUT listing bridge files in
# BUILD_INPUTS (that caused full rebuilds + lcov bloat on every bridge touch —
# see the find roots above). Key on the bridge submodule's HEAD plus a dirty
# marker instead: a new bridge commit changes HEAD; uncommitted bridge work
# makes `status --porcelain` non-empty. Both invalidate; untouched bridge is a
# cheap no-op.
BRIDGE_STATE := $(shell git -C $(BRIDGE_DIR) rev-parse HEAD 2>/dev/null)-$(shell [ -n "$$(git -C $(BRIDGE_DIR) status --porcelain 2>/dev/null)" ] && echo dirty)
BRIDGE_STATE_FILE := $(BUILD_DIR)/cli-test-bridge-state.txt
# Build system: Ninja (recommended) or Make (fallback)
# Ninja handles parallel dependency ordering correctly; Make has a known race
# condition where .o recompilation doesn't always trigger re-link with --parallel.
NINJA_BIN := $(shell command -v ninja 2>/dev/null)
ifdef NINJA_BIN
CMAKE_GENERATOR := -G Ninja
CMAKE_BUILD_PARALLEL_FLAG := $(if $(strip $(BUILD_PARALLEL_LEVEL)),-j $(BUILD_PARALLEL_LEVEL),)
# Ninja banner: shown only on real builds, NEVER during `summary` (which recurses
# into this Makefile via $(MAKE) -C engine-sim-cli summary and would otherwise
# interleave a "[build] Ninja detected" line into the end-of-make headline block).
# SUMMARY_QUIET is exported by the summary targets so the recursion stays silent.
ifndef SUMMARY_QUIET
$(info [build] Ninja detected — parallel builds enabled)
endif
else
CMAKE_GENERATOR :=
CMAKE_BUILD_PARALLEL_FLAG :=
ifndef SUMMARY_QUIET
$(warning [build] Ninja not found — parallel builds disabled to avoid re-link race condition. Install ninja to enable.)
endif
endif
ESP32_DIR ?= engine-sim-esp32
ESP32_PORT ?= $(shell ls /dev/cu.usbserial-* 2>/dev/null | head -1)
# Auto-detect EIM-installed ESP-IDF: prefers latest versioned install, falls back to IDF_PATH env var
IDF_PATH ?= $(or $(wildcard $(HOME)/.espressif/v6.*/esp-idf),$(HOME)/esp/esp-idf)
IDF_ACTIVATE ?= $(firstword $(wildcard $(HOME)/.espressif/tools/activate_idf_*.sh))
.DEFAULT_GOAL := all
.PHONY: all build clean clean-cli scrub-cli test test-fast test-quick testquick submodules check-cmake check-platform check-submodule remove-orphans \
force-rebuild sync-es copy-es-mr copy-es-json presets bridge-presets bridge-build \
run run-json help build-cross clean-cross sonar-clean sonar-summary \
coverage-run coverage-clean coverage-summary summary gate \
smoke-gearbox bench-gearbox sine-knock-smoke engine-knock-smoke
.PHONY: esp32 deploy_esp32 run_esp32 clean_esp32
.PHONY: build-cross-gate
# gate MUST run its steps strictly in order: build -> test -> iOS cross ->
# coverage -> sonar -> summary. The steps share build dirs (build/ for the
# macOS compile, build-OS64/ for the cross, build-cov/ for coverage) and the
# bridge submodule; running them concurrently under `make -j gate` would race
# on those dirs. .NOTPARALLEL forces serial execution of the gate (and its
# cross-build wrapper) regardless of -j, while leaving the rest of the
# Makefile's parallelism (compiler/ctest -j inside each step) intact.
.NOTPARALLEL: gate build-cross-gate
# ============================================================================
# all: Full pipeline -- build + test (default target). `summary` is the LAST
# step so the end-of-make output is the four summary BLOCKS (cli coverage,
# cli sonar, bridge coverage, bridge sonar) followed by EXACTLY the two
# headline rows (cli line, then bridge line -- the recursion calls the
# bridge's summary-headline LAST, so no rows land after them).
# ============================================================================
all: build test summary
# ============================================================================
# gate: THE pre-commit command. Encodes the COMMIT GATE rule from CLAUDE.md as
# a single fail-fast command so it cannot be skipped by accident.
#
# The full gate, in order: macOS build -> bridge+CLI tests -> iOS cross-build
# -> coverage-regen -> Sonar scan (zero-new-issues) -> headline summary.
#
# WHY the cross-build is in here: on 2025-07-04 the lead declared the tree
# green after running only the macOS build, missing an iOS (PLATFORM=OS64)
# cross-build break. The rule already existed; the discipline failed. `gate`
# makes the rule mechanical.
#
# Sequential, fail-fast via prerequisites: the first failing step stops the
# run and the exit code propagates. Reuses existing targets (DRY) -- it does
# not reimplement their bodies. Ordering is enforced even under `make -j`
# via the .NOTPARALLEL declaration near the .PHONY block.
#
# NOTE: sonar-scan requires SONAR_TOKEN_ES or SONAR_TOKEN. If neither is set
# the sonar-scan step fails fast with a clear message (it does NOT silently
# skip), so the gate surfaces the missing token rather than passing without it.
# ============================================================================
gate: build test build-cross-gate coverage-run sonar-scan summary
@echo ""
@printf '\033[0;32m=== [engine-sim-cli] GATE PASSED: build + tests + iOS cross + coverage + sonar ===\033[0m\n'
# iOS cross-build wrapper so `gate` can pass PLATFORM=OS64 to build-cross
# without re-declaring its recipe. Fail-fast: build-cross's own $(error)
# guards malformed PLATFORM.
build-cross-gate:
+@$(MAKE) build-cross PLATFORM=OS64
# ============================================================================
# build: Compile everything -- configure, compile, build presets, sync es/
#
# Ordering is sequential via dependencies:
# 1. submodules -- init recursive submodules
# 2. $(BUILD_DIR)/CMakeCache.txt -- cmake configure
# 3. check-platform -- verify macOS, then compile everything
# 4. bridge-presets -- compile .mr -> .json (needs preset_compiler from step 3)
# 5. sync-es -- copy bridge es/ + preset/ -> CLI es/
# ============================================================================
build: check-platform bridge-presets sync-es
check-platform: check-cmake bridge-build $(BUILD_DIR)/CMakeCache.txt
@if [ "$$(uname)" != "Darwin" ]; then \
echo ""; \
echo "ERROR: engine-sim-cli only supports macOS (CoreAudio/AudioUnit)."; \
echo " Linux and Windows are not supported — no audio hardware provider exists."; \
echo " Planned next platforms: ESP32, Android."; \
echo " See README.md for the platform support roadmap."; \
echo ""; \
exit 1; \
fi
+@cmake --build $(BUILD_DIR) $(CMAKE_BUILD_PARALLEL_FLAG)
# Bridge builds independently -- must complete before CLI cmake configure
bridge-build: submodules check-submodule
+@$(MAKE) -C engine-sim-bridge build ALLOW_DEBUG_BUILD=$(ALLOW_DEBUG_BUILD)
# Build presets in bridge (depends on check-platform so compiler exists)
bridge-presets: check-platform
+@$(MAKE) -C engine-sim-bridge presets
# ---------------------------------------------------------------------------
# es/ convenience copy -- full mirror from bridge
#
# The bridge/es/ directory is the source of truth for all .mr scripts and
# supporting files. The bridge Makefile's CANDIDATE_ENGINES controls which
# get compiled to JSON. This target just mirrors the full directory.
# ---------------------------------------------------------------------------
BRIDGE_ES := engine-sim-bridge/es
BRIDGE_PRESET := engine-sim-bridge/preset
CLI_ES := es
copy-es-mr:
@echo "Syncing es/ from bridge..."
@mkdir -p $(CLI_ES)
@rsync -a --exclude='.git' $(BRIDGE_ES)/ $(CLI_ES)/
copy-es-json: bridge-presets
@if [ -d $(BRIDGE_PRESET) ] && ls $(BRIDGE_PRESET)/*.json >/dev/null 2>&1; then \
echo "Syncing JSON presets..."; \
cp $(BRIDGE_PRESET)/*.json $(CLI_ES)/; \
else \
echo "No presets built yet -- run 'make presets' first."; \
fi
sync-es: copy-es-mr copy-es-json
presets: bridge-presets
# ---------------------------------------------------------------------------
# Submodule and CMake configuration
# ---------------------------------------------------------------------------
check-submodule: submodules
@CURRENT_SUBMODULE=$$(git submodule status engine-sim-bridge | awk '{print $$1}'); \
STAMPED_SUBMODULE=$$(cat $(SUBMODULE_STAMP) 2>/dev/null); \
if [ "$$CURRENT_SUBMODULE" != "$$STAMPED_SUBMODULE" ]; then \
echo "Submodule changed, forcing rebuild..."; \
rm -f $(BUILD_DIR)/CMakeCache.txt; \
$(MAKE) -C engine-sim-bridge scrub; \
mkdir -p $(BUILD_DIR); \
echo "$$CURRENT_SUBMODULE" > $(SUBMODULE_STAMP); \
fi
check-cmake:
@if [ -f CMakeCache.txt ] && ! grep -qE "CMAKE_BUILD_TYPE:STRING=(Release|RelWithDebInfo)" CMakeCache.txt; then \
echo "ERROR: Root CMakeCache.txt exists with wrong BUILD_TYPE. This happens when running 'cmake -S . -B .' directly."; \
echo "Please run 'git checkout Makefile' and then use 'make' instead."; \
exit 1; \
fi
submodules:
@if [ ! -f engine-sim-bridge/CMakeLists.txt ]; then \
echo "Initializing submodules..."; \
git submodule update --init --recursive; \
fi
# check-submodule is an ORDER-ONLY prereq on purpose (found 2026-09-09): as a
# normal prereq of this phony target the configure recipe re-ran on EVERY
# root make. It still runs every make (also via bridge-build), so the
# scrub-on-pointer-change behaviour is intact -- and when it deletes this
# cache the rule reconfigures because the target is missing. The trailing
# `touch CMakeCache.txt` is the same fix as the build-cov rule below: cmake
# does not rewrite an unchanged cache, so without the touch the cache mtime
# stays older than an edited CMakeLists.txt and Make reconfigures forever.
$(BUILD_DIR)/CMakeCache.txt: CMakeLists.txt | check-submodule
@mkdir -p $(BUILD_DIR)
@cd $(BUILD_DIR) && cmake $(CMAKE_GENERATOR) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \
-DBUILD_PHASE0_SPIKES=$(BUILD_PHASE0_SPIKES) \
-DCMAKE_SUPPRESS_DEVELOPER_WARNINGS=ON \
-DCMAKE_POLICY_DEFAULT_CMP0091=NEW \
.. && touch CMakeCache.txt
# ---------------------------------------------------------------------------
# Clean targets -- cascade to bridge
# ---------------------------------------------------------------------------
remove-orphans:
@rm -rf assets
@rm -f *.dylib libenginesim*.dylib
@find . -name "*.dylib*" -type l -delete 2>/dev/null || true
@rm -f $(SUBMODULE_STAMP)
@find . -path ./$(BUILD_DIR) -prune -o -name "CMakeCache.txt" -type f -print -delete 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "CMakeFiles" -type d -print -exec rm -rf {} + 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "cmake_install.cmake" -type f -print -delete 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "CTestTestfile.cmake" -type f -print -delete 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "*_include.cmake" -type f -print -delete 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "*.a" -type f -print -delete 2>/dev/null || true
@find . -path ./$(BUILD_DIR) -prune -o -name "_deps" -type d -print -exec rm -rf {} + 2>/dev/null || true
# cascade clean to submodules
clean: remove-orphans clean_esp32 sonar-clean coverage-clean
+@$(MAKE) -C engine-sim-bridge clean 2>/dev/null || true
# clean this repo only
clean-cli: clean
@if [ -d $(BUILD_DIR) ]; then \
cmake --build $(BUILD_DIR) --target clean >/dev/null 2>&1 || true; \
fi
@rm -rf $(CLI_ES)
# cascade the scrub to submodules
scrub: scrub-cli
+@$(MAKE) -C engine-sim-bridge scrub 2>/dev/null || true
# scrub this repo only
scrub-cli: clean-cli
@echo "Scrubbing all build artifacts..."
@rm -rf $(BUILD_DIR) $(BUILD_COV_DIR) $(CLI_ES)
@$(MAKE) remove-orphans
@echo "Build artifacts scrubbed. Run 'make' to rebuild."
# ---------------------------------------------------------------------------
# Test -- build first, then run all test suites via CTest
# ---------------------------------------------------------------------------
# --- Test caching artefacts (real files, NOT .stamp hacks) -------------------
# CLI ctest emits JUnit XML to build/cli-test-results.xml (ctest --output-junit).
# The bridge side of the guard is keyed on what the CLI actually CONSUMES from
# the bridge: the static archive it links (engine-sim-bridge/build/libenginesim.a
# -- BRIDGE_STATIC_LIB in CMakeLists.txt) and the bridge preset JSONs that
# sync-es copies into es/. `make test` SKIPS both runs when nothing changed:
# the CLI artefact exists and is non-empty, no source input is newer than it,
# AND the CLI artefact is newer than EVERY bridge artefact. Touching src/
# include/ test/ (or rebuilding the bridge archive / a preset) invalidates and
# re-runs. Re-keyed 2026-09-09 from the bridge's build/test-summary.log: the
# bridge's own test tiers legitimately refresh that log, and a log refresh
# says nothing about the bridge code the CLI links -- the log-keyed guard made
# every no-change bridge make spuriously re-run the CLI's full ctest + sonar
# scan.
# The guard is -s, not -f: an EMPTY junit file (0-byte stamp from an interrupted
# run, which `make clean` does not delete) counts as ABSENT — it must never skip
# the gate's test stage (blind spot found 2026-09-08: a gate ran "green" with no
# ctest stage at all behind a 0-byte stamp).
# The stage-2 ctest below passes the junit path ABSOLUTE ($(abspath)): ctest
# runs with cwd=$(BUILD_DIR), so a relative --output-junit landed in
# build/build/cli-test-results.xml while `touch` left THIS path as a 0-byte
# ghost — the guard then failed on every run and the full suite re-ran each
# time (found 2026-09-08; the stray build/build/ dir was the giveaway).
# EVERY bridge artefact is guarded by `! -e` BEFORE its -nt: `test a -nt b` is
# TRUE when b does not exist, so after `check-submodule` scrubs the bridge
# (any submodule-pointer move) the guard must read STALE, not "up to date",
# while the bridge archive the CLI links is gone (found 2026-09-08, when the
# bridge's test/coverage/sonar data was gone and the bridge headline went
# "(no summary data)"). A MISSING artefact is stale, same philosophy as the
# -s check above.
# Folds caching into the existing two-stage flow; does NOT rewrite it.
CLI_TEST_RESULTS := $(BUILD_DIR)/cli-test-results.xml
BRIDGE_TEST_ARTEFACTS := $(BRIDGE_DIR)/build/libenginesim.a $(wildcard $(BRIDGE_DIR)/preset/*.json)
# --- DRY test-stage macros --------------------------------------------------
# Mirror the file's existing `define ... endef` shell style (cf. ESP32_ACTIVATE).
# `$(call)` substitutes params textually into the single shell that runs the
# recipe, so shell vars (bridge_elapsed, cli_elapsed) set by one macro persist
# into later ones. PASS/FAIL messages, exit codes and the non-fatal
# coverage/sonar summary call (full mode only) are preserved exactly.
define run_bridge_stage
bridge_start=$$(date +%s); \
if $(MAKE) -C engine-sim-bridge $(1); then \
bridge_end=$$(date +%s); \
bridge_elapsed=$$((bridge_end - bridge_start)); \
echo "=== [engine-sim-cli] $(2) PASSED ($${bridge_elapsed}s) ==="; \
else \
bridge_end=$$(date +%s); \
bridge_elapsed=$$((bridge_end - bridge_start)); \
echo "=== [engine-sim-cli] $(2) FAILED ($${bridge_elapsed}s) ==="; \
printf '\033[0;31m=== [engine-sim-cli] FAILURES:\033[0m\n'; \
-grep -E "(FAILED|Failed [0-9]+ tests)" engine-sim-bridge/$(BUILD_DIR)/test-summary.log 2>/dev/null | head -30; \
-grep -E "^\[[ ]*FAILED" engine-sim-bridge/$(BUILD_DIR)/Testing/Temporary/LastTest.log 2>/dev/null | head -30; \
total_end=$$(date +%s); \
total_elapsed=$$((total_end - total_start)); \
echo "=== [engine-sim-cli] TIME: $(3)=$${bridge_elapsed}s cli=SKIPPED total=$${total_elapsed}s ==="; \
printf '\033[0;31m=== [engine-sim-cli] RESULT: TESTS FAILED ===\033[0m\n'; \
exit 1; \
fi
endef
define run_cli_stage
cli_start=$$(date +%s); \
if (cd $(BUILD_DIR) && ctest $(CTEST_UI_FLAGS) --output-on-failure --output-log ../test.log $(4) -j$(CTEST_JOBS)); then \
cli_end=$$(date +%s); \
cli_elapsed=$$((cli_end - cli_start)); \
total_end=$$(date +%s); \
total_elapsed=$$((total_end - total_start)); \
echo "=== [engine-sim-cli] TIME: $(1)=$${bridge_elapsed}s cli=$${cli_elapsed}s total=$${total_elapsed}s ==="; \
echo "=== [engine-sim-cli] SUMMARY: PASS ($(2)) ==="; \
printf '\033[0;32m=== [engine-sim-cli] RESULT: $(3) ===\033[0m\n'; \
else \
cli_end=$$(date +%s); \
cli_elapsed=$$((cli_end - cli_start)); \
total_end=$$(date +%s); \
total_elapsed=$$((total_end - total_start)); \
echo "=== [engine-sim-cli] TIME: $(1)=$${bridge_elapsed}s cli=$${cli_elapsed}s total=$${total_elapsed}s ==="; \
echo "=== [engine-sim-cli] SUMMARY: FAIL ($(2)) ==="; \
printf '\033[0;31m=== [engine-sim-cli] FAILURES:\033[0m\n'; \
-grep -E "(FAILED|Failed [0-9]+ tests)" ../test.log 2>/dev/null | head -30; \
-grep -E "^\[[ ]*FAILED" ../test.log 2>/dev/null | head -30; \
printf '\033[0;31m=== [engine-sim-cli] RESULT: TESTS FAILED ===\033[0m\n'; \
exit 1; \
fi
endef
define run_bridge_only_stage
if $(MAKE) -C engine-sim-bridge $(1); then \
echo "=== [engine-sim-cli] SUMMARY: PASS ($(2)) ==="; \
printf '\033[0;32m=== [engine-sim-cli] RESULT: $(3) ===\033[0m\n'; \
else \
echo "=== [engine-sim-cli] SUMMARY: FAIL ($(2)) ==="; \
printf '\033[0;31m=== [engine-sim-cli] RESULT: TESTS FAILED ===\033[0m\n'; \
exit 1; \
fi
endef
test: build
+@bridge_artefact_stale=0; \
for artefact in $(BRIDGE_TEST_ARTEFACTS); do \
if [ ! -e "$$artefact" ] || ! [ $(CLI_TEST_RESULTS) -nt "$$artefact" ]; then \
bridge_artefact_stale=1; \
break; \
fi; \
done; \
if [ -s $(CLI_TEST_RESULTS) ] && \
[ "$$bridge_artefact_stale" = "0" ] && \
[ -z "$$(find $(BUILD_INPUTS) -newer $(CLI_TEST_RESULTS) -print -quit 2>/dev/null)" ] && \
[ "$$(cat $(BRIDGE_STATE_FILE) 2>/dev/null)" = "$(BRIDGE_STATE)" ]; then \
echo "=== [engine-sim-cli] TESTS UP TO DATE — bridge + ctest skipped (artefacts current) ==="; \
else \
total_start=$$(date +%s); \
bridge_elapsed=0; \
cli_elapsed=0; \
echo "=== [engine-sim-cli] Stage 1/2: bridge tests ==="; \
$(call run_bridge_stage,test,Stage 1/2: bridge tests,bridge); \
echo "=== [engine-sim-cli] Stage 2/2: cli/unit/integration tests ==="; \
$(call run_cli_stage,bridge,full,ALL TESTS PASSED,--output-junit $(abspath $(CLI_TEST_RESULTS))); \
touch $(CLI_TEST_RESULTS); \
printf '%s' "$(BRIDGE_STATE)" > $(BRIDGE_STATE_FILE); \
$(MAKE) $(SONAR_REPORT) || \
echo "=== [engine-sim-cli] sonar/coverage summary skipped (non-fatal) ==="; \
fi
# Fast test path: build + bridge fast tests + full CLI tests.
test-fast: build
+@total_start=$$(date +%s); \
bridge_elapsed=0; \
cli_elapsed=0; \
echo "=== [engine-sim-cli] Fast mode: bridge test-fast + full cli/unit/integration ==="; \
$(call run_bridge_stage,test-fast,Bridge fast suite,bridge-fast); \
echo "=== [engine-sim-cli] Stage 2/2: cli/unit/integration tests ==="; \
$(call run_cli_stage,bridge-fast,fast,FAST TESTS PASSED,)
# Quick mode: minimal bridge-only infra checks for tight edit/run loops.
test-quick: build
@echo "=== [engine-sim-cli] Quick mode: bridge test-quick only ==="
+@$(call run_bridge_only_stage,test-quick,quick,QUICK TESTS PASSED)
testquick: test-quick
# Explicit long-running tier: bridge isomorphism + engine-sim physics tests.
test-deep: build
@echo "=== [engine-sim-cli] Deep mode: bridge isomorphism + engine-sim physics tests ==="
+@$(call run_bridge_only_stage,test-deep,deep,DEEP TESTS PASSED)
testdeep: test-deep
# ---------------------------------------------------------------------------
# Convenience targets
# ---------------------------------------------------------------------------
run: build
./build/engine-sim-cli --interactive --play --script es/ferrari_f136.mr
run-json: build
./build/engine-sim-cli --interactive --play --script es/v8_gm_ls.json
# --- Road-test kit ------------------------------------------------------------
# Headless, short, deterministic road-test runs. Each run auto-generates a
# UTC-timestamped roadtest_<timestamp>.csv (--csv-out true) so reruns NEVER
# overwrite a prior log. NO build step inside these targets — run `make build`
# first, then `make roadtest_*`. --silent (mandatory on the laptop) and
# --pin-tau-ms 150 (tuned road value) are on EVERY run. The full command line
# is echoed (so it is visible / copyable) before execution.
#
# PRESETS (verified present in es/):
# Ferrari F136 -> es/ferrari_f136.mr (canonical, also the existing `run` target)
# C63 -> es_new/C63_M156_V4.mr (span-tamed V4: clean body + tamed
# audio span, audio_volume 40x->4x; supersedes the V3 in es/).
ROADTEST_SCRIPT_FERRARI ?= es/ferrari_f136.mr
ROADTEST_SCRIPT_C63 ?= es_new/C63_M156_V4.mr
ROADTEST_DURATION ?= 5
roadtest_ferrari:
@echo "=== [engine-sim-cli] roadtest_ferrari: short deterministic run ==="
@echo "./build/engine-sim-cli --silent --pin-tau-ms 150 --csv-out true --deterministic --duration $(ROADTEST_DURATION) --script $(ROADTEST_SCRIPT_FERRARI)"
./build/engine-sim-cli --silent --pin-tau-ms 150 --csv-out true --deterministic --duration $(ROADTEST_DURATION) --script $(ROADTEST_SCRIPT_FERRARI)
roadtest_c63:
@echo "=== [engine-sim-cli] roadtest_c63: short deterministic run ==="
@echo "./build/engine-sim-cli --silent --pin-tau-ms 150 --csv-out true --deterministic --duration $(ROADTEST_DURATION) --script $(ROADTEST_SCRIPT_C63)"
./build/engine-sim-cli --silent --pin-tau-ms 150 --csv-out true --deterministic --duration $(ROADTEST_DURATION) --script $(ROADTEST_SCRIPT_C63)
# --- Gearbox regression smoke + bench -----------------------------------------
# Canonical recording + window for the "6 mph stall" regression that MUST stay
# green. VEHICLE_SIM_CAP / RECORDING / WINDOW overrides via the env.
VEHICLE_SIM_CAP ?= $(HOME)/vscode/escli.vehicle-sim/captures
SMOKE_RECORDING ?= $(VEHICLE_SIM_CAP)/UpLeckHillWithKickdown_2026-08-12-133448.csv
SMOKE_WINDOW_START ?= 00:20
SMOKE_WINDOW_END ?= 00:25
BENCH_RECORDING ?= $(VEHICLE_SIM_CAP)/em-dinner.csv
# Gateable regression smoke: rpm>=950, no mid-drive stall, mph-tracking on the
# 00:20-00:25 window of UpLeckHillWithKickdown (the 6 mph stall window).
# Exits non-zero on any invariant violation. See scripts/smoke_gearbox.py.
smoke-gearbox: build
@echo "=== [engine-sim-cli] smoke-gearbox: 6 mph stall regression ($(SMOKE_WINDOW_START)-$(SMOKE_WINDOW_END) on $(notdir $(SMOKE_RECORDING))) ==="
@echo " invariants: rpm>=950 (mid-drive), no stall, |sim-tgt|mph<=2 for >=90%"
@scripts/smoke_gearbox.py "$(SMOKE_RECORDING)" \
--start-from $(SMOKE_WINDOW_START) --end-at $(SMOKE_WINDOW_END)
# ---------------------------------------------------------------------------
# sine-knock-smoke — sync-pull audio knock regression test.
#
# Renders a 30s --sine run to a WAV (the true rendered output, captured
# pre-silent-mute by the --output seam) and measures buffer-boundary
# discontinuities. The knock is a mid-waveform restart from the audio ring's
# write index lapping its read index; it shows up as hundreds of large int16
# jumps between adjacent samples. A clean sine has at most a handful of
# startup-transient jumps.
#
# Headless: uses --silent (no audio hardware) and --output (WAV file).
# Fails if discontinuities > 10 OR zero-sample rate > 1% OR RMS < 1000.
# ---------------------------------------------------------------------------
SINE_KNOCK_DUR ?= 30
SINE_KNOCK_WAV := $(BUILD_DIR)/sine-knock-smoke.wav
sine-knock-smoke: build
@echo "=== [engine-sim-cli] sine-knock-smoke: 30s --sine knock regression ==="
@rm -f $(SINE_KNOCK_WAV)
@$(BUILD_DIR)/engine-sim-cli --sine --duration $(SINE_KNOCK_DUR) \
--output $(SINE_KNOCK_WAV) --silent
@echo "--- analyzing $(SINE_KNOCK_WAV) ---"
@python3 scripts/sine_knock_smoke.py $(SINE_KNOCK_WAV)
# ---------------------------------------------------------------------------
# engine-knock-smoke — sync-pull knock regression test on a real engine replay.
#
# Same detector as sine-knock-smoke but exercises the full engine path (2
# input channels + impulse-response convolution) that the owner hears the knock
# on. Renders a C63 AMG replay clip to WAV and runs the discontinuity detector.
# Fails if discontinuities > 10 OR zero-sample rate > 1% OR RMS < 1000.
# ---------------------------------------------------------------------------
ENGINE_KNOCK_DUR ?= 15
ENGINE_KNOCK_WAV := $(BUILD_DIR)/engine-knock-smoke.wav
ENGINE_KNOCK_SCRIPT ?= $(HOME)/vscode/engine-sim-cli/es_new/C63_M156_V4.mr
ENGINE_KNOCK_CAP ?= $(HOME)/vscode/escli.vehicle-sim/captures/PinFixDrive_2026-08-29-1640.csv
engine-knock-smoke: build
@echo "=== [engine-sim-cli] engine-knock-smoke: C63 replay knock regression ==="
@rm -f $(ENGINE_KNOCK_WAV)
@$(BUILD_DIR)/engine-sim-cli --replay-telemetry $(ENGINE_KNOCK_CAP) \
--start-from 00:30 --end-at 00:45 --pin-tau-ms 150 \
--script $(ENGINE_KNOCK_SCRIPT) --auto --silent \
--output $(ENGINE_KNOCK_WAV)
@echo "--- analyzing $(ENGINE_KNOCK_WAV) ---"
@python3 scripts/sine_knock_smoke.py $(ENGINE_KNOCK_WAV)
# Diagnostic bench harness on em-dinner (mph MAE/worst/%>2, gear-per-speed vs
# oracle, rpm-coupling self-calibrated K, stall). Richer detail than the smoke
# test; same metric logic as the acceptance brief.
bench-gearbox: build
@echo "=== [engine-sim-cli] bench-gearbox: diagnostic metrics on $(notdir $(BENCH_RECORDING)) ==="
@scripts/bench_gearbox.py replay "$(BENCH_RECORDING)"
help:
@echo "engine-sim-cli Makefile"
@echo ""
@echo "Targets:"
@echo " make - Build + test (complete pipeline)"
@echo " make gate - FULL pre-commit gate: build + tests + iOS cross + coverage + sonar (fail-fast)"
@echo " make build - Compile everything (no tests)"
@echo " make sonar-scan - Run SonarQube scan with coverage (only re-runs when build/inputs change)"
@echo " make coverage-run - Run CLI tests with coverage instrumentation"
@echo " make coverage-summary - Show local coverage % from lcov.info"
@echo " make sonar-summary - Show SonarCloud issues summary"
@echo " make test - Build then run all tests (full)"
@echo " make test-deep - Run bridge isomorphism + engine-sim physics tests"
@echo " make test-fast - Build then run fast tests (skips 6 heavy groups)"
@echo " make test-quick/testquick - Build then run quick tests only"
@echo " make summary - Print the end-of-make headline (cli line, then bridge line)"
@echo " make presets - Compile .mr wrappers to JSON presets"
@echo " make clean - Clean build artifacts (fast rebuild)"
@echo " make scrub - Remove entire build directory (full clean)"
@echo " make run - Build and run CLI with .mr script"
@echo " make run-json - Build and run CLI with JSON preset"
@echo " make sine-knock-smoke - Sync-pull audio knock regression (30s --sine, fails on knock)"
@echo " make engine-knock-smoke - Sync-pull knock regression on C63 engine replay (fails on knock)"
@echo " make smoke-gearbox - Gearbox regression smoke (6 mph stall window, must stay green)"
@echo " make bench-gearbox - Gearbox diagnostic bench (mph/gear/coupling/stall metrics)"
@echo " make esp32 - Build ESP32 firmware"
@echo " make deploy_esp32 - Flash ESP32 firmware"
@echo " make run_esp32 - Build, flash, and monitor ESP32"
@echo " make help - Show this help"
# ============================================================================
# SonarQube scan + LLVM coverage -- mirrors the bridge's honed model.
#
# build : RelWithDebInfo, tests run via `make test` (separate dir).
# build-cov : RelWithDebInfo + llvm-cov instrumentation, for coverage/sonar.
#
# Coverage runs BEFORE sonar (fresh coverage report). Tests run BEFORE sonar
# (fail-fast). coverage.txt and sonar-report.json are the make targets
# (artefacts, not stamps) -- re-run only on input changes (second make: nothing
# to do). Drops the `|| true` that swallowed test failures. The CLI build-cov
# links the bridge's INSTRUMENTED build-cov archive
# (-DBRIDGE_BUILD_DIR=engine-sim-bridge/build-cov) so coverage attributes bridge
# source lines. DRY: reuses the bridge's run_coverage_tests.sh (recursive glob
# finds CLI build-cov/test/* binaries), sonar_summary.py, coverage_summary.py.
# ============================================================================
# Bridge instrumented lib. The bridge instruments its ``build-cov/`` directory
# (RelWithDebInfo + -fprofile-instr-generate/-fcoverage-mapping), produced by
# the bridge's own coverage-run. The CLI MUST link this instrumented archive
# (NOT the plain build/libenginesim.a) so bridge source lines get a coverage
# mapping — otherwise llvm-cov export emits no SF records for archive-only
# bridge TUs (SimulationLoop, BridgeSimulator, all deserializers, ...) and they
# silently drop to 0% in lcov/Sonar despite being exercised by the CLI binary.
BRIDGE_COV_DIR := $(BRIDGE_DIR)/build-cov
# BRIDGE_BUILD_COV_LIB (defined above) == $(BRIDGE_COV_DIR)/libenginesim.a, so a
# single rule builds it by delegating to the bridge's coverage-run (which
# configures + builds + tests the bridge's instrumented build-cov/).
$(BRIDGE_BUILD_COV_LIB):
+@$(MAKE) -C $(BRIDGE_DIR) coverage-run
@test -e $@ || { echo "ERROR: bridge instrumented lib missing at $@"; exit 1; }
# Coverage build: separate build-cov dir with llvm-cov instrumentation.
# RelWithDebInfo (NOT Debug) + -fprofile-instr-generate/-fcoverage-mapping/-g.
# Points at the bridge's instrumented build-cov/ so coverage attributes bridge
# source. Depends on the bridge instrumented lib existing first (ordering).
# NOTE: `touch CMakeCache.txt` after configure is REQUIRED, not cosmetic (the
# bridge's fix, same war): cmake does not rewrite an unchanged cache file, so
# without the touch the cache mtime never advances past $(BRIDGE_BUILD_COV_LIB)
# (which the bridge's own coverage-run rebuilds independently). Make then
# reconfigures on EVERY invocation, each configure rewrites compile_commands.json,
# and that keeps sonar-report.json permanently stale — the CLI sonar scan
# re-ran on every `make` in this tree until 2026-09-08. The build/ dir escapes
# this only because its check-submodule recipe rewrites state each run.
$(BUILD_COV_DIR)/CMakeCache.txt: CMakeLists.txt $(BRIDGE_BUILD_COV_LIB)
@mkdir -p $(BUILD_COV_DIR)
@cd $(BUILD_COV_DIR) && cmake \
-DCMAKE_BUILD_TYPE=$(BUILD_TYPE_COV) \
-DCMAKE_CXX_FLAGS="-fprofile-instr-generate -fcoverage-mapping -g" \
-DCMAKE_EXE_LINKER_FLAGS="-fprofile-instr-generate" \
-DBUILD_PHASE0_SPIKES=$(BUILD_PHASE0_SPIKES) \
-DCMAKE_SUPPRESS_DEVELOPER_WARNINGS=ON \
-DCMAKE_POLICY_DEFAULT_CMP0091=NEW \
-DBRIDGE_BUILD_DIR=$(CURDIR)/$(BRIDGE_COV_DIR) \
.. && touch CMakeCache.txt
$(BUILD_COV_STAMP): $(BUILD_INPUTS) $(BUILD_COV_DIR)/CMakeCache.txt $(BRIDGE_BUILD_COV_LIB)
@echo "=== [engine-sim-cli] Building coverage (build-cov, RelWithDebInfo+instr) ==="
@cmake --build $(BUILD_COV_DIR) $(CMAKE_BUILD_PARALLEL_FLAG)
@touch $@
@# `touch $@` mirrors the bridge's $(BUILD_COV_STAMP): `cmake --build` only
@# advances the binary mtime when something relinks — on a no-op build the
@# mtime stays put while deps (a freshly-touched CMakeCache, a rebuilt
@# bridge lib) stay newer, and Make would re-run this recipe — and the
@# coverage + sonar chain behind it — forever. Touching the real artefact
@# records "checked with these inputs — no change", settling the chain
@# (same idiom, no .stamp file). The $(BRIDGE_BUILD_COV_LIB) prereq relinks
@# the binary when the bridge's instrumented lib is rebuilt; without it the
@# binary silently stayed stale while the cache rule still reconfigured.
# coverage-run: run CLI tests on the coverage-instrumented build, merge profdata,
# export coverage.txt (llvm-cov text) + lcov.info. File-artefact target: re-runs
# only when build-cov, source inputs, or the coverage script change. The bridge's
# run_coverage_tests.sh uses a recursive glob that finds CLI build-cov/test/*
# binaries (Ninja layout) and writes coverage.txt + lcov.info itself. No `|| true`
# -- the script collects profraw from every binary then surfaces failures at the
# end (honesty gate), so a failing test propagates non-zero.
$(COVERAGE_REPORT): $(BUILD_COV_STAMP) $(BUILD_INPUTS) $(BRIDGE_DIR)/scripts/run_coverage_tests.sh
@LLVM_PROFDATA="$(LLVM_PROFDATA)" LLVM_COV="$(LLVM_COV)" \
COVERAGE_IGNORE_REGEX='engine-sim-bridge/|\.fetchcache/|/dependencies/' \
bash $(BRIDGE_DIR)/scripts/run_coverage_tests.sh $(BUILD_COV_DIR)
coverage-run: $(COVERAGE_REPORT)
sonar-scan: $(SONAR_REPORT)
# SONAR_REPORT depends on the coverage ARTEFACT (coverage.txt), so coverage is
# regenerated (tests re-run) before the scan reads the fresh coverage report.
# Re-scans only when coverage/compile-db/properties/sources change. The curl
# writes SONAR_REPORT itself. NOTE: this sonar-scanner rejects -q, so log output
# is redirected to a file and tailed on failure (the bridge's pattern).
# Derive -Dsonar.branch.name from the current git branch (worktree-aware).
# In a worktree, git rev-parse --abbrev-ref HEAD returns the worktree's branch.
# If derivation fails, FAIL FAST — never publish a branchless scan that
# overwrites SonarCloud master. Master scans remain possible (master -> "master").
BRANCH := $(shell git -C $$(dirname $(abspath $(firstword $(MAKEFILE_LIST)))) rev-parse --abbrev-ref HEAD 2>/dev/null)
ifeq ($(BRANCH),)
$(error SONAR GUARD: cannot derive sonar.branch.name from git (no branch / no git). Refusing to publish a branchless scan.)
endif
ifeq ($(BRANCH),HEAD)
$(error SONAR GUARD: HEAD is detached — cannot derive a branch name. Check out a named branch before scanning.)
endif
SONAR_BRANCH_FLAG := -Dsonar.branch.name=$(BRANCH)
$(SONAR_REPORT): $(COVERAGE_REPORT) $(COMPILE_DB) $(SONAR_PROJECT_PROPERTIES) $(BUILD_INPUTS)
@if [ -z "$${SONAR_TOKEN_ES}" ] && [ -z "$${SONAR_TOKEN}" ]; then \
echo "ERROR: Neither SONAR_TOKEN_ES nor SONAR_TOKEN is set. Run: source ~/.zshrc"; \
exit 1; \
fi
@echo "=== [engine-sim-cli] Running Sonar scan (branch: $(BRANCH)) ==="
@SONAR_TOKEN="$${SONAR_TOKEN_ES:-$${SONAR_TOKEN}}" sonar-scanner \
$(SONAR_BRANCH_FLAG) \
> $(BUILD_COV_DIR)/sonar-scanner.log 2>&1; \
rc=$$?; \
if [ $$rc -ne 0 ]; then \
echo "=== [engine-sim-cli] sonar-scanner failed (rc=$$rc); see $(BUILD_COV_DIR)/sonar-scanner.log ==="; \
tail -n 20 $(BUILD_COV_DIR)/sonar-scanner.log; \
exit $$rc; \
fi
@echo "=== [engine-sim-cli] Waiting for SonarCloud Compute Engine to finish ==="
@TOKEN="$${SONAR_TOKEN_ES:-$${SONAR_TOKEN}}"; \
CETASKID=$$(grep -E '^ceTaskId=' $(BUILD_COV_DIR)/.scannerwork/report-task.txt 2>/dev/null | cut -d= -f2); \
if [ -z "$$CETASKID" ]; then \
echo "ERROR: no ceTaskId in $(BUILD_COV_DIR)/.scannerwork/report-task.txt; cannot confirm analysis settled"; \
exit 1; \
fi; \
echo " CE task: $$CETASKID"; \
dead=0; \
while [ $$dead -lt 60 ]; do \
status=$$(curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/ce/task?id=$$CETASKID" \
| python3 -c "import json,sys; print(json.load(sys.stdin).get('task',{}).get('status',''))" 2>/dev/null); \
if [ "$$status" = "SUCCESS" ]; then \
echo " CE task SUCCESS after $$(($$dead * 2))s"; \
break; \
fi; \
if [ "$$status" = "FAILED" ] || [ "$$status" = "CANCELED" ]; then \
echo "ERROR: SonarCloud CE task $$status (id=$$CETASKID); report did not settle"; \
exit 1; \
fi; \
sleep 2; \
dead=$$((dead + 1)); \
done; \
if [ "$$status" != "SUCCESS" ]; then \
echo "ERROR: CE task did not settle within 120s (id=$$CETASKID)"; \
exit 1; \
fi
@echo "=== [engine-sim-cli] Caching SonarCloud issue report ==="
@TOKEN="$${SONAR_TOKEN_ES:-$${SONAR_TOKEN}}"; \
curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/issues/search?componentKeys=danieljsinclair_engine-sim-cli&ps=500&statuses=OPEN" \
> $(SONAR_REPORT) 2>/dev/null || true
@echo "=== [engine-sim-cli] Caching SonarCloud measures (lines_to_cover) ==="
@TOKEN="$${SONAR_TOKEN_ES:-$${SONAR_TOKEN}}"; \
curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/measures/component?component=danieljsinclair_engine-sim-cli&metricKeys=lines_to_cover,uncovered_lines" \
> $(BUILD_COV_DIR)/sonar-measures.json 2>/dev/null || true
$(COMPILE_DB): $(BUILD_COV_DIR)/CMakeCache.txt
coverage-clean:
@rm -f $(COVERAGE_REPORT) $(COVERAGE_XML) $(SONAR_REPORT) $(BUILD_COV_STAMP) $(BUILD_COV_DIR)/coverage.profdata $(BUILD_COV_DIR)/lcov.info $(BUILD_COV_DIR)/profraw/*.profraw
@rm -rf $(BUILD_COV_DIR)/profraw
sonar-clean:
@rm -f $(SONAR_REPORT) $(SONAR_LIVE)
@rm -rf $(BUILD_COV_DIR)/.scannerwork
# Sonar summary -- display issues from a LIVE SonarCloud report (DRY: bridge script).
# No prereq on $(SONAR_REPORT): this must NEVER trigger a scan. Curls the API
# live at display time (refreshing the cached file) so local counts always
# match the dashboard. If no token, prints a hint.
# SHOW_TYPE_SEVERITY=1 also shows the legacy severity (CRITICAL/MAJOR/MINOR/INFO).
SHOW_TYPE_SEVERITY ?= 0
sonar-summary:
@echo ""
@echo "=== [engine-sim-cli] BEGIN: SonarCloud issues summary ==="
@TOKEN="$${SONAR_TOKEN_ES:-$${SONAR_TOKEN}}"; \
if [ -z "$$TOKEN" ]; then echo " No token"; exit 0; fi; \
curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/issues/search?componentKeys=danieljsinclair_engine-sim-cli&ps=500&statuses=OPEN&facets=impactSeverities" > $(SONAR_LIVE) 2>/dev/null || true; \
curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/issues/search?componentKeys=danieljsinclair_engine-sim-cli&ps=1&resolutions=REMOVED&facets=impactSeverities" > $(SONAR_REMOVED_FACET) 2>/dev/null || true; \
curl -s -u "$$TOKEN:" "https://sonarcloud.io/api/measures/component?component=danieljsinclair_engine-sim-cli&metricKeys=coverage,lines_to_cover,uncovered_lines" > $(SONAR_MEASURES) 2>/dev/null || true; \
python3 engine-sim-bridge/scripts/sonar_summary.py $(SONAR_LIVE) $(if $(filter 1,$(SHOW_TYPE_SEVERITY)),--type-severity,) --label engine-sim-cli --removed-facet $(SONAR_REMOVED_FACET)
@echo "=== [engine-sim-cli] END: SonarCloud issues summary ==="
# Coverage summary -- emit the shared multi-line coverage block (SonarCloud-live
# headline + local lcov + exclusions). DRY: delegates to the bridge's
# scripts/coverage_block.py (shared block-emission helper; contains NONE of the
# bridge's top-5/dead-stripped/ESP32 extras). The local lcov is the honest
# llvm-cov number over /src/ from build-cov/lcov.info. No prereq: this must
# NEVER trigger a scan. Graceful fallback if no token / fetch fails / no local
# file (shows what's available, never crashes).
coverage-summary:
@echo ""
@echo "=== [engine-sim-cli] BEGIN: coverage summary ==="
@python3 engine-sim-bridge/scripts/coverage_block.py \
--project-key danieljsinclair_engine-sim-cli \
--local-cov $(BUILD_COV_DIR)/lcov.info \
--local-type lcov \
--exclusions $(SONAR_PROJECT_PROPERTIES) \
--label "[engine-sim-cli]"
@echo "=== [engine-sim-cli] END: coverage summary ==="
# summary: the end-of-make report (russian doll). Re-prints the four summary
# BLOCKS on EVERY make -- cli coverage-summary + sonar-summary, then the
# bridge's summary-blocks (display-only; cached path included -- found
# 2026-09-08: blocks only printed when the test stage ran, so a cached
# "TESTS UP TO DATE" make showed headlines with no report blocks) -- then the
# CLI's OWN headline line (tests from the teed test.log, coverage from the
# cached sonar-measures JSON -- the same headline coverage_block.py shows,
# sonar from the cached sonar-report.json), and finally recurses into the
# bridge's summary-headline so its line is the LAST row. The block targets
# are cheap display-only (cached JSON / live curl) and NEVER trigger a scan
# or test. Order is SELF-then-submodule so the nesting reads top-down
# (cli, then bridge). Headline greps plain numbers + re-emits coloured -- no
# live re-query, never crashes; missing fields are omitted gracefully.
BUILD_SUMMARY_SCRIPT := engine-sim-bridge/scripts/build_summary.py
summary:
+@$(MAKE) --no-print-directory coverage-summary sonar-summary SUMMARY_QUIET=1
+@$(MAKE) --no-print-directory -C engine-sim-bridge summary-blocks SUMMARY_QUIET=1
@python3 $(BUILD_SUMMARY_SCRIPT) \
--label "[engine-sim-cli]" \
--test-log test.log \
--cov-measures $(SONAR_MEASURES) \
--local-cov $(BUILD_COV_DIR)/lcov.info --local-type lcov \
--sonar-report $(SONAR_LIVE) \
--removed-facet $(SONAR_REMOVED_FACET)
+@$(MAKE) --no-print-directory -C engine-sim-bridge summary-headline SUMMARY_QUIET=1
# ---------------------------------------------------------------------------
# Cross-compilation (caller sets PLATFORM, e.g. OS64, SIMULATOR64)
# Not iOS-aware -- just accepts a platform variable for the CMake toolchain.
# ---------------------------------------------------------------------------
ifdef PLATFORM
CROSS_BUILD_DIR := build-$(PLATFORM)
CROSS_TOOLCHAIN := ios.toolchain.cmake
endif
build-cross: submodules
ifndef PLATFORM
$(error PLATFORM is required. Usage: make build-cross PLATFORM=OS64)
endif
@mkdir -p $(CROSS_BUILD_DIR)
@cd $(CROSS_BUILD_DIR) && cmake \
-DCMAKE_TOOLCHAIN_FILE=$(CROSS_TOOLCHAIN) \
-DPLATFORM=$(PLATFORM) \
-DDEPLOYMENT_TARGET=16.0 \
-DBUILD_TESTS=OFF \
-DBUILD_BRIDGE_TESTS=OFF \
-DBRIDGE_USE_PREBUILT=OFF \
-DCMAKE_BUILD_TYPE=$(BUILD_TYPE) ..
@$(MAKE) -C $(CROSS_BUILD_DIR) engine-sim-cli -j$(shell sysctl -n hw.ncpu 2>/dev/null || echo 4)
clean-cross:
ifdef PLATFORM
@rm -rf $(CROSS_BUILD_DIR)
else
@rm -rf build-OS64 build-SIMULATOR64
endif
# -----------------------------------------------------------------------------
# ESP32 targets (ESP32-S3 + MAX98357A I2S DAC)
# Prerequisites: ESP-IDF installed via EIM
# brew tap espressif/eim && brew install eim && eim install
# Hardware: GPIO 4=BCLK, GPIO 5=LRCLK, GPIO 6=DIN -> MAX98357A
# -----------------------------------------------------------------------------
# Resolve activation: source EIM activation script or legacy export.sh
# idf.py invocation: EIM uses shell aliases (invisible to make's non-interactive shells),
# so we call it directly via the venv python instead.
IDF_VENV_PYTHON := $(shell ls $(HOME)/.espressif/tools/python/v*/venv/bin/python 2>/dev/null | head -1)
IDF_PYTHON ?= $(or $(IDF_VENV_PYTHON),python3)
IDF_PY ?= $(IDF_PYTHON) $(IDF_PATH)/tools/idf.py
define ESP32_ACTIVATE
if [ -f "$(IDF_ACTIVATE)" ]; then . "$(IDF_ACTIVATE)" 2>/dev/null; elif [ -f "$(IDF_PATH)/export.sh" ]; then . "$(IDF_PATH)/export.sh" 2>/dev/null; fi
endef
esp32: submodules
@if [ ! -d "$(IDF_PATH)" ] && [ -z "$(IDF_ACTIVATE)" ]; then \
echo ""; \
echo "ERROR: ESP-IDF not found."; \
echo " Install via EIM: brew tap espressif/eim && brew install eim && eim install"; \
echo " Or set IDF_PATH manually: make esp32 IDF_PATH=/path/to/esp-idf"; \
echo ""; \
exit 1; \
fi
@if [ ! -d $(ESP32_DIR) ]; then \
echo "ERROR: ESP32 project not found at $(ESP32_DIR)/"; \
exit 1; \
fi
@$(ESP32_ACTIVATE) && cd $(ESP32_DIR) && $(IDF_PY) build
deploy_esp32: esp32
@if [ -z "$(ESP32_PORT)" ]; then \
echo "ERROR: No ESP32 serial port found."; \
echo "Connect ESP32 via USB and check /dev/cu.usbserial-*"; \
echo "Or set ESP32_PORT manually: make deploy_esp32 ESP32_PORT=/dev/cu.usbserial-XXXX"; \
exit 1; \
fi
@$(ESP32_ACTIVATE) && cd $(ESP32_DIR) && $(IDF_PY) -p $(ESP32_PORT) flash
run_esp32: deploy_esp32
@$(ESP32_ACTIVATE) && cd $(ESP32_DIR) && $(IDF_PY) -p $(ESP32_PORT) monitor
clean_esp32:
@if [ -d $(ESP32_DIR) ]; then \
rm -rf $(ESP32_DIR)/build; \
fi