diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 0488b60..1176297 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 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). - **Wave 148 (Hermetic sandboxing, F1)**: `Sandbox::sandbox_supported()` probes unprivileged user namespaces; `vbs build|test|run --sandbox=off|warn|strict` (or `VBS_SANDBOX`) wraps every action in the hidden `vbs __sandbox-exec` mode, which unshares user/mount/network namespaces, maps the caller to root, binds the project read-only, the build root (snapshots included) read-write, and `/usr`, `/lib`, `/bin`, `/etc` and the Nix store read-only before `pivot_root` and exec. `/proc`, `/sys` and `/dev` are bound read-write (their mounts cannot be remounted read-only from a user namespace), `/tmp` is an empty directory, and system read-only remounts that the kernel refuses degrade to writable binds (the project itself is required to be read-only). `vbs doctor` reports availability, CI runs a strict smoke build when the runner allows user namespaces, and `FullV1Tests.sandbox_strict_allows_project_builds_and_hides_outside_files` proves a strict build succeeds while an action that reads an outside file fails. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index c1adff5..5616634 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -149,4 +149,5 @@ Base HEAD: `fe0d1a6` | Wave 147 (Lifecycle CLI + native caching + BEP) | `vbs run` (Void::Process inherited stdio, exit-code passthrough, Wine), `vbs metadata` (StrictJson schema v1), `vbs why`, `vbs tree`, `vbs fmt`/`vbs lint`, `vbs install-binary`, `vbs add`/`vbs remove` (Semver-validated manifest editing + lock refresh), `vbs new`, `--frozen`, `--bep` event stream, `--native-cache off/auto/ccache/sccache` with doctor reporting | COMPLETE & VERIFIED for the implemented commands (GCC 16.2; lifecycle, tree, fmt, BEP and native-cache tests pass; CLI contracts pass) | `src/Main.cpp`, `src/Toolchain/Driver.{hpp,cpp}`, `src/Package/Manifest.{hpp,cpp}`, `include/Void/Build/Package/Manifest.hpp`, `tests/{FullV1Tests,CliContracts}`, docs | | 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 | | 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 ca86749..51a00a0 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -157,6 +157,17 @@ the registry offline; `install-binary` installs and runs the registry artifact. ### G2 — Feature flags that actually work *(M–L)* +**Status: implemented (Wave 150).** `Project::feature(name, default_on)` (or +`FeatureDescription`), `Target::require_feature(name)` (the plan's `.requires` spelling collides +with the C++20 keyword) and `Dependency::when(feature)`; `--features a,b` / +`--no-default-features` on build/test/run/explain/deps; additive unification (defaults + target +requirements + requests); `VBS_FEATURE_` defines on every target so action keys and the +cache follow the feature set; optional dependencies filtered before resolution; `vbs explain +--show-features` and `vbs metadata` report the unified set and its reasons. Verified by +`FullV1Tests.features_unify_defines_and_invalidate_action_keys` and +`optional_dependencies_follow_feature_selection`. The ABI rule (features may add definition +macros, never layout) is documented. + **Beats:** Cargo's best idea, applied to C++ — no C++ build system has additive, unified features. Current state: `Dependency::feature(name)` is recorded and serialized into the lockfile but **is diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp index 23096fb..61ed65a 100644 --- a/include/Void/Build.hpp +++ b/include/Void/Build.hpp @@ -80,6 +80,12 @@ struct ProfileContext { bool nondeterministic{false}; }; +struct FeatureDescription { + std::string name; + bool default_on{false}; + std::string description; +}; + struct ProfileDescription { std::string name; std::vector compile_options; @@ -196,6 +202,7 @@ struct TargetRecord { std::vector defines; std::vector link_options; std::vector prerequisites; + std::vector required_features; // Project features this target requires. CStandard c_standard{CStandard::Default}; CxxStandard cxx_standard{CxxStandard::Default}; std::string precompiled_header; @@ -232,6 +239,7 @@ struct DependencyRecord { std::string registry_authority; std::string sha256; std::vector features; + std::string required_feature; // Optional dependency: only used when this feature is on. bool build_dependency{false}; }; @@ -306,6 +314,8 @@ class Target { Target &fixture_setup(std::string name); Target &fixture_required(std::string name); Target &fixture_cleanup(std::string name); + // Contributes a project feature to the additive feature set (Cargo-style unification). + Target &require_feature(std::string feature); Target &nondeterministic(bool enabled = true); Target &enabled(bool flag); Target &install(std::string destination = {}, std::string component = "default"); @@ -333,6 +343,8 @@ class Dependency { Dependency &package(std::string id, std::string range); Dependency ®istry(std::string authority_url); Dependency &feature(std::string name); + // Optional dependency: resolved only when the project feature is enabled. + Dependency &when(std::string feature); Dependency &build_dependency(bool is_build_tool = true); [[nodiscard]] ImportedTarget target(std::string exported_name) const; [[nodiscard]] const DependencyRecord &record() const; @@ -367,6 +379,10 @@ class Project { // A target that compiles declared shader sources to SPIR-V (`.shader(...)`). [[nodiscard]] Target shader_bundle(std::string name); [[nodiscard]] Target test(std::string name); + // Declares a project feature (additive; defaults are on unless --no-default-features). + Project &feature(std::string name, bool default_on = false); + Project &feature(FeatureDescription description); + [[nodiscard]] const std::vector &features() const noexcept; [[nodiscard]] Dependency dependency(std::string name); // Links to another member of the enclosing workspace. The member path is supplied by the // workspace driver through VBS_WORKSPACE_MEMBER_ and built with the native provider. diff --git a/include/Void/Build/Graph/Graph.hpp b/include/Void/Build/Graph/Graph.hpp index 88ad64f..79c93e6 100644 --- a/include/Void/Build/Graph/Graph.hpp +++ b/include/Void/Build/Graph/Graph.hpp @@ -23,6 +23,7 @@ struct ProjectDescription { ProfileContext profile; std::vector targets; std::vector dependencies; + std::vector features; std::vector dependency_files; std::vector install_rules; diff --git a/sdk/Build.cpp b/sdk/Build.cpp index 49368c5..11bbcd2 100644 --- a/sdk/Build.cpp +++ b/sdk/Build.cpp @@ -13,6 +13,7 @@ struct ProjectState { ProfileContext context; std::vector targets; std::vector dependencies; + std::vector features; std::vector dependency_files; std::vector install_rules; }; @@ -891,6 +892,15 @@ Target &Target::fixture_cleanup(std::string name) { return *this; } +Target &Target::require_feature(std::string feature) { + require_text(feature, "feature name"); + auto &features = owner(owner_)->targets.at(index_).required_features; + if (!std::ranges::contains(features, feature)) { + features.push_back(std::move(feature)); + } + return *this; +} + Target &Target::enabled(bool flag) { owner(owner_)->targets.at(index_).enabled = flag; return *this; @@ -1068,6 +1078,12 @@ Dependency &Dependency::feature(std::string name) { return *this; } +Dependency &Dependency::when(std::string feature) { + require_text(feature, "feature name"); + owner(owner_)->dependencies.at(index_).required_feature = std::move(feature); + return *this; +} + Dependency &Dependency::build_dependency(bool is_build_tool) { owner(owner_)->dependencies.at(index_).build_dependency = is_build_tool; return *this; @@ -1125,6 +1141,35 @@ Target Project::shader_bundle(std::string name) { } Target Project::test(std::string name) { return add_target(std::move(name), TargetKind::Test); } +Project &Project::feature(std::string name, bool default_on) { + FeatureDescription description; + description.name = std::move(name); + description.default_on = default_on; + return feature(std::move(description)); +} + +Project &Project::feature(FeatureDescription description) { + require_text(description.name, "feature name"); + for (const char c : description.name) { + if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && + c != '_' && c != '-') { + throw std::invalid_argument{"feature name '" + description.name + + "' may only contain letters, digits, '_' and '-'"}; + } + } + if (std::ranges::any_of(state_->features, [&](const FeatureDescription &existing) { + return existing.name == description.name; + })) { + throw std::invalid_argument{"duplicate feature '" + description.name + "'"}; + } + state_->features.push_back(std::move(description)); + return *this; +} + +const std::vector &Project::features() const noexcept { + return state_->features; +} + Dependency Project::dependency(std::string name) { require_text(name, "dependency name"); if (std::ranges::any_of(state_->dependencies, @@ -1225,7 +1270,12 @@ std::string Project::to_json() const { ",\"compiler_path\":" + json_quote(profile.compiler_path) + ",\"reproducibility_epoch\":" + std::to_string(profile.reproducibility_epoch) + ",\"nondeterministic\":" + std::string{profile.nondeterministic ? "true" : "false"} + - "},\"targets\":"; + "},\"features\":" + + json_array(features(), [](const FeatureDescription &feature) { + return "{\"name\":" + json_quote(feature.name) + + ",\"default_on\":" + std::string{feature.default_on ? "true" : "false"} + + ",\"description\":" + json_quote(feature.description) + '}'; + }) + ",\"targets\":"; output += json_array(targets(), [](const TargetRecord &target) { std::string out = "{\"name\":" + json_quote(target.name) + @@ -1257,6 +1307,7 @@ std::string Project::to_json() const { json_quote(visibility_name(link.visibility)) + '}'; }) + ",\"prerequisites\":" + json_array(target.prerequisites, json_quote) + + ",\"required_features\":" + json_array(target.required_features, json_quote) + ",\"c_standard\":" + json_quote(c_standard_name(target.c_standard)) + ",\"cxx_standard\":" + json_quote(cxx_standard_name(target.cxx_standard)) + ",\"precompiled_header\":" + json_quote(target.precompiled_header) + @@ -1365,6 +1416,7 @@ std::string Project::to_json() const { ",\"options\":" + options_json(dependency.options) + ",\"registry_authority\":" + json_quote(dependency.registry_authority) + ",\"features\":" + json_array(dependency.features, json_quote) + + ",\"required_feature\":" + json_quote(dependency.required_feature) + ",\"build_dependency\":" + std::string{dependency.build_dependency ? "true" : "false"} + '}'; return result; diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index 40e0ce1..febb006 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -242,6 +242,26 @@ ProjectDescription::from_json(std::string_view json_text) { desc.profile.reproducibility_epoch = get_i64(*prof, "reproducibility_epoch", 0); desc.profile.nondeterministic = get_bool(*prof, "nondeterministic", false); + if (const auto *features_v = find_key(*root, "features")) { + if (const auto *features_arr = std::get_if(&features_v->value)) { + for (const auto &feature_value : *features_arr) { + const auto *feature = + std::get_if(&feature_value.value); + if (feature == nullptr) { + continue; + } + FeatureDescription description; + description.name = get_str(*feature, "name"); + if (description.name.empty()) { + continue; + } + description.default_on = get_bool(*feature, "default_on", false); + description.description = get_str(*feature, "description"); + desc.features.push_back(std::move(description)); + } + } + } + if (const auto *targets_v = find_key(*root, "targets")) { const auto *arr = std::get_if(&targets_v->value); if (!arr) { @@ -303,6 +323,7 @@ ProjectDescription::from_json(std::string_view json_text) { } } t.prerequisites = get_str_array(*to, "prerequisites"); + t.required_features = get_str_array(*to, "required_features"); t.c_standard = parse_c_standard(get_str(*to, "c_standard", "default")); t.cxx_standard = parse_cxx_standard(get_str(*to, "cxx_standard", "default")); t.precompiled_header = get_str(*to, "precompiled_header"); @@ -396,6 +417,7 @@ ProjectDescription::from_json(std::string_view json_text) { d.builder = get_str(*do_obj, "builder"); 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"); 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 4973686..245cc23 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -460,6 +460,9 @@ struct BuildCmdOptions { bool frozen{false}; std::string native_cache_arg; std::string sandbox_arg{"off"}; + std::vector features; + bool no_default_features{false}; + bool show_features{false}; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -467,6 +470,86 @@ struct BuildCmdOptions { bool native_foreign{false}; }; +std::string feature_macro_name(std::string_view feature) { + std::string macro{"VBS_FEATURE_"}; + for (const char c : feature) { + macro.push_back(std::isalnum(static_cast(c)) != 0 + ? static_cast(std::toupper(static_cast(c))) + : '_'); + } + return macro; +} + +// Additive feature unification: defaults (unless disabled) + features required by targets + +// features requested on the command line. +bool compute_enabled_features(const Graph::ProjectDescription &description, + const std::vector &requested, bool no_defaults, + std::vector &enabled, std::string &error) { + std::map> declared; + for (const auto &feature : description.features) { + declared[feature.name] = &feature; + } + std::set set; + if (!no_defaults) { + for (const auto &feature : description.features) { + if (feature.default_on) { + set.insert(feature.name); + } + } + } + for (const auto &target : description.targets) { + for (const auto &required : target.required_features) { + if (!declared.contains(required)) { + error = std::format("target '{}' requires undeclared feature '{}'", target.name, + required); + return false; + } + set.insert(required); + } + } + for (const auto &raw : requested) { + for (const auto part : Void::Str::split(raw, ',')) { + const std::string name = std::string{Void::Str::trim(part)}; + if (name.empty()) { + continue; + } + if (!declared.contains(name)) { + std::string known; + for (const auto &[key, value] : declared) { + (void)value; + if (!known.empty()) { + known += ", "; + } + known += key; + } + error = std::format("unknown feature '{}' (declared: {})", name, + known.empty() ? "none" : known); + return false; + } + set.insert(name); + } + } + enabled.assign(set.begin(), set.end()); + return true; +} + +void apply_feature_defines(Graph::ProjectDescription &description, + const std::vector &enabled) { + for (auto &target : description.targets) { + for (const auto &feature : enabled) { + target.defines.push_back({feature_macro_name(feature), Visibility::Private}); + } + } +} + +void filter_optional_dependencies(std::vector &dependencies, + const std::vector &enabled) { + std::erase_if(dependencies, [&](const Package::NormalizedDependency &dependency) { + const std::string &required = dependency.record.required_feature; + return !required.empty() && !std::ranges::contains(enabled, required); + }); +} + int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; if (opts.frozen) { @@ -871,6 +954,49 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { eval_sw.elapsed_ms()); trace_phase("eval", "phase", eval_sw.elapsed_ms(), "evaluate the project description"); + std::vector enabled_features; + std::string feature_error; + if (!compute_enabled_features(*desc, opts.features, opts.no_default_features, + enabled_features, feature_error)) { + std::cerr << cmd_name << ": " << feature_error << '\n'; + return 2; + } + if (opts.show_features) { + std::cout << "features for " << prof_name << ":\n"; + for (const auto &feature : desc->features) { + const bool on = std::ranges::contains(enabled_features, feature.name); + std::string reasons; + if (feature.default_on && !opts.no_default_features) { + reasons += "default"; + } + for (const auto &raw : opts.features) { + for (const auto part : Void::Str::split(raw, ',')) { + if (std::string{Void::Str::trim(part)} == feature.name) { + if (!reasons.empty()) { + reasons += ", "; + } + reasons += "requested"; + } + } + } + for (const auto &target : desc->targets) { + if (std::ranges::contains(target.required_features, feature.name)) { + if (!reasons.empty()) { + reasons += ", "; + } + reasons += "required by " + target.name; + } + } + std::cout << " " << feature.name << ": " << (on ? "enabled" : "disabled"); + if (!reasons.empty()) { + std::cout << " (" << reasons << ')'; + } + std::cout << '\n'; + } + continue; + } + apply_feature_defines(*desc, enabled_features); + // Load & merge any TOML dependency manifests declared by build.cpp. std::vector toml_deps; for (const auto &dep_file : desc->dependency_files) { @@ -891,6 +1017,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cerr << "vbs: " << merged_deps.error().message() << '\n'; return 1; } + filter_optional_dependencies(*merged_deps, enabled_features); // Validate/update lockfile context and materialize dependencies (including live registry). std::map> imported_targets; @@ -3412,6 +3539,13 @@ int execute_install_command(const InstallCmdOptions &opts) { // Import declared dependencies like `vbs build`, so projects with external // dependencies (e.g. VoidLibrary) can be installed too. + std::vector enabled_features; + std::string feature_error; + if (!compute_enabled_features(*desc, {}, false, enabled_features, feature_error)) { + std::cerr << "vbs install: " << feature_error << '\n'; + return 2; + } + apply_feature_defines(*desc, enabled_features); std::vector toml_deps; for (const auto &dep_file : desc->dependency_files) { const auto dep_path = std::filesystem::path{dep_file}.is_absolute() @@ -3429,6 +3563,7 @@ int execute_install_command(const InstallCmdOptions &opts) { std::cerr << "vbs install: " << merged_deps.error().message() << '\n'; return 1; } + filter_optional_dependencies(*merged_deps, enabled_features); std::map> imported_targets; if (!merged_deps->empty()) { auto pinned_lock = Package::load_pinned_lock(project_root / "vbs.lock"); @@ -3943,6 +4078,8 @@ struct DepsCmdOptions { std::optional build_arg; std::string profile_name{"debug"}; bool offline{false}; + std::vector features; + bool no_default_features{false}; }; int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { @@ -3970,6 +4107,14 @@ int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { std::cerr << "vbs deps: " << desc.error().message() << '\n'; return 1; } + std::vector enabled_features; + std::string feature_error; + if (!compute_enabled_features(*desc, opts.features, opts.no_default_features, + enabled_features, feature_error)) { + std::cerr << "vbs deps: " << feature_error << '\n'; + return 2; + } + apply_feature_defines(*desc, enabled_features); std::vector toml_deps; for (const auto &df : desc->dependency_files) { auto loaded = Package::load_dependencies_toml(project_root / df); @@ -3984,6 +4129,7 @@ int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { std::cerr << "vbs deps: " << merged.error().message() << '\n'; return 1; } + filter_optional_dependencies(*merged, enabled_features); const auto lock_path = project_root / "vbs.lock"; auto existing = Package::load_pinned_lock(lock_path); @@ -4104,6 +4250,15 @@ int execute_metadata_command(const MetadataCmdOptions &opts) { return v; }; + std::vector metadata_features; + { + std::string feature_error; + if (!compute_enabled_features(*desc, {}, false, metadata_features, feature_error)) { + std::cerr << "vbs metadata: " << feature_error << '\n'; + return 2; + } + } + JsonObject root; root["schema_version"] = number(1); root["project_root"] = text(project_root.string()); @@ -4113,6 +4268,18 @@ int execute_metadata_command(const MetadataCmdOptions &opts) { root["os"] = text(desc->profile.os); root["architecture"] = text(desc->profile.architecture); + JsonArray features; + for (const auto &feature : desc->features) { + JsonObject entry; + entry["name"] = text(feature.name); + entry["default_on"] = boolean(feature.default_on); + entry["description"] = text(feature.description); + entry["enabled"] = + boolean(std::ranges::contains(metadata_features, feature.name)); + features.push_back(object(std::move(entry))); + } + root["features"] = array(std::move(features)); + JsonArray targets; for (const auto &target : desc->targets) { JsonObject entry; @@ -4145,6 +4312,11 @@ int execute_metadata_command(const MetadataCmdOptions &opts) { labels.push_back(text(label)); } entry["labels"] = array(std::move(labels)); + JsonArray required_features; + for (const auto &feature : target.required_features) { + required_features.push_back(text(feature)); + } + entry["required_features"] = array(std::move(required_features)); if (target.install_rule) { JsonObject install; install["destination"] = text(target.install_rule->destination); @@ -5497,6 +5669,17 @@ int execute_ide_command(std::string_view sub, const IdeCmdOptions &opts) { std::cerr << "vbs ide: " << desc.error().message() << '\n'; return 1; } + std::vector ide_enabled_features; + { + std::vector enabled_features; + std::string feature_error; + if (!compute_enabled_features(*desc, {}, false, enabled_features, feature_error)) { + std::cerr << "vbs ide: " << feature_error << '\n'; + return 2; + } + apply_feature_defines(*desc, enabled_features); + ide_enabled_features = std::move(enabled_features); + } // MetadataOnly provider loading: inspect cached provider exports if already built; never // run foreign configure/build/fetch. On unbuilt checkouts, synthesize empty placeholders so @@ -5512,8 +5695,10 @@ int execute_ide_command(std::string_view sub, const IdeCmdOptions &opts) { } } auto merged_deps = Package::merge_dependencies(desc->dependencies, toml_deps); - if (merged_deps && !merged_deps->empty()) { - std::optional pinned_lock; + if (merged_deps) { + filter_optional_dependencies(*merged_deps, ide_enabled_features); + } + if (merged_deps && !merged_deps->empty()) { std::optional pinned_lock; if (auto pl = Package::load_pinned_lock(project_root / "vbs.lock"); pl) { pinned_lock = *pl; } @@ -5800,6 +5985,11 @@ int main(int argc, char **argv) { "Hermetic sandbox: off (default), warn or strict", build_opts.sandbox_arg, sandbox_default, {"off", "warn", "strict"}) + .option_many("--features", "", + "Enable project features (comma-separated or repeatable)", + build_opts.features) + .flag("--no-default-features", "", "Disable default project features", + build_opts.no_default_features) .flag("--offline", "", "Disallow network fetches", build_opts.offline) .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) .flag("--native-foreign", "", @@ -5831,6 +6021,9 @@ int main(int argc, char **argv) { configure_build_or_test(explain_cmd); explain_cmd.option_default("--format", "", "Output format: text (default) or json", build_opts.explain_format, "text"); + explain_cmd.flag("--show-features", "", + "List declared project features and their enabled state", + build_opts.show_features); auto &describe_cmd = root.subcommand("describe", "Evaluate build.cpp and emit versioned graph summary JSON"); @@ -5880,6 +6073,10 @@ int main(int argc, char **argv) { p.option_default("--project", "-C", "Project directory", deps_opts.project_arg, cwd) .option("--build-dir", "-B", "Build output directory", deps_opts.build_arg) .option_default("--profile", "-p", "Profile name", deps_opts.profile_name, "debug") + .option_many("--features", "", "Enable project features (comma-separated or repeatable)", + deps_opts.features) + .flag("--no-default-features", "", "Disable default project features", + deps_opts.no_default_features) .flag("--offline", "", "Disallow network fetches", deps_opts.offline); add_log_flags(p); }; diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index b1b0e6d..d9fb9b7 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -61,6 +61,9 @@ check_process(0 "--frozen" "" build --help) check_process(0 "--native-cache" "" build --help) check_process(0 "--bep" "" build --help) 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(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 af8a6db..d0e9fb7 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -4982,3 +4982,207 @@ VOID_TEST(FullV1Tests, audit_matches_osv_advisories_against_lock) { advisories.string()}); Void::Testing::expect(clean.has_value() && clean->succeeded()); } + +// === Feature flags: additive unification, defines and feature-aware action keys (G2) === +VOID_TEST(FullV1Tests, features_unify_defines_and_invalidate_action_keys) { + 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_features_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.feature("ssl", true); + p.feature("simd", false); + p.executable("app") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"src/main.cpp"}) + .require_feature("simd"); +} +)cpp"); + write_file(proj / "src" / "main.cpp", R"cpp(#include +int main() { +#ifdef VBS_FEATURE_SSL + std::puts("ssl"); +#endif +#ifdef VBS_FEATURE_SIMD + std::puts("simd"); +#endif + return 0; +} +)cpp"); + 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 default_run = run_vbs({"run", "--project", proj.string(), "--build-dir", + (tmp / "build-default").string(), "--target", "app"}); + Void::Testing::expect(default_run.has_value() && default_run->succeeded()); + if (default_run) { + Void::Testing::expect(default_run->stdout_data.find("ssl") != std::string::npos); + Void::Testing::expect(default_run->stdout_data.find("simd") != std::string::npos); + } + auto no_default = run_vbs({"run", "--project", proj.string(), "--build-dir", + (tmp / "build-nodefault").string(), "--target", "app", + "--no-default-features"}); + Void::Testing::expect(no_default.has_value() && no_default->succeeded()); + if (no_default) { + Void::Testing::expect(no_default->stdout_data.find("ssl") == std::string::npos); + Void::Testing::expect(no_default->stdout_data.find("simd") != std::string::npos); + } + auto explicit_ssl = run_vbs({"run", "--project", proj.string(), "--build-dir", + (tmp / "build-ssl").string(), "--target", "app", + "--no-default-features", "--features", "ssl"}); + Void::Testing::expect(explicit_ssl.has_value() && explicit_ssl->succeeded()); + if (explicit_ssl) { + Void::Testing::expect(explicit_ssl->stdout_data.find("ssl") != std::string::npos); + Void::Testing::expect(explicit_ssl->stdout_data.find("simd") != std::string::npos); + } + auto unknown = run_vbs({"build", "--project", proj.string(), "--build-dir", + (tmp / "build-unknown").string(), "--features", "nope"}); + Void::Testing::expect(unknown.has_value() && unknown->exit_code == 2); + if (unknown) { + Void::Testing::expect(unknown->stderr_data.find("unknown feature 'nope'") != + std::string::npos); + } + + // Feature selection changes the action keys: a cached default build is stale for + // --no-default-features. + auto explained_default = run_vbs({"explain", "--project", proj.string(), "--build-dir", + (tmp / "build-default").string(), "--format", "json"}); + Void::Testing::expect(explained_default.has_value() && explained_default->succeeded()); + auto explained_other = run_vbs({"explain", "--project", proj.string(), "--build-dir", + (tmp / "build-default").string(), "--no-default-features", + "--format", "json"}); + Void::Testing::expect(explained_other.has_value() && explained_other->succeeded()); + const auto would_run = [](const Platform::ProcessResult &result) -> long long { + auto parsed = Void::Json::Strict::parse(result.stdout_data); + if (!parsed) { + return -1; + } + const auto *root = std::get_if(&parsed->value); + if (root == nullptr) { + return -1; + } + const auto *value = std::get_if(&root->at("would_run").value); + return value ? *value : -1; + }; + Void::Testing::expect_eq(would_run(*explained_default), 0LL); + Void::Testing::expect(would_run(*explained_other) >= 1); + + // `explain --show-features` reports the unification reasons. + auto shown = run_vbs({"explain", "--project", proj.string(), "--build-dir", + (tmp / "build-default").string(), "--show-features"}); + Void::Testing::expect(shown.has_value() && shown->succeeded()); + if (shown) { + Void::Testing::expect(shown->stdout_data.find("ssl: enabled (default)") != + std::string::npos); + Void::Testing::expect(shown->stdout_data.find("simd: enabled (required by app)") != + std::string::npos); + } + + // `vbs metadata` exposes the declared features and their enabled state. + auto metadata = run_vbs({"metadata", "--project", proj.string(), "--build-dir", + (tmp / "build-default").string()}); + Void::Testing::expect(metadata.has_value() && metadata->succeeded()); + if (metadata) { + auto parsed = Void::Json::Strict::parse(metadata->stdout_data); + Void::Testing::require(parsed.has_value()); + const auto *root = std::get_if(&parsed->value); + Void::Testing::require(root != nullptr); + const auto *features = + std::get_if(&root->at("features").value); + Void::Testing::require(features != nullptr); + Void::Testing::expect_eq(features->size(), std::size_t{2}); + bool ssl_enabled = false; + bool simd_enabled = false; + for (const auto &feature : *features) { + const auto *object = std::get_if(&feature.value); + if (object == nullptr) { + continue; + } + const auto *name = std::get_if(&object->at("name").value); + const auto *enabled = std::get_if(&object->at("enabled").value); + if (name != nullptr && enabled != nullptr && *enabled) { + if (*name == "ssl") { + ssl_enabled = true; + } + if (*name == "simd") { + simd_enabled = true; + } + } + } + Void::Testing::expect(ssl_enabled); + Void::Testing::expect(simd_enabled); + } +} + +// === Feature flags: optional dependencies are resolved only when enabled === +VOID_TEST(FullV1Tests, optional_dependencies_follow_feature_selection) { + 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_optdep_"}; + const auto dep = tmp / "dep"; + const auto app = tmp / "app"; + 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", "int depfn() { return 1; }\n"); + write_file(app / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.feature("extra", false); + p.dependency("dep").path("../dep").when("extra"); + p.executable("app").sources({"src/main.cpp"}); +} +)cpp"); + write_file(app / "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); + }; + const auto entry_count = [&]() -> long long { + auto text = Void::FileSystem::read_file(app / "vbs.lock"); + if (!text) { + return -1; + } + auto parsed = Void::Json::Strict::parse(*text); + if (!parsed) { + return -1; + } + const auto *root = std::get_if(&parsed->value); + if (root == nullptr) { + return -1; + } + const auto *contexts = + std::get_if(&root->at("contexts").value); + if (contexts == nullptr || contexts->empty()) { + return -1; + } + const auto *context = + std::get_if(&contexts->begin()->second.value); + if (context == nullptr) { + return -1; + } + const auto *entries = + std::get_if(&context->at("entries").value); + return entries ? static_cast(entries->size()) : -1; + }; + auto resolved = run_vbs({"deps", "resolve", "--project", app.string()}); + Void::Testing::expect(resolved.has_value() && resolved->succeeded()); + Void::Testing::expect_eq(entry_count(), 0LL); + auto with_feature = run_vbs({"deps", "resolve", "--project", app.string(), "--features", + "extra"}); + Void::Testing::expect(with_feature.has_value() && with_feature->succeeded()); + Void::Testing::expect_eq(entry_count(), 1LL); +}