cmake_minimum_required(VERSION 3.21)
project(acestep-ggml LANGUAGES C CXX)

# CI cache generation: 2 (2026-07-16). This file is hashed into the GitHub
# Actions build-cache key — bump this comment to force cold builds when the
# cached objects themselves are suspect (v1.1.3 stale-cache mixed-ABI crash,
# issues #82/#83). Routine drift is handled by the .built-commit stamp guard
# in release.yml/cache-warm.yml; this is the manual override.

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# version.h: embed git commit hash into all binaries.
# runs on every build, only rewrites if the hash changed.
set(VERSION_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/version.h")
add_custom_target(version ALL
    COMMAND "${CMAKE_COMMAND}" "-DSRC_DIR=${CMAKE_CURRENT_SOURCE_DIR}" "-DOUTPUT=${VERSION_OUTPUT}"
            -P "${CMAKE_CURRENT_SOURCE_DIR}/tools/version.cmake"
    BYPRODUCTS "${VERSION_OUTPUT}"
    COMMENT "Checking git version"
)

# pthread: required explicitly on older glibc (< 2.34) where libpthread
# is not merged into libc. Modern distros link it implicitly but aarch64
# and older x86_64 toolchains need the explicit dependency.
find_package(Threads REQUIRED)

# Suppress MSVC fopen/sprintf deprecation warnings and Windows.h macro pollution.
# NOMINMAX: prevents Windows.h from defining min/max macros that collide with
#           std::min/std::max (causes C2589 errors in solvers/schedulers).
# WIN32_LEAN_AND_MEAN: reduces Windows.h header bloat.
if(MSVC)
    add_compile_definitions(_CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN)
endif()

# Static MSVC runtime (/MT) for portable release builds.
# Eliminates the VC++ Redistributable dependency for end users.
# Only enable during release builds: -DHOT_STEP_STATIC_RUNTIME=ON
option(HOT_STEP_STATIC_RUNTIME "Use static MSVC runtime (/MT) for portable builds" OFF)
if(HOT_STEP_STATIC_RUNTIME AND MSVC)
    set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
    message(STATUS "MSVC runtime: static (/MT)")
endif()

# Put executables and backend .so in the same directory (build root).
# Without this, ggml defaults to bin/ for .so but executables stay in root,
# and ggml_backend_load_all() can't find the backends at runtime.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})

# macOS rpath: make binaries relocatable (portable release support).
# Without this, CMake bakes the absolute build directory into LC_RPATH,
# which breaks on any machine other than the one that built it.
# @executable_path tells dyld to look for dylibs next to the binary.
if(APPLE)
    set(CMAKE_INSTALL_RPATH "@executable_path")
    set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
    set(CMAKE_MACOSX_RPATH TRUE)
endif()

# Linux rpath: make binaries relocatable (portable release support).
# $ORIGIN tells the dynamic linker to search for .so files next to the binary.
if(UNIX AND NOT APPLE)
    set(CMAKE_INSTALL_RPATH "$ORIGIN")
    set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
endif()

# DiT tensor names can exceed default GGML_MAX_NAME of 64
add_compile_definitions(GGML_MAX_NAME=128)

# Harden: mark fread/fwrite/etc with warn_unused_result on all platforms
if(NOT MSVC)
    add_compile_definitions(_FORTIFY_SOURCE=2)
endif()

# CUDA architectures: cover Turing to Blackwell for distributed binaries (CI: CUDA 13.1 / 12.8).
# The CUDA 12.8 build additionally targets legacy Pascal/Volta (see below).
# Users can override with -DCMAKE_CUDA_ARCHITECTURES=native for local builds.
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
    find_package(CUDAToolkit QUIET)
    # Base arch list: Turing through Lovelace/Ada
    set(CMAKE_CUDA_ARCHITECTURES "75-virtual;80-virtual;86-real;89-real;90-real")
    if(CUDAToolkit_FOUND)
        # Legacy GPUs — Pascal only (sm_60 P100, sm_61 GTX 10xx / P40 / P4).
        # CUDA 12.x can still compile real SASS for these; CUDA 13.0 removed
        # offline compilation support, so they go only into the cuda12.8 variant.
        # Real SASS is required — the 75-virtual PTX above can't JIT backwards
        # onto pre-Turing cards.
        #
        # NOTE: Volta (sm_70) is deliberately EXCLUDED. ggml's mma-based MMQ and
        # flash-attention kernels have no device code for sm_70 (they need
        # Turing+), so a sm_70 build crashes on Volta. Worse, sm_70 SASS is
        # binary-compatible upward to Turing (sm_75), so the driver loads it on
        # 75 cards in preference to JIT-ing the compute_75 PTX — which regressed
        # all Turing users on the cuda12.8 bundle in v1.1.1 (#63). Pascal (major
        # 6) is unaffected since Turing can't load major-6 SASS.
        if(CUDAToolkit_VERSION VERSION_LESS "13.0")
            list(APPEND CMAKE_CUDA_ARCHITECTURES "60-real;61-real")
        endif()
        # Blackwell sm_120a: CUDA 12.8+
        if(CUDAToolkit_VERSION VERSION_GREATER_EQUAL "12.8")
            list(APPEND CMAKE_CUDA_ARCHITECTURES "120a-real")
        endif()
        # Blackwell sm_121a: CUDA 12.9+ (same as upstream GGML)
        if(CUDAToolkit_VERSION VERSION_GREATER_EQUAL "12.9")
            list(APPEND CMAKE_CUDA_ARCHITECTURES "121a-real")
        endif()
    endif()
endif()

# AMD ROCm/HIP (community-contributed, no CI coverage — see engine/buildhip.sh).
#
# GATED ON GGML_HIP DELIBERATELY. The probe must not run on a CUDA build: a
# Linux box with both SDKs installed would set hip_FOUND, and the global
# __HIP_PLATFORM_AMD__ then makes src/gpu.h rewrite cudaMemGetInfo ->
# hipMemGetInfo and link hip::host into a CUDA binary. GGML_HIP is the flag
# that actually selects the backend, so it is the one to key off.
if(GGML_HIP)
    list(APPEND CMAKE_PREFIX_PATH /opt/rocm)
    find_package(hip CONFIG QUIET)

    if(hip_FOUND)
        message(STATUS "building with AMD ROCm support")
        add_compile_definitions(__HIP_PLATFORM_AMD__)
    endif()
endif()

# Disable flash attention (cuda12-volta variant). ggml's mma flash-attention has
# no device code for Volta (sm_70); with this defined the engine takes the manual
# attention path instead. Pair with -DGGML_CUDA_FORCE_CUBLAS=ON (ggml) which
# likewise replaces the mma MMQ kernels. See engine/src/hot-step-build-flags.h.
option(HOT_STEP_DISABLE_FA "Disable flash attention (Volta / pre-Turing GPUs)" OFF)
if(HOT_STEP_DISABLE_FA)
    add_compile_definitions(HOT_STEP_DISABLE_FA)
    message(STATUS "[HOT-Step] Flash attention DISABLED (HOT_STEP_DISABLE_FA)")
endif()

# ggml as subdirectory, inherits GGML_CUDA, GGML_METAL, etc. from cmake flags
# CUDA graphs default on: standalone ggml ships them off. Overridable with
# -DGGML_CUDA_GRAPHS=OFF or at runtime with GGML_CUDA_DISABLE_GRAPHS=1.
if(NOT DEFINED GGML_CUDA_GRAPHS)
    set(GGML_CUDA_GRAPHS_DEFAULT ON)
endif()
# ── HOT-Step's ggml fork ─────────────────────────────────────────────────────
# engine/ggml is pinned to HOT-ggml's hot-step-0.29 branch, which carries the ggml
# changes the engine needs (training ops, BF16 out_prod, quant copies ...) as
# commits; see docs/dev/ggml-fork.md. A plain ggml-org checkout lacks them and
# fails much later, at ace-train's link step, so refuse it here. The usual
# cause is a submodule URL cached from before the fork: `git submodule sync
# -- engine/ggml` then `git submodule update --init engine/ggml` fixes it.
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/ggml/include/ggml.h" _hs_fa_train REGEX "GGML_OP_FLASH_ATTN_TRAIN,")
if(NOT _hs_fa_train)
    message(FATAL_ERROR "[HOT-Step] engine/ggml is not the HOT-ggml fork (no GGML_OP_FLASH_ATTN_TRAIN in ggml.h). Run: git submodule sync -- engine/ggml && git submodule update --init engine/ggml")
endif()

add_subdirectory(ggml)

# cpp-httplib (HTTP server library, used by ace-server)
add_subdirectory(vendor/cpp-httplib)

# Shared compile options and ggml linkage
macro(link_ggml_backends target)
    target_include_directories(${target} PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/src
        ${CMAKE_CURRENT_SOURCE_DIR}
        ${CMAKE_CURRENT_BINARY_DIR}
    )
    target_include_directories(${target} SYSTEM PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/ggml/include
    )
    if(MSVC)
        target_compile_options(${target} PRIVATE /W4 /wd4100 /wd4505)
    else()
        target_compile_options(${target} PRIVATE -Wall -Wextra -Wshadow -Wconversion
                              -Wno-unused-parameter -Wno-unused-function -Wno-sign-conversion)
    endif()
    # CMAKE_DL_LIBS: backend.h's Linux HIP diagnosis dlopen()s the ROCm runtime
    # to name what is missing. Empty on Windows, and on glibc >= 2.34 where
    # dlopen moved into libc — but this repo still targets older glibc (see the
    # Threads note above), which needs the explicit -ldl.
    target_link_libraries(${target} PRIVATE ggml Threads::Threads ${CMAKE_DL_LIBS})
    if(TARGET ggml-base)
        target_link_libraries(${target} PRIVATE ggml-base)
    endif()
    foreach(backend cpu blas cuda metal vulkan)
        if(TARGET ggml-${backend})
            get_target_property(CURRENT_BACKEND_TYPE ggml-${backend} TYPE)
            if (CURRENT_BACKEND_TYPE STREQUAL "MODULE_LIBRARY")
                # DL mode: backend is loaded at runtime via dlopen,
                # skip all link-time deps.
                continue()
            endif()
            target_link_libraries(${target} PRIVATE ggml-${backend})
        endif()
    endforeach()
    add_dependencies(${target} version)
endmacro()

# yyjson (MIT, fast JSON parser/writer)
add_library(yyjson STATIC vendor/yyjson/yyjson.c)
target_include_directories(yyjson PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vendor/yyjson)
if(MSVC)
    target_compile_options(yyjson PRIVATE /W0)
else()
    target_compile_options(yyjson PRIVATE -w)
endif()

# LuaJIT 2.1 (MIT, embedded scripting for the plugin system). vendor/luajit is
# an unmodified source snapshot; it is copied into the build tree and built
# there with its own scripts (msvcbuild.bat / make), so the source stays clean.
# lua52compat gives views a working #; the plugin host is lua-plugin.h.
set(LUAJIT_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/vendor/luajit)
set(LUAJIT_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/luajit)
file(GLOB_RECURSE LUAJIT_INPUTS CONFIGURE_DEPENDS ${LUAJIT_SRC_DIR}/src/*.c ${LUAJIT_SRC_DIR}/src/*.h ${LUAJIT_SRC_DIR}/src/*.dasc)
if(MSVC)
    set(LUAJIT_LIB ${LUAJIT_BUILD_DIR}/src/lua51.lib)
    # cl reads extra options from %CL%: match the engine's MSVC runtime.
    if(CMAKE_MSVC_RUNTIME_LIBRARY MATCHES "DLL$" OR NOT CMAKE_MSVC_RUNTIME_LIBRARY)
        set(LUAJIT_CRT /MD)
    else()
        set(LUAJIT_CRT /MT)
    endif()
    # msvcbuild.bat runs its helpers from the current directory, which
    # NoDefaultCurrentDirectoryInExePath (set in some agent shells) forbids.
    set(LUAJIT_BUILD_CMD ${CMAKE_COMMAND} -E env --unset=NoDefaultCurrentDirectoryInExePath CL=${LUAJIT_CRT}
        cmd /c "cd /d ${LUAJIT_BUILD_DIR}/src && msvcbuild.bat lua52compat static")
else()
    set(LUAJIT_LIB ${LUAJIT_BUILD_DIR}/src/libluajit.a)
    set(LUAJIT_ENV)
    if(APPLE)
        set(LUAJIT_MACOS_TARGET ${CMAKE_OSX_DEPLOYMENT_TARGET})
        if(NOT LUAJIT_MACOS_TARGET)
            set(LUAJIT_MACOS_TARGET 11.0)
        endif()
        set(LUAJIT_ENV MACOSX_DEPLOYMENT_TARGET=${LUAJIT_MACOS_TARGET})
    endif()
    set(LUAJIT_BUILD_CMD ${CMAKE_COMMAND} -E env ${LUAJIT_ENV}
        make -C ${LUAJIT_BUILD_DIR}/src libluajit.a BUILDMODE=static CC=${CMAKE_C_COMPILER}
        "XCFLAGS=-DLUAJIT_ENABLE_LUA52COMPAT -fPIC")
endif()
add_custom_command(
    OUTPUT ${LUAJIT_LIB}
    COMMAND ${CMAKE_COMMAND} -E rm -rf ${LUAJIT_BUILD_DIR}
    COMMAND ${CMAKE_COMMAND} -E copy_directory ${LUAJIT_SRC_DIR} ${LUAJIT_BUILD_DIR}
    COMMAND ${LUAJIT_BUILD_CMD}
    WORKING_DIRECTORY ${LUAJIT_BUILD_DIR}/..
    DEPENDS ${LUAJIT_INPUTS}
    COMMENT "Building LuaJIT"
    VERBATIM)
add_custom_target(luajit-build DEPENDS ${LUAJIT_LIB})
add_library(luajit STATIC IMPORTED GLOBAL)
set_target_properties(luajit PROPERTIES IMPORTED_LOCATION ${LUAJIT_LIB})
target_include_directories(luajit INTERFACE ${LUAJIT_SRC_DIR}/src)
add_dependencies(luajit luajit-build)
if(UNIX AND NOT APPLE)
    target_link_libraries(luajit INTERFACE m dl)
endif()

# CUDAToolkit detection: the find_package at L73 is conditional on
# CMAKE_CUDA_ARCHITECTURES, so on cached re-configures CUDAToolkit_FOUND
# may be unset. Ensure it's always available (SuperSep and the cudart copy
# below test it).
find_package(CUDAToolkit QUIET)

# SuperSep library (STFT front-end + GGML stem models)
add_library(supersep STATIC src/supersep.cpp)
target_include_directories(supersep PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}/vendor/pocketfft
    ${CMAKE_CURRENT_BINARY_DIR}
)
# bs-roformer-ggml.h needs ggml headers/symbols.
target_link_libraries(supersep PUBLIC ggml)
if(MSVC)
    target_compile_options(supersep PRIVATE /W4 /wd4100 /wd4505 /wd4244 /wd4267)
else()
    target_compile_options(supersep PRIVATE -Wall -Wextra -Wno-unused-parameter -Wno-sign-conversion)
endif()

# SuperSep is now pure GGML (bs-roformer-ggml.h / mdx23c-ggml.h) — no ONNX
# Runtime, so it builds and runs on every backend including Vulkan, Metal and
# plain CPU. The definition is kept because supersep.cpp/.h still guard on it.
target_compile_definitions(supersep PUBLIC HOT_STEP_SUPERSEP)
message(STATUS "SuperSep: ENABLED (native GGML)")

if(CUDAToolkit_FOUND)
    target_compile_definitions(supersep PUBLIC GGML_USE_CUDA)
endif()

# TensorRT Native SDK (DiT TRT acceleration + LoRA refitting)
# ─────────────────────────────────────────────────────────────────────────────
# Platform-specific TRT detection:
#   Windows: vendored SDK in engine/deps/tensorrt/ (versioned import libs)
#   Linux:   system-installed TRT packages via find_path/find_library
# The runtime DLLs/SOs are expected on the library search path at runtime.
set(TRT_ENABLED FALSE)

# --- Windows: vendored SDK in engine/deps/tensorrt/ ---
set(_TRT_DEPS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/deps/tensorrt")
if(WIN32 AND EXISTS "${_TRT_DEPS_DIR}/include/NvInfer.h" AND EXISTS "${_TRT_DEPS_DIR}/lib/nvinfer_10.lib")
    set(TRT_ENABLED TRUE)
    set(_TRT_INCLUDE_DIR "${_TRT_DEPS_DIR}/include")
    set(_TRT_LIB_DIR "${_TRT_DEPS_DIR}/lib")
    # Windows vendored SDK ships versioned import libs
    set(_TRT_NVINFER_LIB nvinfer_10)
    set(_TRT_NVONNXPARSER_LIB nvonnxparser_10)
    message(STATUS "[TRT] Found vendored SDK at ${_TRT_DEPS_DIR}")

# --- Linux: system-installed TRT packages ---
elseif(NOT WIN32)
    find_path(_TRT_INCLUDE_DIR
        NAMES NvInfer.h
        PATHS /usr/include/x86_64-linux-gnu /usr/local/include /usr/include
    )
    find_library(_TRT_NVINFER_LIB
        NAMES nvinfer
        PATHS /usr/lib/x86_64-linux-gnu /usr/local/lib /usr/lib
    )
    find_library(_TRT_NVONNXPARSER_LIB
        NAMES nvonnxparser
        PATHS /usr/lib/x86_64-linux-gnu /usr/local/lib /usr/lib
    )
    if(_TRT_INCLUDE_DIR AND _TRT_NVINFER_LIB AND _TRT_NVONNXPARSER_LIB)
        set(TRT_ENABLED TRUE)
        message(STATUS "[TRT] Found system TRT: ${_TRT_NVINFER_LIB}")
    else()
        message(STATUS "[TRT] Not found (install libnvinfer-dev + libnvonnxparsers-dev to enable)")
    endif()
endif()

if(NOT TRT_ENABLED AND WIN32)
    message(STATUS "[TRT] Not found (set engine/deps/tensorrt/ to enable DiT TRT)")
endif()

# Core library (shared between binaries)
add_library(acestep-core STATIC
    src/request.cpp
    src/model-store.cpp
    src/pipeline-lm.cpp
    src/pipeline-synth.cpp
    src/pipeline-synth-ops.cpp
    src/pipeline-understand.cpp
)
if(hip_FOUND)
   target_link_libraries(acestep-core PUBLIC yyjson luajit supersep hip::host)
else()
   target_link_libraries(acestep-core PUBLIC yyjson luajit supersep)
endif()
link_ggml_backends(acestep-core)

# TRT native linkage for DiT acceleration (shared across platforms)
if(TRT_ENABLED)
    target_compile_definitions(acestep-core PUBLIC HOT_STEP_TRT)
    target_include_directories(acestep-core PUBLIC "${_TRT_INCLUDE_DIR}")
    if(_TRT_LIB_DIR)
        target_link_directories(acestep-core PUBLIC "${_TRT_LIB_DIR}")
    endif()
    target_link_libraries(acestep-core PUBLIC ${_TRT_NVINFER_LIB} ${_TRT_NVONNXPARSER_LIB})
    if(WIN32)
        # nvinfer_10.dll / nvonnxparser_10.dll are hundreds of MB and are never
        # part of the release archive — the user fetches them through the Model
        # Manager (see docs/plans/2026-09-11-mm3-trt-dit-shipping.md). A normal
        # /IMPORT link makes the OS loader resolve these DLLs at process start,
        # so ace-server.exe (and every other exe linking acestep-core) would
        # refuse to launch until they're downloaded. /DELAYLOAD defers
        # resolution to first call, so mm3_trt_available()'s own DLL probe runs
        # first and the app starts fine without them.
        target_link_libraries(acestep-core PUBLIC delayimp.lib)
        target_link_options(acestep-core PUBLIC
            /DELAYLOAD:nvinfer_10.dll
            /DELAYLOAD:nvonnxparser_10.dll
        )
    endif()
    # TRT headers include cuda_runtime_api.h — on Linux g++ needs the CUDA
    # include path explicitly (nvcc gets it automatically, but acestep-core
    # compiles as plain C++). Windows CUDA Toolkit puts headers on PATH.
    if(NOT WIN32)
        find_package(CUDAToolkit QUIET)
        if(CUDAToolkit_FOUND)
            target_include_directories(acestep-core PUBLIC ${CUDAToolkit_INCLUDE_DIRS})
            target_link_libraries(acestep-core PUBLIC CUDA::cudart)
            message(STATUS "[TRT] CUDA include: ${CUDAToolkit_INCLUDE_DIRS}")
        endif()
    endif()
    message(STATUS "[TRT] DiT TRT acceleration: ENABLED")
endif()

# acestep-core compiles as plain C++ (not nvcc), but pipeline-synth.cpp includes
# <cuda_runtime.h> for VRAM instrumentation whenever GGML_USE_CUDA is defined
# (propagated from ggml). The host compiler needs the CUDA Toolkit include path
# explicitly on EVERY CUDA build — Linux g++ and Windows MSVC (under Ninja) both
# fail to find it otherwise. (The TRT block above also adds this, but only when
# TRT is enabled, so plain CUDA release builds were missing it.)
if(GGML_CUDA)
    find_package(CUDAToolkit QUIET)
    if(CUDAToolkit_FOUND)
        target_include_directories(acestep-core PUBLIC ${CUDAToolkit_INCLUDE_DIRS})
        target_link_libraries(acestep-core PUBLIC CUDA::cudart)
        message(STATUS "[CUDA] acestep-core include: ${CUDAToolkit_INCLUDE_DIRS}")
    endif()
endif()

# ─────────────────────────────────────────────────────────────────────────────
# TRT-LLM Executor (C++ Executor API for LM inference)
# ─────────────────────────────────────────────────────────────────────────────
# Pre-built TRT-LLM SDK (tensorrt_llm.dll + plugin DLL).
# Auto-detect from engine/trtllm-libs/.
# This is SEPARATE from HOT_STEP_TRT (raw NvInfer for DiT). Both can coexist.
#
# STATUS: DISABLED (2026-06-02). Native Windows TRT-LLM is not viable:
#   - FMHA/XQA cubin embedding requires GCC inline asm (INCBIN), impossible on MSVC
#   - Docker-built engines have Linux platform tags, can't deserialize on Windows
#   - TRT version mismatch between Docker (10.14) and Windows SDK (10.16)
#   - ONNX-rebuilt engines lack TRT-LLM tensor bindings (kv_cache_block_offsets etc.)
# The code remains intact behind #ifdef HOT_STEP_TRTLLM for future WSL2 or
# cross-platform engine support. To re-enable, set HOT_STEP_TRTLLM_ENABLE=ON.
option(HOT_STEP_TRTLLM_ENABLE "Enable TRT-LLM Executor (currently broken on native Windows)" OFF)
set(TRTLLM_ENABLED FALSE)
set(_TRTLLM_LIBS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/trtllm-libs")
set(_TRTLLM_INC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/trtllm-include")
if(HOT_STEP_TRTLLM_ENABLE AND WIN32
         AND EXISTS "${_TRTLLM_LIBS_DIR}/tensorrt_llm.lib"
         AND EXISTS "${_TRTLLM_INC_DIR}/tensorrt_llm/executor/executor.h")
    set(TRTLLM_ENABLED TRUE)
    message(STATUS "[TRT-LLM] Found at ${_TRTLLM_LIBS_DIR}")
    target_compile_definitions(acestep-core PUBLIC HOT_STEP_TRTLLM)
    target_include_directories(acestep-core PUBLIC "${_TRTLLM_INC_DIR}")
    target_link_directories(acestep-core PUBLIC "${_TRTLLM_LIBS_DIR}")
    target_link_libraries(acestep-core PUBLIC tensorrt_llm)
    # NOTE: nvinfer_plugin_tensorrt_llm is loaded dynamically via LoadLibrary
    # in lm-trtllm.h to avoid pulling its dependency chain at process startup.
    message(STATUS "[TRT-LLM] LM Executor: ENABLED")
else()
    if(HOT_STEP_TRTLLM_ENABLE)
        message(STATUS "[TRT-LLM] Not found (set engine/trtllm-libs/ + trtllm-include/ to enable)")
    else()
        message(STATUS "[TRT-LLM] DISABLED (set -DHOT_STEP_TRTLLM_ENABLE=ON to re-enable)")
    endif()
endif()


# ace-synth: full pipeline (text-enc + cond + dit + vae + wav)
add_executable(ace-synth tools/ace-synth.cpp)
target_link_libraries(ace-synth PRIVATE acestep-core)
link_ggml_backends(ace-synth)
# CUDA runtime for TRT DiT path (cudaMalloc, cudaMemcpy, etc.)
if(CUDAToolkit_FOUND)
    if(GGML_STATIC)
        target_link_libraries(ace-synth PRIVATE CUDA::cudart_static)
    else()
        target_link_libraries(ace-synth PRIVATE CUDA::cudart)
    endif()
endif()

# ace-lm: LLM inference (CoT + audio codes)
add_executable(ace-lm tools/ace-lm.cpp)
target_link_libraries(ace-lm PRIVATE acestep-core)
link_ggml_backends(ace-lm)
# CUDA runtime for TRT LM path (cudaMalloc, cudaMemcpy, etc.)
if(CUDAToolkit_FOUND)
    if(GGML_STATIC)
        target_link_libraries(ace-lm PRIVATE CUDA::cudart_static)
    else()
        target_link_libraries(ace-lm PRIVATE CUDA::cudart)
    endif()
endif()

# webui: convert tools/webui/public/index.html.gz to a C header for embedding.
# the .gz is committed to git so the C++ build works without npm.
# to update: cd tools/webui && npm install && npm run build, then rebuild ace-server.
set(WEBUI_INPUT "${CMAKE_CURRENT_SOURCE_DIR}/tools/public/index.html.gz")
set(WEBUI_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/index.html.gz.hpp")
add_custom_command(
    OUTPUT "${WEBUI_OUTPUT}"
    COMMAND "${CMAKE_COMMAND}" "-DINPUT=${WEBUI_INPUT}" "-DOUTPUT=${WEBUI_OUTPUT}" -P "${CMAKE_CURRENT_SOURCE_DIR}/tools/xxd.cmake"
    DEPENDS "${WEBUI_INPUT}"
    COMMENT "Embedding webui into index.html.gz.hpp"
)
set_source_files_properties(${WEBUI_OUTPUT} PROPERTIES GENERATED TRUE)

# hot-step-server: HOT-Step HTTP server (LM + synth endpoints + embedded webui)
# NOTE: upstream ace-server.cpp is kept as reference but NOT compiled.
#       Our server binary is hot-step-server.cpp with extension layer support.
add_executable(ace-server tools/hot-step-server.cpp ${WEBUI_OUTPUT})
target_include_directories(ace-server PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
if(hip_FOUND)
    target_link_libraries(ace-server PRIVATE acestep-core httplib supersep hip::host)
else()
    target_link_libraries(ace-server PRIVATE acestep-core httplib supersep)
endif()
link_ggml_backends(ace-server)
# Every backend's server is one translation unit; it outgrew MSVC's default
# COFF section limit (C1128), as ace-train did. /bigobj lifts it.
if(MSVC)
  target_compile_options(ace-server PRIVATE /bigobj)
endif()
# CUDA runtime for GET /vram (cudaMemGetInfo)
find_package(CUDAToolkit QUIET)
if(CUDAToolkit_FOUND)
    target_compile_definitions(ace-server PRIVATE GGML_USE_CUDA)
    if(GGML_STATIC)
        target_link_libraries(ace-server PRIVATE CUDA::cudart_static)
    else()
        target_link_libraries(ace-server PRIVATE CUDA::cudart)
    endif()
    # Copy CUDA runtime DLL to build dir (needed for portable release builds —
    # end users don't have the CUDA Toolkit, so cudart64_*.dll must ship with the binary)
    if(WIN32)
        get_target_property(_CUDART_LOC CUDA::cudart IMPORTED_LOCATION)
        if(_CUDART_LOC)
            add_custom_command(TARGET ace-server POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy_if_different
                    "${_CUDART_LOC}"
                    "$<TARGET_FILE_DIR:ace-server>"
                COMMENT "Copying cudart DLL for portable release"
            )
        endif()
    endif()
    # Write CUDA version marker next to ace-server (server reads this to
    # select the correct runtime DLLs — cuBLAS/cudart/cuDNN for 12 vs 13)
    file(GENERATE OUTPUT "$<TARGET_FILE_DIR:ace-server>/.cuda-version"
         CONTENT "${CUDAToolkit_VERSION_MAJOR}")
endif()

add_executable(ace-understand tools/ace-understand.cpp)
target_link_libraries(ace-understand PRIVATE acestep-core)
link_ggml_backends(ace-understand)

# quantize: GGUF requantizer (BF16 -> K-quants)
add_executable(quantize tools/quantize.cpp)
link_ggml_backends(quantize)

# neural-codec: Oobleck VAE neural audio codec (encode/decode WAV <-> latent)
add_executable(neural-codec tools/neural-codec.cpp)
link_ggml_backends(neural-codec)

add_executable(dettato-grouper-decode-test tools/dettato-grouper-decode-test.cpp)
target_include_directories(dettato-grouper-decode-test PRIVATE src)
target_link_libraries(dettato-grouper-decode-test PRIVATE yyjson)

# sa3-ggml-test: parity tests for the StableStep GGML SA3 modules vs goldens
add_executable(sa3-ggml-test tools/sa3-ggml-test.cpp)
target_link_libraries(sa3-ggml-test PRIVATE yyjson)
link_ggml_backends(sa3-ggml-test)

# fattn-train-test: parity for GGML_OP_FLASH_ATTN_TRAIN{,_BACK} against the
# autodiff'd dit_attn_f32 chain. docs/plans/fattn-train-spec.md §7.
add_executable(fattn-train-test tools/fattn-train-test.cpp)
target_link_libraries(fattn-train-test PRIVATE yyjson)
link_ggml_backends(fattn-train-test)

# convrot-graph-probe: ConvRot8 forward/backward under repeated CUDA graph
# capture and replay, with a cuBLAS API log check for stream resets. CUDA only.
if(GGML_CUDA AND CUDAToolkit_FOUND)
    add_executable(convrot-graph-probe tools/convrot-graph-probe.cpp)
    link_ggml_backends(convrot-graph-probe)
    target_link_libraries(convrot-graph-probe PRIVATE CUDA::cublas CUDA::cudart)
endif()



# yue2-convrot8-cpu-numeric-test: numeric correctness gate for
# engine/patches/zzzz-yue2-convrot8-cpu.patch -- runs the real CPU
# GGML_OP_CONVROT8{,_BACK} kernels and diffs them, bit for bit, against
# tools/yue2-aitk-reference/convrot_cpu.h's validated scalar oracle.
add_executable(yue2-convrot8-cpu-numeric-test tools/yue2-convrot8-cpu-numeric-test.cpp)
link_ggml_backends(yue2-convrot8-cpu-numeric-test)

# yue2-bf16-round-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real
# GGML_UNARY_OP_BF16_ROUND forward+backward graph on both the CPU and Metal
# backends and diffs them, bit for bit (docs/plans/yue2-joint-training-metal-port.md
# Phase 3, kernel #1). Skips cleanly if no Metal device is present.
add_executable(yue2-bf16-round-metal-numeric-test tools/yue2-bf16-round-metal-numeric-test.cpp)
link_ggml_backends(yue2-bf16-round-metal-numeric-test)

# yue2-silu-back-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real GGML_OP_SILU_BACK
# kernel on both the CPU and Metal backends and diffs them with a tolerance
# (this op involves exp(), so bit-exactness is not the right bar -- see the
# test's own top comment) (docs/plans/yue2-joint-training-metal-port.md
# Phase 3, kernel #2). Skips cleanly if no Metal device is present.
add_executable(yue2-silu-back-metal-numeric-test tools/yue2-silu-back-metal-numeric-test.cpp)
link_ggml_backends(yue2-silu-back-metal-numeric-test)

# yue2-repeat-back-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real GGML_OP_REPEAT_BACK
# kernel on both the CPU and Metal backends and diffs them bit for bit (the
# kernel's summation order matches the CPU oracle exactly, so this is the
# same bar as BF16_ROUND, not a tolerance)
# (docs/plans/yue2-joint-training-metal-port.md Phase 3, kernel #3). Skips
# cleanly if no Metal device is present.
add_executable(yue2-repeat-back-metal-numeric-test tools/yue2-repeat-back-metal-numeric-test.cpp)
link_ggml_backends(yue2-repeat-back-metal-numeric-test)

# yue2-rms-norm-back-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real
# GGML_OP_RMS_NORM_BACK kernel on both the CPU and Metal backends and
# compares with a tolerance (CPU's ggml_float reduction is double precision;
# Apple GPUs have no double support, so the Metal kernel reduces in float32
# instead, the same choice ggml-cuda's own rms_norm_back_f32 already makes --
# see the test file's header for the full derivation)
# (docs/plans/yue2-joint-training-metal-port.md Phase 3, kernel #4). Skips
# cleanly if no Metal device is present.
add_executable(yue2-rms-norm-back-metal-numeric-test tools/yue2-rms-norm-back-metal-numeric-test.cpp)
link_ggml_backends(yue2-rms-norm-back-metal-numeric-test)

# yue2-convrot8-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real GGML_OP_CONVROT8 /
# GGML_OP_CONVROT8_BACK kernels on both the CPU and Metal backends and
# compares with a tolerance (the forward int8 dot product and the backward
# gradient's sequential accumulation order are both still exact/matched --
# see the test file's header -- but the Hadamard rotation's float add/sub
# butterflies can be reassociated under Metal's runtime library compile,
# which leaves MTLCompileOptions.fastMathEnabled at its default true;
# confirmed empirically: every case with use_bf16=false showed ~1 ULP
# diffs, every case with use_bf16=true passed exactly since bf16's ~1/128
# rounding step absorbs that noise)
# (docs/plans/yue2-joint-training-metal-port.md Phase 3, kernel #5). Skips
# cleanly if no Metal device is present.
add_executable(yue2-convrot8-metal-numeric-test tools/yue2-convrot8-metal-numeric-test.cpp)
link_ggml_backends(yue2-convrot8-metal-numeric-test)

# yue2-convrot8-metal-tiled-test: equivalence + timing gate for the tiled
# Metal CONVROT8/_BACK kernels (GGML_METAL_CONVROT8_TILED): legacy vs tiled
# on the same Metal backend (forward bit-exact), small shapes also vs CPU,
# real block/LM-head shapes timed. Skips cleanly without a Metal device.
add_executable(yue2-convrot8-metal-tiled-test tools/yue2-convrot8-metal-tiled-test.cpp)
link_ggml_backends(yue2-convrot8-metal-tiled-test)

# yue2-out-prod-metal-numeric-test: numeric correctness gate for
# engine/patches/zzzzz-metal-training-kernels.patch -- runs the real GGML_OP_OUT_PROD
# kernel (F32-only; this project's LoRA/adapter matmul gradients never
# produce the quantized/F16 src0 variants ggml-cpu's reference also
# implements) on both the CPU and Metal backends and diffs them bit for bit
# (single sequential per-thread accumulation, no cross-thread reduction --
# same bar as REPEAT_BACK, attempted first before falling back to a
# tolerance the way kernel #5 (CONVROT8) had to -- see the test file's
# header)
# (docs/plans/yue2-joint-training-metal-port.md Phase 3, kernel #6). Skips
# cleanly if no Metal device is present.
add_executable(yue2-out-prod-metal-numeric-test tools/yue2-out-prod-metal-numeric-test.cpp)
link_ggml_backends(yue2-out-prod-metal-numeric-test)

# yue2-out-prod-metal-tiled-test: equivalence (tolerance, NOT bit-exact --
# see the test file's own header) + timing gate for the tiled Metal
# OUT_PROD kernel (GGML_METAL_OUT_PROD_TILED). Skips cleanly without Metal.
add_executable(yue2-out-prod-metal-tiled-test tools/yue2-out-prod-metal-tiled-test.cpp)
link_ggml_backends(yue2-out-prod-metal-tiled-test)

# yue2-mul-mat-k32-metal-test: tolerance + timing gate for the f32 K = 32 (LoRA rank)
# mul_mat kernel (GGML_METAL_MM_K32). Skips cleanly without Metal.
add_executable(yue2-mul-mat-k32-metal-test tools/yue2-mul-mat-k32-metal-test.cpp)
link_ggml_backends(yue2-mul-mat-k32-metal-test)

# yue2-nar-op-bench: TFLOPS of the generic ggml Metal mul_mat (q8_0/f16 weights) and
# flash_attn_ext at the YuE2 NAR generation shapes. No model needed.
add_executable(yue2-nar-op-bench tools/yue2-nar-op-bench.cpp)
link_ggml_backends(yue2-nar-op-bench)

# yue2-acc-metal-test: isolates GGML_OP_ACC (autodiff of a view) at real sequence
# lengths, Metal vs CPU -- the op the NaN bisect blamed. Skips without Metal.
add_executable(yue2-acc-metal-test tools/yue2-acc-metal-test.cpp)
link_ggml_backends(yue2-acc-metal-test)



# yue2-bf16-round-fuse-metal-test: bit-exactness gate for the new BF16_ROUND
# epilogue fusion in kernel_bin_fuse (ADD/SUB/MUL immediately followed by a
# single-consumer ggml_bf16_round() now execute as one Metal kernel dispatch
# instead of two). Pure execution-scheduling change -- compares fused-Metal
# output against CPU, covering single ops, an ADD chain (n_fuse>1 + round
# together), the row-broadcast dispatch path, and a multi-consumer case that
# must correctly fall back to the unfused path. Skips cleanly without Metal.
add_executable(yue2-bf16-round-fuse-metal-test tools/yue2-bf16-round-fuse-metal-test.cpp)
link_ggml_backends(yue2-bf16-round-fuse-metal-test)

# yue2-rms-double-round-test: confirms removing the redundant outer
# ggml_bf16_round() in yue2-aitk-graph.h's rms() (the one wrapping
# ggml_rms_norm's output, made redundant by mul_bf16's own internal
# round() of its first argument) is a bit-exact no-op change, since
# bf16_round_cast is idempotent. See engine/tools/yue2-rms-double-round-test.cpp.
add_executable(yue2-rms-double-round-test tools/yue2-rms-double-round-test.cpp)
link_ggml_backends(yue2-rms-double-round-test)

# backend-health-test: logic test for the #242 poisoned-backend probe,
# fault injection (ACE_FAULT_BACKEND_ERROR) and teardown recovery.
add_executable(backend-health-test tools/backend-health-test.cpp)
link_ggml_backends(backend-health-test)
target_compile_definitions(backend-health-test PRIVATE ACE_ENABLE_FAULT_INJECTION)

# yue2-linear-lora-round-test: checks whether removing the seemingly
# redundant round(ctx, x) in yue2-aitk-graph.h's linear() (LoRA branch)
# is actually a bit-exact no-op like the rms() fix was -- unlike that
# case, x here has two consumers (base + LoRA branch), so this checks
# forward AND backward (grad_p/grad_a/grad_b), not just forward.
# See engine/tools/yue2-linear-lora-round-test.cpp.
add_executable(yue2-linear-lora-round-test tools/yue2-linear-lora-round-test.cpp)
link_ggml_backends(yue2-linear-lora-round-test)

# yue2-train-gemm-precision-test: S2a gate for the YuE2 trainer's BF16
# tensor-core GEMMs. Runs yue2_aitk_graph::linear() and the head-loss GEMMs
# at YuE2 shapes, forward and backward, on the BF16 path and the strict-F32
# rollback (YUE2_AITK_PRECISION=strict-f32) and checks they agree within the
# frozen limits. See engine/tools/yue2-train-gemm-precision-test.cpp.
add_executable(yue2-train-gemm-precision-test tools/yue2-train-gemm-precision-test.cpp)
link_ggml_backends(yue2-train-gemm-precision-test)

# yue2-clip-non-finite-test: S2d-1 gate 3 (RESEARCH/YUE2_S2D_TOLERANCES.md) --
# a gradient with one non-finite value must still fail
# Yue2AitkTrainState::clip_gradients() on both the device sum-of-squares path
# (default) and the host rollback (YUE2_AITK_CLIP_HOST=1) on the CPU backend,
# and on a CUDA build also the CUDA clip kernels on the GPU. No checkpoint
# needed. See engine/tools/yue2-clip-non-finite-test.cpp.
add_executable(yue2-clip-non-finite-test tools/yue2-clip-non-finite-test.cpp)
target_include_directories(yue2-clip-non-finite-test PRIVATE src)
target_link_libraries(yue2-clip-non-finite-test PRIVATE yyjson)
link_ggml_backends(yue2-clip-non-finite-test)

# yue2-head-loss-device-test: the head CE/KL device mode (rows already on the
# backend, as the joint step's Yue2AitkArHeadRows feeds it) must match the host
# mode (YUE2_AITK_HEAD_HOST=1) bit for bit. CPU backend only, no checkpoint
# needed. See engine/tools/yue2-head-loss-device-test.cpp.
add_executable(yue2-head-loss-device-test tools/yue2-head-loss-device-test.cpp)
target_include_directories(yue2-head-loss-device-test PRIVATE src)
link_ggml_backends(yue2-head-loss-device-test)

# yue2-mul-bf16-dispatch-profile: diagnostic tool (no PASS/FAIL) that
# measures the real wall-clock cost of mul_bf16()'s 3-dispatch pattern
# (round(a), round(b), mul+round-epilogue) vs a proxy for a fully fused
# 1-dispatch version, at the exact call shapes and count one transformer
# block makes per forward pass -- used to decide whether a BF16_ROUND
# prologue fusion is worth building before building it.
# See engine/tools/yue2-mul-bf16-dispatch-profile.cpp.
add_executable(yue2-mul-bf16-dispatch-profile tools/yue2-mul-bf16-dispatch-profile.cpp)
link_ggml_backends(yue2-mul-bf16-dispatch-profile)





# moss-ggml-test: parity tests for the MOSS-Music captioning port vs fp32
# fixtures (engine/tools/moss-numpy-ref.py documents the same maths in numpy).
add_executable(moss-ggml-test tools/moss-ggml-test.cpp)
target_include_directories(moss-ggml-test PRIVATE src)
link_ggml_backends(moss-ggml-test)

# ace-caption: MOSS-Music captioning CLI (audio -> caption / MM3 caption / lyrics).
# Complements ace-understand, which does the same job through ACE's own VAE+FSQ+LM.
add_executable(ace-caption tools/ace-caption.cpp)
target_link_libraries(ace-caption PRIVATE acestep-core)
link_ggml_backends(ace-caption)

# yue2-probe: bring-up CLI for the YuE2 GGUF loader (engine/src/yue2/yue2-model.h)
# and tokenizer (engine/src/yue2/yue2-tokenizer.h).
# --info/--load: config + tensor counts / actual weight load, no compute graphs.
# --tokenize/--tokenizer-check/--prefix-check: BPE + protocol-assembly bring-up,
# uses bpe.h (which pulls in yyjson.h) and yyjson directly for fixture JSON --
# same dependency sa3-ggml-test already takes for its own JSON fixtures.
# docs/plans/yue2/06-engine-port-plan.md milestone M0. Header-only loader
# (no acestep-core dependency), same posture as moss-ggml-test.
add_executable(yue2-probe tools/yue2-probe.cpp)
# HeartMuLa's tokenizer probe reads a tensor-free GGUF and runs entirely on CPU.
add_executable(heartmula-probe tools/heartmula-probe.cpp)
target_link_libraries(heartmula-probe PRIVATE yyjson)
link_ggml_backends(heartmula-probe)
# HeartCodec decode parity probe (RVQ, flow, scalar decoder) against S1's fixtures.
add_executable(heartcodec-probe tools/heartcodec-probe.cpp)
target_link_libraries(heartcodec-probe PRIVATE yyjson)
link_ggml_backends(heartcodec-probe)
# MM3 refiner parity entry points; implementations follow the frozen torch fixtures.
add_executable(mm3-refiner-mert-probe tools/mm3-refiner-mert-probe.cpp)
target_link_libraries(mm3-refiner-mert-probe PRIVATE yyjson)
link_ggml_backends(mm3-refiner-mert-probe)
add_executable(mm3-refiner-clap-probe tools/mm3-refiner-clap-probe.cpp)
target_link_libraries(mm3-refiner-clap-probe PRIVATE yyjson)
link_ggml_backends(mm3-refiner-clap-probe)
add_executable(mm3-refiner-dit-probe tools/mm3-refiner-dit-probe.cpp)
target_link_libraries(mm3-refiner-dit-probe PRIVATE yyjson)
link_ggml_backends(mm3-refiner-dit-probe)
# MM3 refiner end to end (ModelStore, the four modules, windowing, loudness): fixture parity and behaviour checks.
add_executable(mm3-refiner-probe tools/mm3-refiner-probe.cpp)
target_link_libraries(mm3-refiner-probe PRIVATE acestep-core)
link_ggml_backends(mm3-refiner-probe)
# HeartMuLa text to music through heartmula/pipeline.h; the smoke test's HeartMuLa case.
add_executable(heartmula-generate tools/heartmula-generate.cpp)
target_link_libraries(heartmula-generate PRIVATE yyjson)
link_ggml_backends(heartmula-generate)
# MuLaCover Stage 3a receipts: Qwen style vector parity, cover-module load and refusals.
add_executable(mulacover-check tools/mulacover-check.cpp)
target_link_libraries(mulacover-check PRIVATE yyjson)
link_ggml_backends(mulacover-check)
# HeartMuLa imatrix collection and held-out quant scoring (tools/heartmula-quant-ladder.mjs).
add_executable(heartmula-quant tools/heartmula-quant.cpp)
target_link_libraries(heartmula-quant PRIVATE yyjson)
link_ggml_backends(heartmula-quant)
# HeartCodec encoder (waveform to RVQ codes) parity probe and round trip.
add_executable(heartcodec-encode-probe tools/heartcodec-encode-probe.cpp)
target_link_libraries(heartcodec-encode-probe PRIVATE yyjson)
link_ggml_backends(heartcodec-encode-probe)

add_executable(yue2-vae-lifetime-test tests/test-yue2-vae-lifetime.cpp)
target_link_libraries(yue2-vae-lifetime-test PRIVATE yyjson)
link_ggml_backends(yue2-vae-lifetime-test)
add_executable(yue2-empty-style-test tests/test-yue2-empty-style.cpp)
target_include_directories(yue2-empty-style-test PRIVATE src/yue2)
target_link_libraries(yue2-empty-style-test PRIVATE yyjson)
link_ggml_backends(yue2-empty-style-test)
# yue2-nar-graph.h also contains the optional Lua sampler dispatch. The probe
# includes that header for parity fixtures even though it uses native midpoint.
target_link_libraries(yue2-probe PRIVATE yyjson luajit)
link_ggml_backends(yue2-probe)

# bs-roformer-test: parity test for the GGML BS-RoFormer (SuperSep StableStep
# separation) vs PyTorch goldens. See scripts/dump_bs_roformer_goldens.py.
add_executable(bs-roformer-test tools/bs-roformer-test.cpp)
link_ggml_backends(bs-roformer-test)

# mdx23c-test: parity test for the GGML MDX23C drum separator (SuperSep stage 3).
add_executable(mdx23c-test tools/mdx23c-test.cpp)
link_ggml_backends(mdx23c-test)

# dettato-drums-test: validate the drum stage against the Python oracle.
add_executable(dettato-drums-test tools/dettato-drums-test.cpp)
target_link_libraries(dettato-drums-test PRIVATE yyjson)
link_ggml_backends(dettato-drums-test)

# dettato-repairer-test: validate the evidence repairer against the Python oracle's repairer captures.
add_executable(dettato-repairer-test tools/dettato-repairer-test.cpp)
target_link_libraries(dettato-repairer-test PRIVATE yyjson)
link_ggml_backends(dettato-repairer-test)

# dettato-grouper-test: validate the grouper (features, network, decode) against the oracle and its exact-PCEN reference.
add_executable(dettato-grouper-test tools/dettato-grouper-test.cpp)
target_include_directories(dettato-grouper-test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor/pocketfft)
target_link_libraries(dettato-grouper-test PRIVATE yyjson)
link_ggml_backends(dettato-grouper-test)

# ace-midi: MuScriptor audio->MIDI transcription (GGML port, in development —
# docs/plans/muscriptor-cpp-port.md). Standalone tool, no acestep-core needed.
# libsoxr 0.1.3-14-ga66f3ee (LGPL-2.1, vendor/soxr): the resampler upstream dettato reads its 16 kHz audio through
# (python-soxr 1.0.0), built with python-soxr's options; HQ only needs the float32 engines (soxr-config.h).
set(SOXR_SRC soxr data-io dbesi0 filter fft4g64 cr cr32 fft4g32 cr32s pffft32s util32s)
list(TRANSFORM SOXR_SRC PREPEND ${CMAKE_CURRENT_SOURCE_DIR}/vendor/soxr/src/)
list(TRANSFORM SOXR_SRC APPEND .c)
add_library(soxr STATIC ${SOXR_SRC})
target_include_directories(soxr PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vendor/soxr/src PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor/soxr)
target_compile_definitions(soxr PRIVATE SOXR_LIB $<$<C_COMPILER_ID:MSVC>:_USE_MATH_DEFINES _CRT_SECURE_NO_WARNINGS>)
set_target_properties(soxr PROPERTIES C_STANDARD 99 C_EXTENSIONS ON)
if(MSVC)
    target_compile_options(soxr PRIVATE /W0)
else()
    target_compile_options(soxr PRIVATE -w)
    target_link_libraries(soxr PRIVATE m)
endif()

add_executable(ace-midi tools/ace-midi.cpp)
link_ggml_backends(ace-midi)
target_include_directories(ace-midi PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor/pocketfft)  # dettato grouper's PCEN
target_link_libraries(ace-midi PRIVATE soxr)  # dettato's 16 kHz input
# --abc-out renders through SheetSage2's notation headers, whose event code uses yyjson
target_link_libraries(ace-midi PRIVATE yyjson)

# ace-train: training toolchain (phase 2: dataset tensor preprocessing —
# docs/plans/2026-07-27-preprocess-implementation.md). Standalone tool: every
# engine module it uses is header-only, so no acestep-core link is needed.
add_executable(ace-train tools/ace-train.cpp)
include(${CMAKE_CURRENT_SOURCE_DIR}/src/train/aitk-runtime.cmake)
# One translation unit now carries every trainer plus the SheetSage2
# transcriber (yue2-sheet); with the TensorRT build on, MSVC's default COFF
# section limit overflows (C1128). /bigobj lifts it; no effect elsewhere.
if(MSVC)
  target_compile_options(ace-train PRIVATE /bigobj)
endif()
# luajit is not used by the trainer directly. It is needed because ace-train
# includes minimax/mm3-request.h, which reaches lua-plugin.h transitively via
# mm3-pipeline.h -> mm3-plugins.h, and luajit is what carries vendor/luajit on
# its include path. Every other target that pulls this chain gets it by
# linking acestep-core; ace-train deliberately does not link acestep-core (the
# comment above), so it has to name luajit itself. Without this the build fails
# with "Cannot open include file: 'lua.h'" from lua-plugin.h.
#
# The YuE2 NAR trainer (train/yue2-nar-train-run.h, subcommand yue2-nar-train)
# needs NOTHING extra: engine/src/yue2/ is header-only, link_ggml_backends
# already puts ${CMAKE_CURRENT_SOURCE_DIR}/src on the include path, and the one
# library dependency it drags in — yyjson, via yue2-tokenizer.h -> bpe.h — is
# already named here. yue2-probe links exactly yyjson + ggml, so ace-train's
# dependency set is a strict superset.
target_link_libraries(ace-train PRIVATE yyjson luajit)
link_ggml_backends(ace-train)

# mp3-codec: MP3 encoder/decoder (standalone, no ggml needed)
# The mp3/ headers are header-only and usable by ace-synth too via #include "mp3/mp3enc.h"
add_executable(mp3-codec tools/mp3-codec.cpp)
target_include_directories(mp3-codec PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_BINARY_DIR}
)
add_dependencies(mp3-codec version)
if(MSVC)
    target_compile_options(mp3-codec PRIVATE /W4 /wd4100 /wd4505)
else()
    target_compile_options(mp3-codec PRIVATE -Wall -Wextra -Wconversion
                          -Wno-unused-parameter -Wno-unused-function -Wno-sign-conversion)
    target_link_libraries(mp3-codec PRIVATE m)
endif()
target_link_libraries(mp3-codec PRIVATE Threads::Threads)

# mastering: reference-based audio mastering (standalone, no ggml needed)
# Implements the matchering algorithm using pocketfft for FFT.
add_executable(mastering tools/mastering.cpp)
target_include_directories(mastering PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}/vendor/pocketfft
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_BINARY_DIR}
)
add_dependencies(mastering version)
if(MSVC)
    target_compile_options(mastering PRIVATE /W4 /wd4100 /wd4505 /wd4244 /wd4267)
else()
    target_compile_options(mastering PRIVATE -Wall -Wextra -Wconversion
                          -Wno-unused-parameter -Wno-unused-function -Wno-sign-conversion)
    target_link_libraries(mastering PRIVATE m)
endif()
target_link_libraries(mastering PRIVATE Threads::Threads)

# ─────────────────────────────────────────────────────────────────────────────
# VST3 Hosting Library + vst-host tool
# ─────────────────────────────────────────────────────────────────────────────
# We compile only the necessary VST3 SDK source files for hosting (loading
# plugins, processing audio, state save/restore). We do NOT use the SDK's
# own CMakeLists.txt because it requires cmake 3.25+ and pulls in the full
# build system including plugin examples and VSTGUI.

set(VST3SDK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/vendor/vst3sdk")

# Static library: vst3-hosting
# Platform-specific hosting sources:
#   Windows: module_win32.cpp + threadchecker_win32.cpp
#   macOS:   module_mac.mm (ARC) + threadchecker_mac.mm
#   Linux:   module_linux.cpp + threadchecker_linux.cpp
if(APPLE)
    set(VST3_PLATFORM_SOURCES
        ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/module_mac.mm
        ${VST3SDK_ROOT}/public.sdk/source/common/threadchecker_mac.mm
    )
    # module_mac.mm requires Objective-C ARC
    set_source_files_properties(
        ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/module_mac.mm
        ${VST3SDK_ROOT}/public.sdk/source/common/threadchecker_mac.mm
        PROPERTIES COMPILE_FLAGS "-fobjc-arc"
    )
elseif(WIN32)
    set(VST3_PLATFORM_SOURCES
        ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/module_win32.cpp
        ${VST3SDK_ROOT}/public.sdk/source/common/threadchecker_win32.cpp
    )
else()
    set(VST3_PLATFORM_SOURCES
        ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/module_linux.cpp
        ${VST3SDK_ROOT}/public.sdk/source/common/threadchecker_linux.cpp
    )
endif()

add_library(vst3-hosting STATIC
    # Base library
    ${VST3SDK_ROOT}/base/source/baseiids.cpp
    ${VST3SDK_ROOT}/base/source/fobject.cpp
    ${VST3SDK_ROOT}/base/source/fdebug.cpp
    ${VST3SDK_ROOT}/base/source/fstreamer.cpp
    ${VST3SDK_ROOT}/base/source/fbuffer.cpp
    ${VST3SDK_ROOT}/base/source/updatehandler.cpp
    ${VST3SDK_ROOT}/base/source/timer.cpp
    ${VST3SDK_ROOT}/base/source/fstring.cpp

    # Pluginterfaces
    ${VST3SDK_ROOT}/pluginterfaces/base/funknown.cpp
    ${VST3SDK_ROOT}/pluginterfaces/base/ustring.cpp
    ${VST3SDK_ROOT}/pluginterfaces/base/coreiids.cpp
    ${VST3SDK_ROOT}/pluginterfaces/base/conststringtable.cpp

    # Public SDK hosting (cross-platform + platform-specific)
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/module.cpp
    ${VST3_PLATFORM_SOURCES}
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/hostclasses.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/plugprovider.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/processdata.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/parameterchanges.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/pluginterfacesupport.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/eventlist.cpp
    ${VST3SDK_ROOT}/public.sdk/source/vst/hosting/connectionproxy.cpp

    # Public SDK common (memory streams for state I/O)
    ${VST3SDK_ROOT}/public.sdk/source/common/memorystream.cpp
    ${VST3SDK_ROOT}/public.sdk/source/common/commoniids.cpp
    ${VST3SDK_ROOT}/public.sdk/source/common/pluginview.cpp
    ${VST3SDK_ROOT}/public.sdk/source/common/commonstringconvert.cpp

    # VST interface ID definitions (all DEF_CLASS_IID symbols)
    ${VST3SDK_ROOT}/public.sdk/source/vst/vstinitiids.cpp

    # VST utilities
    ${VST3SDK_ROOT}/public.sdk/source/vst/utility/stringconvert.cpp
)

target_include_directories(vst3-hosting PUBLIC
    ${VST3SDK_ROOT}
    ${VST3SDK_ROOT}/pluginterfaces
    ${VST3SDK_ROOT}/public.sdk
)

# The SDK defines DEVELOPMENT=1 for debug builds
target_compile_definitions(vst3-hosting PRIVATE
    $<$<CONFIG:Debug>:DEVELOPMENT=1>
    $<$<CONFIG:Release>:RELEASE=1>
)

if(MSVC)
    # Suppress noisy SDK warnings
    target_compile_options(vst3-hosting PRIVATE /W0)
else()
    target_compile_options(vst3-hosting PRIVATE -w)
endif()

# macOS: VST3 hosting needs Cocoa + CoreFoundation frameworks
if(APPLE)
    find_library(COCOA_FRAMEWORK Cocoa)
    find_library(COREFOUNDATION_FRAMEWORK CoreFoundation)
    target_link_libraries(vst3-hosting PRIVATE
        ${COCOA_FRAMEWORK}
        ${COREFOUNDATION_FRAMEWORK}
    )
endif()

# vst-host: standalone VST3 host tool (GUI + offline processing + chain)
add_executable(vst-host tools/vst-host.cpp)
target_include_directories(vst-host PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${CMAKE_CURRENT_BINARY_DIR}
    ${VST3SDK_ROOT}
)
target_link_libraries(vst-host PRIVATE vst3-hosting yyjson Threads::Threads)
if(MSVC)
    target_compile_options(vst-host PRIVATE /W4 /wd4100 /wd4505)
    target_compile_definitions(vst-host PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN)
else()
    target_compile_options(vst-host PRIVATE -Wall -Wextra -Wconversion
                          -Wno-unused-parameter -Wno-unused-function -Wno-sign-conversion)
endif()
add_dependencies(vst-host version)

# macOS: vst-host also needs Apple frameworks
if(APPLE)
    target_link_libraries(vst-host PRIVATE ${COCOA_FRAMEWORK} ${COREFOUNDATION_FRAMEWORK})
endif()

# Monitor chain unit test (no VST plugins needed). Off by default so it is not
# part of the ALL build; configure with -DBUILD_TESTING=ON to build and run it.
option(BUILD_TESTING "Build the engine unit tests" OFF)
if(BUILD_TESTING)
    enable_testing()
    # No models or GPU required: residual identity, delta export and legacy load.
    add_executable(pissa-residual-test tests/test-pissa-residual.cpp)
    link_ggml_backends(pissa-residual-test)
    target_link_libraries(pissa-residual-test PRIVATE yyjson)
    add_test(NAME pissa-residual COMMAND pissa-residual-test)
    set_tests_properties(pissa-residual PROPERTIES ENVIRONMENT "GGML_BACKEND=CPU" TIMEOUT 60)

    add_executable(test-monitor-chain tests/test-monitor-chain.cpp)
    add_test(NAME monitor-chain COMMAND test-monitor-chain)

    # wav.h reader: PCM 16/24/32 and float32, classic and EXTENSIBLE headers.
    add_executable(wav-read-test tests/test-wav-read.cpp)
    add_test(NAME wav-read COMMAND wav-read-test)

    add_executable(yue2-lyrics-instrumental-test tests/test-yue2-lyrics-instrumental.cpp)
    add_test(NAME yue2-lyrics-instrumental COMMAND yue2-lyrics-instrumental-test)

    # MM3 planning-stage VRAM ladder (mm3-vram-fit.h): pure arithmetic.
    add_executable(mm3-vram-fit-test tests/test-mm3-vram-fit.cpp)
    add_test(NAME mm3-vram-fit COMMAND mm3-vram-fit-test)

    # DoRA norm-refresh freeze fixture (dora-common.h vs the pre-extraction
    # graphs). GGML_BACKEND picks the device; see the test's header.
    add_executable(dora-common-test tests/test-dora-common.cpp)
    link_ggml_backends(dora-common-test)
    add_test(NAME dora-common COMMAND dora-common-test)

    add_executable(dora-runtime-test tests/test-dora-runtime.cpp)
    link_ggml_backends(dora-runtime-test)
    target_link_libraries(dora-runtime-test PRIVATE yyjson)
    add_test(NAME dora-runtime COMMAND dora-runtime-test)

    # MM3 flow-DiT DoRA trainer/merge parity and the MM3 LM DoRA dial switch.
    # luajit only for its include path: mm3-model.h reaches lua-plugin.h, as
    # ace-train's comment explains.
    add_executable(mm3-dit-dora-test tests/test-mm3-dit-dora.cpp)
    link_ggml_backends(mm3-dit-dora-test)
    target_link_libraries(mm3-dit-dora-test PRIVATE yyjson luajit)
    add_test(NAME mm3-dit-dora COMMAND mm3-dit-dora-test)

    add_executable(sa3-dora-load-test tests/test-sa3-dora-load.cpp)
    link_ggml_backends(sa3-dora-load-test)
    target_link_libraries(sa3-dora-load-test PRIVATE yyjson)
    add_test(NAME sa3-dora-load COMMAND sa3-dora-load-test)
    set_tests_properties(sa3-dora-load PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600)

    # SA3 training gate: one DiT block's backward (placement, finite
    # differences, official-trainer replay). Skips (77) without the replay fixture.
    add_executable(sa3-train-grad-test tests/test-sa3-train-grad.cpp)
    link_ggml_backends(sa3-train-grad-test)
    target_link_libraries(sa3-train-grad-test PRIVATE yyjson)
    add_test(NAME sa3-train-grad COMMAND sa3-train-grad-test)
    set_tests_properties(sa3-train-grad PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600)

    # SA3 trainer parity: full official-trainer steps, AdamW, export round trip,
    # SAME and T5Gemma (ace-train sa3-train-check). Skips (77) without the step
    # fixtures (tools/sa3-training-step-fixture.py) or the converted base DiT.
    set(SA3_TRAIN_DATA ${CMAKE_CURRENT_SOURCE_DIR}/../_experiments/sa3-training)
    add_test(NAME sa3-train-check COMMAND ace-train sa3-train-check --fixtures ${SA3_TRAIN_DATA}/step
             --base-dit ${SA3_TRAIN_DATA}/base/sa3-dit-base-BF16.gguf --models ${CMAKE_CURRENT_SOURCE_DIR}/models)
    set_tests_properties(sa3-train-check PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 1800)

    # YuE2 joint/AITK DoRA graph fixture: LoRA identity at m == nrm, rescale
    # forward/backward, exact vs expanded row norms.
    add_executable(yue2-aitk-dora-test tests/test-yue2-aitk-dora.cpp)
    link_ggml_backends(yue2-aitk-dora-test)
    target_link_libraries(yue2-aitk-dora-test PRIVATE yyjson)
    add_test(NAME yue2-aitk-dora COMMAND yue2-aitk-dora-test)

    # A semantic redraw keeps the supplied score (#234). No GPU, no models.
    add_executable(yue2-recompose-test tools/yue2-recompose-test.cpp)
    target_include_directories(yue2-recompose-test PRIVATE src)
    target_link_libraries(yue2-recompose-test PRIVATE yyjson luajit)
    link_ggml_backends(yue2-recompose-test)
    add_test(NAME yue2-recompose COMMAND yue2-recompose-test)

    # A semantic draw outside the codec range ends the stream (#367). No GPU, no models.
    add_executable(yue2-semantic-draw-test tools/yue2-semantic-draw-test.cpp)
    target_include_directories(yue2-semantic-draw-test PRIVATE src)
    target_link_libraries(yue2-semantic-draw-test PRIVATE yyjson luajit)
    link_ggml_backends(yue2-semantic-draw-test)
    add_test(NAME yue2-semantic-draw COMMAND yue2-semantic-draw-test)

    # plan_continue: request parse, section stop rule, tokenizer prefix
    # property. No GPU, no model; the tokenizer part needs YUE2_TOKENIZER_DIR
    # (the yue2/tokenizer folder) and skips (77) without it.
    add_executable(yue2-plan-continue-test tests/test-yue2-plan-continue.cpp)
    target_include_directories(yue2-plan-continue-test PRIVATE src/yue2)
    target_link_libraries(yue2-plan-continue-test PRIVATE yyjson)
    link_ggml_backends(yue2-plan-continue-test)
    add_test(NAME yue2-plan-continue COMMAND yue2-plan-continue-test)
    set_tests_properties(yue2-plan-continue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
endif()

# Keep this after every executable, including optional test targets. Enable
# long paths and UTF-8 narrow file APIs throughout each engine process.
if(MSVC)
    get_property(_hs_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS)
    foreach(_hs_target IN LISTS _hs_targets)
        get_target_property(_hs_type ${_hs_target} TYPE)
        if(_hs_type STREQUAL "EXECUTABLE")
            target_sources(${_hs_target} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/long-paths.manifest)
        endif()
    endforeach()
endif()
