From 3b5d28d7b0a1edc7abc4e7d95c55358e7d0b80c4 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sun, 6 Dec 2026 20:09:50 +0300 Subject: [PATCH] feat(profiles): per-dependency overrides, toolchain pin and profile CLI (G3) - Dependency::profile(name, DependencyProfileOptions) records per-profile compile/link options, defines, LTO and sanitizers. The native provider applies the matching override to the dependency's own ProfileContext and hashes the overrides into the provider input hash, so changing them invalidates cached dependency builds. - vbs-toolchain.toml pins compiler, minimum version, C/C++ standards and sysroot (optional strict); it is loaded once and checked after every toolchain probe. Drift warns by default and fails with --locked-toolchain or strict = true; malformed pins fail with the TOML diagnostic. - vbs profile list|show|diff lists declared profiles with parents, prints a resolved profile (flags, standards, LTO, sanitizers, sysroot) or the fields that differ between two. Verified: dependency_profile_overrides_apply_to_native_builds (a define from the override is required by the dependency source), toolchain_pin_detects_and_enforces_drift and profile_commands_list_show_and_diff pass; vbs_core_tests 8/8; CLI contracts pass; clang-format clean. --- CMakeLists.txt | 1 + docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/roadmap/24-superiority-tracks.md | 8 + include/Void/Build.hpp | 12 ++ include/Void/Build/Toolchain/Pin.hpp | 43 +++++ sdk/Build.cpp | 32 ++++ src/Graph/Graph.cpp | 26 ++++ src/Main.cpp | 216 ++++++++++++++++++++++++++ src/Provider/Provider.cpp | 53 ++++++- src/Toolchain/Pin.cpp | 162 +++++++++++++++++++ tests/CliContracts.cmake | 6 + tests/FullV1Tests.cpp | 144 +++++++++++++++++ 13 files changed, 702 insertions(+), 4 deletions(-) create mode 100644 include/Void/Build/Toolchain/Pin.hpp create mode 100644 src/Toolchain/Pin.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 947c063..b9f893c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,6 +44,7 @@ add_library(VoidBuild_Core STATIC src/Platform/Linux/FileOps.cpp src/Platform/Linux/ProcessSupervisor.cpp src/Toolchain/Driver.cpp + src/Toolchain/Pin.cpp src/Snapshot/Snapshot.cpp src/State/StateStore.cpp src/State/RemoteCache.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 1176297..19d6681 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -401,6 +401,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope +- **Wave 151 (Profiles and toolchain pinning, G3)**: `Dependency::profile(name, DependencyProfileOptions)` stores per-profile compile/link options, defines, LTO and sanitizers; the native provider applies the matching override to the dependency's own `ProfileContext` and includes the overrides in the provider input hash, so changing them invalidates cached dependency builds. `vbs-toolchain.toml` pins compiler, minimum version, C/C++ standards and sysroot (with a `strict` field); it is loaded once per build and checked after every toolchain probe, warning on drift or failing with `--locked-toolchain` (or `strict = true`). `vbs profile list|show|diff` lists declared profiles with parents, prints one resolved profile, or reports the fields that differ between two. Verified by `FullV1Tests.dependency_profile_overrides_apply_to_native_builds`, `toolchain_pin_detects_and_enforces_drift` and `profile_commands_list_show_and_diff`. + - **Wave 150 (Real feature flags, G2)**: `Project::feature(name, default_on)` (or `FeatureDescription`), `Target::require_feature(name)` (renamed because `requires` is a C++20 keyword), and `Dependency::when(feature)` for optional dependencies. `--features a,b` / `--no-default-features` on build/test/run/explain/deps (or `VBS_FEATURE`-style CLI only) perform additive unification: defaults (unless disabled) + features required by targets + requested features; enabled features add `VBS_FEATURE_` compile definitions to every target (so action keys and the cache are feature-aware) and the descriptor JSON/`vbs metadata` expose declared features with their enabled state. Optional dependencies are filtered before resolution, so the lock contains only active ones; `vbs explain --show-features` prints the unified set with reasons (default/requested/required by target). Verified by `FullV1Tests.features_unify_defines_and_invalidate_action_keys` and `FullV1Tests.optional_dependencies_follow_feature_selection`. - **Wave 149 (Trust layer, G5 start)**: `vbs attest create|verify` produces and verifies DSSE-wrapped in-toto Statement v1 / SLSA provenance v1 attestations (subjects, build definition with project/profile/targets/lock revision, internal parameters, run details) signed with the existing Ed25519 primitives; verification requires a trusted key, checks the DSSE PAE signature and requires every supplied artifact digest to be covered. `vbs audit --advisories OSV.json` matches OSV records (introduced/fixed/last_affected/limit ranges and exact versions) against `vbs.lock` packages with a severity threshold and JSON output; `vbs doctor` reports the signing backend. Unsignable hosts fail closed. Verified by `FullV1Tests.attest_create_and_verify_detects_tampering` (valid, wrong artifact, tampered payload, untrusted key, missing keys) and `FullV1Tests.audit_matches_osv_advisories_against_lock` (affected/fixed versions, severity thresholds, JSON). diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 5616634..ccbfa45 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -150,4 +150,5 @@ Base HEAD: `fe0d1a6` | Wave 148 (Hermetic sandboxing) | `Sandbox::sandbox_supported`, `Sandbox::apply_sandbox`, hidden `vbs __sandbox-exec` wrapper, `--sandbox=off|warn|strict`/`VBS_SANDBOX`, project read-only + build root writable + system/toolchain roots read-only, doctor reporting, CI strict smoke step | COMPLETE & VERIFIED (GCC 16.2; `sandbox_strict_allows_project_builds_and_hides_outside_files` passes: strict build succeeds and an action reading an outside file fails; CLI contracts pass) | `include/Void/Build/Sandbox/Sandbox.hpp`, `src/Sandbox/Linux/NamespaceSandbox.cpp`, `include/Void/Build/Execution/Scheduler.hpp`, `src/Execution/Scheduler.cpp`, `src/Main.cpp`, `.gitea/workflows/ci.yml`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 149 (Trust layer) | `vbs attest create\|verify` (DSSE + in-toto Statement v1 + SLSA provenance v1, Ed25519 over the PAE, trusted-key and subject-digest enforcement), `vbs audit --advisories OSV.json` (introduced/fixed/last_affected/limit ranges, severity threshold, JSON), signing availability in `vbs doctor` | COMPLETE & VERIFIED (GCC 16.2; `attest_create_and_verify_detects_tampering` and `audit_matches_osv_advisories_against_lock` pass; CLI contracts pass) | `include/Void/Build/Provenance/Attestation.hpp`, `src/Provenance/Attestation.cpp`, `include/Void/Build/Package/Audit.hpp`, `src/Package/Audit.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 150 (Feature flags) | `Project::feature`, `Target::require_feature`, `Dependency::when`, additive unification, `--features`/`--no-default-features`, `VBS_FEATURE_*` defines, feature-aware action keys, optional dependency filtering, `explain --show-features`, metadata feature list | COMPLETE & VERIFIED (GCC 16.2; `features_unify_defines_and_invalidate_action_keys` and `optional_dependencies_follow_feature_selection` pass; CLI contracts pass) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `include/Void/Build/Graph/Graph.hpp`, `src/Graph/Graph.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | +| Wave 151 (Profiles + toolchain pinning) | `Dependency::profile` overrides for native dependency builds (hash-aware), `vbs-toolchain.toml` pin + drift detection (`--locked-toolchain`, `strict`), `vbs profile list\|show\|diff` | COMPLETE & VERIFIED (GCC 16.2; the three G3 tests pass; CLI contracts pass) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Graph/Graph.cpp`, `src/Provider/Provider.cpp`, `include/Void/Build/Toolchain/Pin.hpp`, `src/Toolchain/Pin.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index 51a00a0..58b134c 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -217,6 +217,14 @@ to additive preprocessor-visible configuration and documents the rule. ### G3 — Profiles, per-package overrides and toolchain pinning *(M)* +**Status: implemented (Wave 151).** `Dependency::profile(name, DependencyProfileOptions)` +(compile/link options, defines, LTO, sanitizers) is applied by the native provider to the +dependency's own `ProfileContext` and included in the provider input hash; `vbs-toolchain.toml` +pins compiler/minimum version/C and C++ standards/sysroot and is checked after probing (warn, or +fail with `--locked-toolchain` or `strict = true`); `vbs profile list|show|diff` covers +inheritance inspection and resolved flags. Foreign providers (CMake/Meson) still receive only +their options map; mapping per-profile overrides onto their build types is future work. + **Beats:** Cargo (per-package profile overrides), CMake/Meson (no per-package profiles). **Work items.** diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp index 61ed65a..c6549c0 100644 --- a/include/Void/Build.hpp +++ b/include/Void/Build.hpp @@ -86,6 +86,15 @@ struct FeatureDescription { std::string description; }; +// Per-profile overrides applied to a dependency's own build (Tracks G3). +struct DependencyProfileOptions { + std::vector compile_options; + std::vector link_options; + std::vector defines; + std::optional lto; + std::vector sanitizers; +}; + struct ProfileDescription { std::string name; std::vector compile_options; @@ -240,6 +249,7 @@ struct DependencyRecord { std::string sha256; std::vector features; std::string required_feature; // Optional dependency: only used when this feature is on. + std::map> profile_overrides; bool build_dependency{false}; }; @@ -345,6 +355,8 @@ class Dependency { Dependency &feature(std::string name); // Optional dependency: resolved only when the project feature is enabled. Dependency &when(std::string feature); + // Per-profile overrides for the dependency's own build (e.g. its release profile). + Dependency &profile(std::string profile, DependencyProfileOptions options = {}); Dependency &build_dependency(bool is_build_tool = true); [[nodiscard]] ImportedTarget target(std::string exported_name) const; [[nodiscard]] const DependencyRecord &record() const; diff --git a/include/Void/Build/Toolchain/Pin.hpp b/include/Void/Build/Toolchain/Pin.hpp new file mode 100644 index 0000000..990b246 --- /dev/null +++ b/include/Void/Build/Toolchain/Pin.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::Toolchain { + +// `vbs-toolchain.toml`: a project-level toolchain contract checked after probing the compiler. +struct ToolchainPin { + std::string compiler; // "gcc" or "clang" (empty = unconstrained) + std::string version; // minimum compiler version, e.g. "16.2" + std::string cxx_standard; // e.g. "cxx26" (also accepts "c++26") + std::string c_standard; // e.g. "c17" + std::string sysroot; // exact sysroot path when set + bool strict{false}; // fail on drift even without --locked-toolchain +}; + +// Loads `/vbs-toolchain.toml`; nullopt when the file does not exist. +[[nodiscard]] Void::Result::Result, Void::Result::Error> +load_toolchain_pin(const std::filesystem::path &project_root); + +struct ToolchainDrift { + std::vector differences; + [[nodiscard]] bool empty() const noexcept { return differences.empty(); } +}; + +// Compares the resolved profile and probe against the pin. A minimum version is satisfied by any +// equal or newer version. +[[nodiscard]] ToolchainDrift check_toolchain_pin(const ToolchainPin &pin, + const ProfileContext &profile, + const ToolchainCapabilities &toolchain); + +// Parses a version prefix ("16.2.0" -> {16,2,0}); empty when no digits are present. +[[nodiscard]] std::vector parse_version_prefix(std::string_view text); + +} // namespace Void::Build::Toolchain diff --git a/sdk/Build.cpp b/sdk/Build.cpp index 11bbcd2..56696d5 100644 --- a/sdk/Build.cpp +++ b/sdk/Build.cpp @@ -133,6 +133,29 @@ std::string scoped_options_json(const std::vector &opts) { }); } +std::string dependency_profile_overrides_json( + const std::map> &overrides) { + std::string out{"{"}; + bool first = true; + for (const auto &[profile_name, options] : overrides) { + if (!first) { + out += ','; + } + first = false; + out += json_quote(profile_name) + ":{\"compile_options\":" + + json_array(options.compile_options, json_quote) + ",\"link_options\":" + + json_array(options.link_options, json_quote) + ",\"defines\":" + + json_array(options.defines, json_quote) + ",\"sanitizers\":" + + json_array(options.sanitizers, + [](Sanitizer s) { return json_quote(sanitizer_name(s)); }); + if (options.lto) { + out += ",\"lto\":" + json_quote(lto_mode_name(*options.lto)); + } + out += '}'; + } + return out + '}'; +} + std::string install_rule_json(const InstallRule &rule) { return "{\"target_name\":" + json_quote(rule.target_name) + ",\"source_path\":" + json_quote(rule.source_path) + @@ -1084,6 +1107,13 @@ Dependency &Dependency::when(std::string feature) { return *this; } +Dependency &Dependency::profile(std::string profile_name, DependencyProfileOptions options) { + require_text(profile_name, "dependency profile name"); + owner(owner_)->dependencies.at(index_).profile_overrides[std::move(profile_name)] = + std::move(options); + return *this; +} + Dependency &Dependency::build_dependency(bool is_build_tool) { owner(owner_)->dependencies.at(index_).build_dependency = is_build_tool; return *this; @@ -1417,6 +1447,8 @@ std::string Project::to_json() const { ",\"registry_authority\":" + json_quote(dependency.registry_authority) + ",\"features\":" + json_array(dependency.features, json_quote) + ",\"required_feature\":" + json_quote(dependency.required_feature) + + ",\"profile_overrides\":" + + dependency_profile_overrides_json(dependency.profile_overrides) + ",\"build_dependency\":" + std::string{dependency.build_dependency ? "true" : "false"} + '}'; return result; diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index febb006..be13269 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -418,6 +418,32 @@ ProjectDescription::from_json(std::string_view json_text) { d.registry_authority = get_str(*do_obj, "registry_authority"); d.features = get_str_array(*do_obj, "features"); d.required_feature = get_str(*do_obj, "required_feature"); + if (const auto *overrides_v = find_key(*do_obj, "profile_overrides"); + overrides_v != nullptr) { + if (const auto *overrides = + std::get_if(&overrides_v->value)) { + for (const auto &[profile_name, override_value] : *overrides) { + const auto *entry = + std::get_if(&override_value.value); + if (entry == nullptr) { + continue; + } + DependencyProfileOptions options; + options.compile_options = + get_str_array(*entry, "compile_options"); + options.link_options = get_str_array(*entry, "link_options"); + options.defines = get_str_array(*entry, "defines"); + if (const std::string lto = get_str(*entry, "lto"); + !lto.empty()) { + options.lto = parse_lto_mode(lto); + } + for (const auto &s : get_str_array(*entry, "sanitizers")) { + options.sanitizers.push_back(parse_sanitizer(s)); + } + d.profile_overrides[profile_name] = std::move(options); + } + } + } d.build_dependency = get_bool(*do_obj, "build_dependency", false); if (const auto *src_v = find_key(*do_obj, "source")) { if (const auto *so = std::get_if(&src_v->value)) { diff --git a/src/Main.cpp b/src/Main.cpp index 245cc23..36a5139 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -463,6 +464,7 @@ struct BuildCmdOptions { std::vector features; bool no_default_features{false}; bool show_features{false}; + bool locked_toolchain{false}; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -828,6 +830,11 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cerr << "vbs: " << compiled.error().message() << '\n'; return 1; } + auto toolchain_pin = Toolchain::load_toolchain_pin(project_root); + if (!toolchain_pin) { + std::cerr << "vbs: " << toolchain_pin.error().message() << '\n'; + return 1; + } Void::Log::info("Config", "Build description {} ({:.0f} ms)", compiled->recompiled ? "compiled" : "up to date (cached)", cfg_sw.elapsed_ms()); trace_phase("config", "phase", cfg_sw.elapsed_ms(), "compile the build description"); @@ -938,6 +945,22 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { tc->native_cache_executable = native_cache->string(); } trace_phase("toolchain", "phase", tc_sw.elapsed_ms(), "discover and probe the toolchain"); + if (toolchain_pin->has_value()) { + const auto drift = Toolchain::check_toolchain_pin(**toolchain_pin, ctx, *tc); + if (!drift.empty()) { + const bool strict = opts.locked_toolchain || (*toolchain_pin)->strict; + for (const auto &difference : drift.differences) { + if (strict) { + std::cerr << cmd_name << ": toolchain pin: " << difference << '\n'; + } else { + Void::Log::warn("Toolchain", "pin drift: {}", difference); + } + } + if (strict) { + return 1; + } + } + } Void::Log::info("Toolchain", "[{}] Using {} ({}) [{}]", prof_name, compiler_name(tc->family), tc->cxx_compiler.string(), tc->version_banner); @@ -5250,6 +5273,176 @@ int execute_audit_command(const AuditCmdOptions &opts) { return findings.empty() ? 0 : 1; } +struct ProfileCmdOptions { + std::string project_arg{"."}; + std::optional build_arg; + std::optional compiler_arg; + std::string profile_arg; + std::vector diff_args; +}; + +std::string join_options(const std::vector &values) { + if (values.empty()) { + return ""; + } + std::string out; + for (const auto &value : values) { + if (!out.empty()) { + out += ' '; + } + out += value; + } + return out; +} + +std::string describe_profile(const ProfileContext &profile) { + std::string out; + out += "name: " + profile.name + '\n'; + out += "compiler: " + std::string{compiler_name(profile.compiler)} + '\n'; + out += "os: " + profile.os + '\n'; + out += "architecture: " + profile.architecture + '\n'; + out += "c_standard: " + std::string{c_standard_name(profile.c_standard)} + '\n'; + out += "cxx_standard: " + std::string{cxx_standard_name(profile.cxx_standard)} + '\n'; + out += "lto: " + std::string{lto_mode_name(profile.lto)} + '\n'; + std::string sanitizers; + for (const auto sanitizer : profile.sanitizers) { + if (!sanitizers.empty()) { + sanitizers += ' '; + } + sanitizers += sanitizer_name(sanitizer); + } + out += "sanitizers: " + (sanitizers.empty() ? std::string{""} : sanitizers) + '\n'; + out += "compile_options: " + join_options(profile.compile_options) + '\n'; + out += "link_options: " + join_options(profile.link_options) + '\n'; + out += "defines: " + join_options(profile.defines) + '\n'; + out += "sysroot: " + (profile.sysroot.empty() ? std::string{""} : profile.sysroot) + '\n'; + out += "compiler_path: " + + (profile.compiler_path.empty() ? std::string{""} : profile.compiler_path) + '\n'; + return out; +} + +int execute_profile_command(std::string_view sub, const ProfileCmdOptions &opts) { + if (sub == "show" && opts.profile_arg.empty()) { + std::cerr << "vbs profile show: a profile name is required\n"; + return 2; + } + if (sub == "diff" && opts.diff_args.size() != 2) { + std::cerr << "vbs profile diff: exactly two profile names are required\n"; + return 2; + } + std::optional compiler_override; + if (opts.compiler_arg) { + try { + compiler_override = parse_compiler(*opts.compiler_arg); + } catch (const std::exception &ex) { + std::cerr << "vbs profile: " << ex.what() << '\n'; + return 2; + } + } + const std::filesystem::path project_root{opts.project_arg}; + const std::filesystem::path build_root = + opts.build_arg ? std::filesystem::path{*opts.build_arg} : (project_root / "build"); + const auto fopts = make_frontend_opts(project_root, build_root, {}); + auto compiled = Config::compile_descriptor(fopts); + if (!compiled) { + std::cerr << "vbs profile: " << compiled.error().message() << '\n'; + return 1; + } + auto profiles = Config::discover_profiles(*compiled, fopts); + if (!profiles) { + std::cerr << "vbs profile: " << profiles.error().message() << '\n'; + return 1; + } + const auto resolve = [&](const std::string &name, + ProfileContext &out) -> std::optional { + try { + out = profiles->resolve(name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + return std::nullopt; + } catch (const std::exception &ex) { + return std::string{ex.what()}; + } + }; + if (sub == "list") { + for (const auto &record : profiles->records()) { + std::cout << record.name; + if (record.parent) { + std::cout << " parent=" << *record.parent; + } + if (record.compiler) { + std::cout << " compiler=" << compiler_name(*record.compiler); + } + if (record.cxx_standard) { + std::cout << " cxx=" << cxx_standard_name(*record.cxx_standard); + } + if (record.lto) { + std::cout << " lto=" << lto_mode_name(*record.lto); + } + if (!record.sanitizers.empty()) { + std::cout << " sanitizers=" << record.sanitizers.size(); + } + std::cout << '\n'; + } + return 0; + } + if (sub == "show") { + if (opts.profile_arg.empty()) { + std::cerr << "vbs profile show: a profile name is required\n"; + return 2; + } + ProfileContext resolved; + if (auto error = resolve(opts.profile_arg, resolved)) { + std::cerr << "vbs profile: " << *error << '\n'; + return 2; + } + std::cout << describe_profile(resolved); + return 0; + } + if (sub == "diff") { + if (opts.diff_args.size() != 2) { + std::cerr << "vbs profile diff: exactly two profile names are required\n"; + return 2; + } + ProfileContext left; + ProfileContext right; + if (auto error = resolve(opts.diff_args[0], left)) { + std::cerr << "vbs profile: " << *error << '\n'; + return 2; + } + if (auto error = resolve(opts.diff_args[1], right)) { + std::cerr << "vbs profile: " << *error << '\n'; + return 2; + } + std::size_t differences = 0; + const auto compare = [&](std::string_view field, std::string_view a, + std::string_view b) { + if (a != b) { + ++differences; + std::cout << field << ": " << left.name << "='" << a << "' " << right.name + << "='" << b << "'\n"; + } + }; + compare("compiler", compiler_name(left.compiler), compiler_name(right.compiler)); + compare("c_standard", c_standard_name(left.c_standard), c_standard_name(right.c_standard)); + compare("cxx_standard", cxx_standard_name(left.cxx_standard), + cxx_standard_name(right.cxx_standard)); + compare("lto", lto_mode_name(left.lto), lto_mode_name(right.lto)); + compare("compile_options", join_options(left.compile_options), + join_options(right.compile_options)); + compare("link_options", join_options(left.link_options), + join_options(right.link_options)); + compare("defines", join_options(left.defines), join_options(right.defines)); + compare("sysroot", left.sysroot.empty() ? "" : left.sysroot, + right.sysroot.empty() ? "" : right.sysroot); + if (differences == 0) { + std::cout << "profiles are equivalent\n"; + } + return 0; + } + std::cerr << "vbs profile: unknown subcommand '" << sub << "' (expected list, show or diff)\n"; + return 2; +} + struct InitCmdOptions { std::string dir_arg; std::optional name_arg; @@ -5904,6 +6097,7 @@ int main(int argc, char **argv) { InstallBinaryCmdOptions install_binary_opts; AttestCmdOptions attest_opts; AuditCmdOptions audit_opts; + ProfileCmdOptions profile_opts; CompletionsCmdOptions completions_opts; ManCmdOptions man_opts; IdeCmdOptions ide_opts; @@ -5990,6 +6184,8 @@ int main(int argc, char **argv) { build_opts.features) .flag("--no-default-features", "", "Disable default project features", build_opts.no_default_features) + .flag("--locked-toolchain", "", + "Fail when vbs-toolchain.toml constraints drift", build_opts.locked_toolchain) .flag("--offline", "", "Disallow network fetches", build_opts.offline) .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) .flag("--native-foreign", "", @@ -6544,6 +6740,23 @@ int main(int argc, char **argv) { .flag("--json", "", "Emit JSON findings", audit_opts.json); add_log_flags(audit_cmd); + auto &profile_cmd = root.subcommand("profile", "Inspect declared and resolved build profiles"); + auto configure_profile_common = [&](Void::Argparse::Parser &p) { + p.option_default("--project", "-C", "Project directory", profile_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", profile_opts.build_arg) + .option("--compiler", "", "Override compiler family (gcc|clang)", + profile_opts.compiler_arg); + add_log_flags(p); + }; + configure_profile_common(profile_cmd.subcommand("list", "List declared profiles")); + auto &profile_show = profile_cmd.subcommand("show", "Show one resolved profile"); + configure_profile_common(profile_show); + profile_show.positional("profile", "Profile name", profile_opts.profile_arg); + auto &profile_diff = + profile_cmd.subcommand("diff", "Show fields that differ between two profiles"); + configure_profile_common(profile_diff); + profile_diff.positional_many("profiles", "Two profile names", profile_opts.diff_args, true); + auto &ide_cmd = root.subcommand("ide", "Generate editor/IDE configs and query workspace metadata"); auto configure_ide_common = [&](Void::Argparse::Parser &p) { @@ -6948,6 +7161,9 @@ int main(int argc, char **argv) { if (cmd == "audit") { return execute_audit_command(audit_opts); } + if (cmd == "profile") { + return execute_profile_command(parsed.matched_command_path.at(1), profile_opts); + } if (cmd == "ide") { return execute_ide_command(parsed.matched_command_path.at(1), ide_opts); } diff --git a/src/Provider/Provider.cpp b/src/Provider/Provider.cpp index 19cdfb6..857f62a 100644 --- a/src/Provider/Provider.cpp +++ b/src/Provider/Provider.cpp @@ -1033,6 +1033,31 @@ collect_native_dep_snapshot_inputs(const Graph::ProjectDescription &desc, return {std::move(explicit_files), std::move(scan_roots)}; } +// Applies `.profile("name", {...})` overrides declared by the consumer to the profile used to +// evaluate and build the dependency itself. +ProfileContext apply_dependency_profile_overrides(const ProfileContext &base, + const DependencyRecord &dependency) { + const auto it = dependency.profile_overrides.find(base.name); + if (it == dependency.profile_overrides.end()) { + return base; + } + ProfileContext profile = base; + const auto &overrides = it->second; + profile.compile_options.insert(profile.compile_options.end(), + overrides.compile_options.begin(), + overrides.compile_options.end()); + profile.link_options.insert(profile.link_options.end(), overrides.link_options.begin(), + overrides.link_options.end()); + profile.defines.insert(profile.defines.end(), overrides.defines.begin(), + overrides.defines.end()); + if (overrides.lto) { + profile.lto = *overrides.lto; + } + profile.sanitizers.insert(profile.sanitizers.end(), overrides.sanitizers.begin(), + overrides.sanitizers.end()); + return profile; +} + Void::Result::Result run_native_provider(const ProviderRequest &request, const std::filesystem::path &build_dir, const std::string &input_hash, std::stop_token stop) { @@ -1058,8 +1083,10 @@ run_native_provider(const ProviderRequest &request, const std::filesystem::path "native subproject builder requires VBS SDK " "include/source paths in ProviderRequest")}; } + const ProfileContext dependency_profile = + apply_dependency_profile_overrides(request.profile, request.dependency); Void::Log::info("Provider", "Evaluating native subproject '{}' (profile='{}')...", - request.dependency.name, request.profile.name); + request.dependency.name, dependency_profile.name); Config::FrontendOptions fopts; fopts.project_root = src_dir; fopts.build_root = build_dir; @@ -1080,7 +1107,7 @@ run_native_provider(const ProviderRequest &request, const std::filesystem::path if (!compiled) { return std::unexpected{compiled.error()}; } - auto eval = Config::evaluate_project(*compiled, request.profile, fopts); + auto eval = Config::evaluate_project(*compiled, dependency_profile, fopts); if (!eval) { return std::unexpected{eval.error()}; } @@ -1105,11 +1132,13 @@ run_native_provider(const ProviderRequest &request, const std::filesystem::path snap = std::move(*cap); } else if (is_void_library) { const auto mods = parse_void_modules_option(request.dependency.options); + const ProfileContext dependency_profile = + apply_dependency_profile_overrides(request.profile, request.dependency); Void::Log::info("Provider", "Evaluating native VoidLibrary recipe for '{}' ({} module(s), " "profile='{}')...", - request.dependency.name, mods.size(), request.profile.name); - Project sub_proj{request.profile}; + request.dependency.name, mods.size(), dependency_profile.name); + Project sub_proj{dependency_profile}; try { (void)Recipes::add_void_library_native(sub_proj, src_dir, mods); } catch (const std::exception &ex) { @@ -1378,6 +1407,22 @@ std::string compute_provider_input_hash(const ProviderRequest &request) { h.update_length_prefixed(k); h.update_length_prefixed(cmake_option_value(v)); } + for (const auto &[profile_name, overrides] : request.dependency.profile_overrides) { + h.update_length_prefixed(profile_name); + for (const auto &option : overrides.compile_options) { + h.update_length_prefixed(option); + } + for (const auto &option : overrides.link_options) { + h.update_length_prefixed(option); + } + for (const auto &define : overrides.defines) { + h.update_length_prefixed(define); + } + h.update_length_prefixed(overrides.lto ? lto_mode_name(*overrides.lto) : "none"); + for (const auto &sanitizer : overrides.sanitizers) { + h.update_length_prefixed(sanitizer_name(sanitizer)); + } + } return h.finalize_hex(); } diff --git a/src/Toolchain/Pin.cpp b/src/Toolchain/Pin.cpp new file mode 100644 index 0000000..dd8332d --- /dev/null +++ b/src/Toolchain/Pin.cpp @@ -0,0 +1,162 @@ +#include + +#include +#include +#include + +#include +#include +#include + +namespace Void::Build::Toolchain { +namespace { + +using Void::Result::Error; +using Void::Result::Result; + +Error make_error(Void::System::SystemErrorCode code, std::string message) { + return Void::System::make_system_error(code, std::move(message)); +} + +std::string read_string(const Package::TomlTable &table, std::string_view key) { + const auto it = table.find(std::string{key}); + if (it == table.end() || !it->second.is_string()) { + return {}; + } + return it->second.as_string(); +} + +std::string normalize_standard(std::string_view value) { + std::string lowered = Void::Str::to_lower(value); + if (lowered.starts_with("c++")) { + lowered = "cxx" + lowered.substr(3); + } + return lowered; +} + +bool version_at_least(const std::vector &actual, const std::vector &minimum) { + const std::size_t count = std::max(actual.size(), minimum.size()); + for (std::size_t i = 0; i < count; ++i) { + const int a = i < actual.size() ? actual[i] : 0; + const int m = i < minimum.size() ? minimum[i] : 0; + if (a != m) { + return a > m; + } + } + return true; +} + +std::string join_version(const std::vector &parts) { + std::string out; + for (const int part : parts) { + if (!out.empty()) { + out += '.'; + } + out += std::to_string(part); + } + return out; +} + +} // namespace + +std::vector parse_version_prefix(std::string_view text) { + std::size_t index = 0; + while (index < text.size() && std::isdigit(static_cast(text[index])) == 0) { + ++index; + } + std::vector parts; + int current = 0; + bool have_digits = false; + for (; index < text.size(); ++index) { + const char c = text[index]; + if (std::isdigit(static_cast(c)) != 0) { + current = current * 10 + (c - '0'); + have_digits = true; + } else if (c == '.' && have_digits) { + parts.push_back(current); + current = 0; + have_digits = false; + } else { + break; + } + } + if (have_digits) { + parts.push_back(current); + } + return parts; +} + +Result, Error> +load_toolchain_pin(const std::filesystem::path &project_root) { + const auto path = project_root / "vbs-toolchain.toml"; + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + return std::optional{}; + } + auto parsed = Package::parse_toml_file(path); + if (!parsed) { + return std::unexpected{parsed.error()}; + } + ToolchainPin pin; + pin.compiler = Void::Str::to_lower(read_string(*parsed, "compiler")); + pin.version = read_string(*parsed, "version"); + pin.cxx_standard = normalize_standard(read_string(*parsed, "cxx_standard")); + pin.c_standard = normalize_standard(read_string(*parsed, "c_standard")); + pin.sysroot = read_string(*parsed, "sysroot"); + if (const auto it = parsed->find("strict"); + it != parsed->end() && it->second.is_bool()) { + pin.strict = it->second.as_bool(); + } + if (!pin.compiler.empty() && pin.compiler != "gcc" && pin.compiler != "clang") { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("vbs-toolchain.toml: unsupported compiler '{}' (expected gcc or clang)", + pin.compiler))}; + } + if (!pin.version.empty() && parse_version_prefix(pin.version).empty()) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("vbs-toolchain.toml: invalid version '{}'", pin.version))}; + } + return std::optional{std::move(pin)}; +} + +ToolchainDrift check_toolchain_pin(const ToolchainPin &pin, const ProfileContext &profile, + const ToolchainCapabilities &toolchain) { + ToolchainDrift drift; + if (!pin.compiler.empty() && compiler_name(profile.compiler) != pin.compiler) { + drift.differences.push_back(std::format("compiler pinned '{}', using '{}'", pin.compiler, + compiler_name(profile.compiler))); + } + if (!pin.version.empty()) { + const auto minimum = parse_version_prefix(pin.version); + const auto actual = parse_version_prefix(toolchain.version_banner); + if (actual.empty()) { + drift.differences.push_back(std::format( + "version pinned >= {}, but the compiler banner has no version", pin.version)); + } else if (!version_at_least(actual, minimum)) { + drift.differences.push_back(std::format("version pinned >= {}, using {}", + pin.version, join_version(actual))); + } + } + if (!pin.cxx_standard.empty() && + normalize_standard(cxx_standard_name(profile.cxx_standard)) != pin.cxx_standard) { + drift.differences.push_back( + std::format("cxx_standard pinned '{}', using '{}'", pin.cxx_standard, + normalize_standard(cxx_standard_name(profile.cxx_standard)))); + } + if (!pin.c_standard.empty() && + normalize_standard(c_standard_name(profile.c_standard)) != pin.c_standard) { + drift.differences.push_back( + std::format("c_standard pinned '{}', using '{}'", pin.c_standard, + normalize_standard(c_standard_name(profile.c_standard)))); + } + if (!pin.sysroot.empty() && profile.sysroot != pin.sysroot) { + drift.differences.push_back(std::format("sysroot pinned '{}', using '{}'", pin.sysroot, + profile.sysroot.empty() ? "" + : profile.sysroot)); + } + return drift; +} + +} // namespace Void::Build::Toolchain diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index d9fb9b7..79894a3 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -64,6 +64,12 @@ check_process(0 "--sandbox" "" build --help) check_process(0 "--features" "" build --help) check_process(0 "--no-default-features" "" build --help) check_process(0 "--show-features" "" explain --help) +check_process(0 "--locked-toolchain" "" build --help) +check_process(0 "Usage: vbs profile " "" profile --help) +check_process(0 "Usage: vbs profile list " "" profile list --help) +check_process(0 "Usage: vbs profile show " "" profile show --help) +check_process(0 "Usage: vbs profile diff " "" profile diff --help) +check_process(2 "" "exactly two profile names" profile diff debug) check_process(2 "" "invalid value 'bogus' for '--sandbox'" build --sandbox bogus) check_process(0 "Usage: vbs new " "" new --help) check_process(2 "" "unsupported --native-cache" build --native-cache bogus) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index d0e9fb7..a8ec210 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -5186,3 +5186,147 @@ void build(Void::Build::Project &p) { Void::Testing::expect(with_feature.has_value() && with_feature->succeeded()); Void::Testing::expect_eq(entry_count(), 1LL); } + +// === G3: per-dependency profile overrides === +VOID_TEST(FullV1Tests, dependency_profile_overrides_apply_to_native_builds) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_dep_profile_"}; + const auto dep = tmp / "dep"; + const auto with_override = tmp / "with"; + const auto without_override = tmp / "without"; + write_file(dep / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { p.static_library("deplib").sources({"src/dep.cpp"}); } +)cpp"); + write_file(dep / "src" / "dep.cpp", "#ifndef VBS_DEP_OVERRIDE\n#error \"VBS_DEP_OVERRIDE is " + "required\"\n#endif\nint depfn() { return 1; }\n"); + write_file(with_override / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.dependency("dep").path("../dep").native_builder({}) + .profile("debug", {.compile_options = {"-DVBS_DEP_OVERRIDE=1"}}); + p.executable("app").sources({"src/main.cpp"}); +} +)cpp"); + write_file(without_override / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.dependency("dep").path("../dep").native_builder({}); + p.executable("app").sources({"src/main.cpp"}); +} +)cpp"); + for (const auto &project : {with_override, without_override}) { + write_file(project / "src" / "main.cpp", "int main() { return 0; }\n"); + } + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + auto overridden = run_vbs({"build", "--project", with_override.string(), "--build-dir", + (tmp / "build-with").string(), "--jobs", "2"}); + Void::Testing::expect(overridden.has_value() && overridden->succeeded()); + if (overridden && !overridden->succeeded()) { + std::cerr << overridden->stderr_data << '\n'; + } + auto plain = run_vbs({"build", "--project", without_override.string(), "--build-dir", + (tmp / "build-without").string(), "--jobs", "2"}); + Void::Testing::expect(plain.has_value() && !plain->succeeded()); +} + +// === G3: vbs-toolchain.toml pinning and drift detection === +VOID_TEST(FullV1Tests, toolchain_pin_detects_and_enforces_drift) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_toolchain_pin_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { p.executable("app").sources({"src/main.cpp"}); } +)cpp"); + write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + write_file(proj / "vbs-toolchain.toml", "compiler = \"clang\"\n"); + auto warned = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-warn").string(), "--jobs", "2"}); + Void::Testing::expect(warned.has_value() && warned->succeeded()); + if (warned) { + Void::Testing::expect((warned->stdout_data + warned->stderr_data) + .find("pin drift") != std::string::npos); + } + auto enforced = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-enforced").string(), "--jobs", "2", + "--locked-toolchain"}); + Void::Testing::expect(enforced.has_value() && enforced->exit_code == 1); + if (enforced) { + Void::Testing::expect(enforced->stderr_data.find("toolchain pin") != std::string::npos); + } + write_file(proj / "vbs-toolchain.toml", "compiler = \"gcc\"\nversion = \"16\"\n"); + auto matching = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-match").string(), "--jobs", "2", + "--locked-toolchain"}); + Void::Testing::expect(matching.has_value() && matching->succeeded()); + write_file(proj / "vbs-toolchain.toml", "compiler = [\n"); + auto malformed = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-bad").string()}); + Void::Testing::expect(malformed.has_value() && !malformed->succeeded()); +} + +// === G3: vbs profile list / show / diff === +VOID_TEST(FullV1Tests, profile_commands_list_show_and_diff) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_profiles_cmd_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { p.executable("app").sources({"src/main.cpp"}); } +)cpp"); + write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n"); + write_file(proj / "build.profiles.cpp", R"cpp(#include +void profiles(Void::Build::Profiles &p) { + p = Void::Build::default_profiles(); + p.inherit("fast", "release", {"-DFAST_MODE=1"}); +} +)cpp"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + auto list = run_vbs({"profile", "list", "--project", proj.string()}); + Void::Testing::expect(list.has_value() && list->succeeded()); + if (list) { + Void::Testing::expect(list->stdout_data.find("fast parent=release") != std::string::npos); + Void::Testing::expect(list->stdout_data.find("debug") != std::string::npos); + } + auto show = run_vbs({"profile", "show", "release", "--project", proj.string()}); + Void::Testing::expect(show.has_value() && show->succeeded()); + if (show) { + Void::Testing::expect(show->stdout_data.find("name: release") != std::string::npos); + Void::Testing::expect(show->stdout_data.find("compiler: gcc") != std::string::npos); + } + auto diff = run_vbs({"profile", "diff", "debug", "fast", "--project", proj.string()}); + Void::Testing::expect(diff.has_value() && diff->succeeded()); + if (diff) { + Void::Testing::expect(diff->stdout_data.find("compile_options:") != std::string::npos); + Void::Testing::expect(diff->stdout_data.find("FAST_MODE") != std::string::npos); + } + auto missing = run_vbs({"profile", "show", "nope", "--project", proj.string()}); + Void::Testing::expect(missing.has_value() && missing->exit_code == 2); +}