diff --git a/README.md b/README.md index 67bbfb6..701c954 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and - **Declaration SDK (`Void::Build`, ``)**: `VoidBuild_Sdk` / `Void::BuildSdk` with version-1 deterministic UTF-8 JSON schema, profile inheritance and cycle detection, all seven `TargetKind`s, scoped options/defines/links, modern C++ flags, install rules, and symbolic TOML manifest references. - **Native Core Engine (`VoidBuild_Core` / `Void::BuildCore`)**: out-of-process host descriptor compilation, graph lowering and transitive visibility resolution, GCC 16 & Clang 23 toolchain discovery/capability probing, content-verified immutable snapshots (`FICLONE`/isolated copies, lookup guards), transactional CAS store (`StateStore`), bounded-parallel DAG execution (`ProcessSupervisor` with `-pgid` `SIGTERM -> SIGKILL` cleanup), and live `Void::Log` progress logging (`--verbose`/`-v`, `--quiet`/`-q`). - **Self-Building & Self-Testing `build.cpp`**: Root [build.cpp](build.cpp) declares the full `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`, and `vbs_self_smoke`) so both `vbs build` and `vbs test` compile, link, and test `VoidBuildSystem` itself end-to-end. -- **Plan 20 Slice 1 — Bounded Native CMake Graph Translation**: [Translator.hpp](include/Void/Build/Provider/Translator.hpp) / [Translator.cpp](src/Provider/Translator.cpp) audits configured CMake File API `codemodel-v2` graphs, executes supported single-config C++ targets natively through VBS's toolchain driver, CAS cache, and depfile tracker (zero `cmake --build`), and explicitly diagnoses or falls back on unsupported constructs (`UTILITY`, generated sources, non-C++ languages, foreign `CXX_MODULES`, precompiled headers, untracked link fragments). +- **Plan 20 Slices 1 & 2A — Bounded Native CMake & Meson Graph Translation**: [Translator.hpp](include/Void/Build/Provider/Translator.hpp) / [Translator.cpp](src/Provider/Translator.cpp) audits configured CMake File API `codemodel-v2` and Meson `meson-info/intro-targets.json` + `build.ninja` graphs, executes supported single-config C++ targets natively through VBS's toolchain driver, CAS cache, and depfile tracker (zero `cmake --build` / `meson compile`), exposes unified `resolve_foreign_with_translation` and opt-in `vbs build|test --native-foreign`, and explicitly diagnoses or falls back on unsupported constructs (`UTILITY`/`custom_target`, generated sources, non-C++ languages, foreign `CXX_MODULES`, precompiled headers, untracked link fragments). - **Modern C++, Editor Metadata & Watchers**: Full graph-integrated P1689r5 named modules & module partitions (GCC `-fmodule-mapper` and Clang two-step `--precompile` `.pcm` -> `.o` + transitive `-fmodule-file=`), explicit `SourceKind::HeaderUnit` compilation, unity batches (excluding modules and per-file overrides), incompatible sanitizer rejection, per-profile `compile_commands.json` with monotonic selection tickets and user-file preservation, and Linux `inotify` build/metadata watching via `Void::FileSystem::DirectoryWatcher` (`MetadataOnly` never triggers builds or foreign configures). - **Native Package Manager, Foreign Providers, Bridge & Install**: `Void::Data::Toml` 1.0 parser/merger, PubGrub-style SemVer solver (`Void::Semver::parse_range`), context-aware CAS `vbs.lock`, live registry HTTP/1.1 client (`vbs publish`, `vbs deps resolve|update`, `vbs build --locked` against `vbs-registry`), deterministic PAX/USTAR `.tar` packaging & staged safe extraction (`Void::Archive`), CMake File API & Meson introspection providers (plus explicit-error Conan2 adapter), `cmake/bridge/VbsDeps.cmake`, and staged relocatable install/export/uninstall. - **Registry Service, Web Admin UI & Native Self-Hosting**: `vbs-registry` HTTP/1.1 service (`VoidBuild_Registry` / `Void::BuildRegistry`) with RBAC, salted password hashes, CSRF/HttpOnly session auth, immutable releases, backup/restore, XSS-safe DOM-only web UI (`registry/web/`), native `VoidLibrary` & full `VbsSelfHostRecipe` recipes (`recipes/VoidLibrary/`, `recipes/SelfHost/`) compiling the full Stage 1 `vbs` binary without CMake to build & test Stage 2 projects, and non-CMake `Void::Testing` registration generator (`vbs gen-tests`). - **Maximal VoidLibrary Reuse (`3e254055...`)**: Built directly on VoidLibrary `Configuration` (`Void::Argparse::Parser` with nested subcommands, `option_many`, and 100% auto-generated `--help` across `vbs`, `vbs-registry`, `vbs_describe`, and `vbs_benchmarks`; `Void::Configuration::get_env`/`get_env_or`), `Crypto` (`Void::Crypto::Hasher` zero-dep SHA-256), `Archive` (`Void::Archive::create` & `extract_staged`), `Data` (`Void::Data::Toml`, `Void::Json::Strict`), `System` (`Void::Process::spawn`/`communicate_blocking`/`enable_subreaper`, `Void::FileSystem::DirectoryWatcher`/`FileLock`/`reflink_copy_file`/`set_canonical_mtime`/`atomic_symlink_swap`, `Void::Process::SignalWatcher`), `Algorithms` (`Void::Algorithms::topological_order`), `Async` (`Void::Concurrency::ThreadPool`), `Unicode` (`Void::Unicode::validate_utf8`), `Text` (`Void::Str`, `Void::Encoding::Hex`, `Void::Encoding::Url`, `Void::Semver::parse_range`), `Log` (`Void::Log`), `Core` (`Void::Scope::on_exit`), `Time` (`Void::Time::Stopwatch`), and `Testing`. -- **Remaining future design scope**: [Plan 20 Slice 2+ — Extended foreign translation & Windows/macOS platform ports](docs/roadmap/20-future-translation-platforms.md) (foreign custom-command/Meson translation, Windows/MSVC, macOS/Apple Clang, remote execution) remains planned architectural scope. +- **Remaining future design scope**: [Plan 20 Slices 2B/2C & 3](docs/roadmap/20-future-translation-platforms.md) and the [Post-v1 Expansion Roadmap](docs/roadmap/21-expansion-roadmap.md) (Track A zero-CMake self-host & full `VOID_TEST` suite, Track B C driver / custom-command / foreign module translation, Track C macOS/Windows/cross-compilation, Track D shared HTTP CAS & supply-chain provenance, Track E workspaces & daemon) remain planned architectural scope. -Start with the [twenty roadmap plans](docs/roadmap/README.md), +Start with the [roadmap plans](docs/roadmap/README.md), [expansion roadmap](docs/roadmap/21-expansion-roadmap.md), [architecture](docs/roadmap/ARCHITECTURE.md), [requirements](docs/roadmap/REQUIREMENTS.md), and [verification log](docs/agent-workflow/VERIFICATION.md). @@ -72,8 +72,12 @@ Note on optional system dependencies: `Void::Crypto` (`VL-007`) and `Void::Archi All CLI help text (`vbs --help`, `vbs --help`, `vbs compdb --help`, `vbs deps --help`, `vbs-registry --help`, etc.) is auto-generated directly by `Void::Argparse::Parser`: - `vbs [--version] [--verbose] [--quiet] ` -- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache] [--verbose] [--quiet]` +- `vbs init [--dir DIR] [--name NAME] [--library] [--with-toml] [--force]` +- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache] [--native-foreign] [--verbose] [--quiet]` - `vbs test ...` (same flags as `vbs build`, then runs selected `TargetKind::Test` binaries) +- `vbs clean [--build-dir DIR] [--all]` +- `vbs doctor` +- `vbs graph [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang] [--format dot|json]` - `vbs describe [--project DIR] [--build-dir DIR] [--profile NAME] [--compiler gcc|clang]` - `vbs compdb use|show|export|watch ...` - `vbs watch [--project DIR] [--build-dir DIR] [--profile NAME] [--target NAME]...` diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index bb51890..86bb883 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -2,7 +2,7 @@ Updated: 2026-11-27 Branch: main -Stage: VERIFIED — Plans 01–19 + Plan 20 Slice 1 (bounded native CMake graph translation) + VoidLibrary `VL-001`..`VL-013` adoption + self-building/self-testing `vbs test` + cache/digest performance hardening complete +Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1 & 2A (bounded native CMake & Meson translation) + Everyday DX CLI (`init`/`clean`/`doctor`/`graph`/`--native-foreign`) + Post-v1 Expansion Roadmap complete ## Completed delivery waves @@ -39,9 +39,14 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slice 1 (bounded native CMake graph - Verified VoidLibrary's upstream `VL-009` `VOID_TEST(suite, name)` self-registering test macro directly with zero CMake and zero scanner across colliding basenames (`alpha/Unit.cpp`, `beta/Unit.cpp`) in `tests/SelfHostTests.cpp`. - Hardened warm-build caching in `src/State/StateStore.cpp` (stat-validated in-memory `DatabaseSnapshot` cache across `lookup_action` / `load_db_locked` / `save_db_locked`) and `src/Execution/Scheduler.cpp` (run-scoped thread-safe `RunDigestCache` with output invalidation), reducing 16-file warm no-op latency from `16ms` to `4ms` and 39-action Debug self-test warm verification from `18.82s` to `12.16s`. +- **Wave 8 (Plan 20 Slice 2A Bounded Native Meson Translation, Everyday DX CLI, & Post-v1 Expansion Roadmap)**: + - Implemented Plan 20 Slice 2A in `include/Void/Build/Provider/Translator.hpp` and `src/Provider/Translator.cpp`: configure-only Meson setup (`configure_meson_for_translation`, never `meson compile`), strict `meson-info/intro-targets.json` completeness auditing (`audit_meson_introspection`), internal `build.ninja` link-edge recovery and native `Graph::BuildGraph` lowering (`translate_meson_to_native_graph`), and unified `resolve_meson_with_translation` / `resolve_foreign_with_translation` (`RequireNative` vs `FallbackToForeignBuild`), verified end-to-end with C++ native execution and `custom_target` fallback in `tests/FullV1Tests.cpp`. + - Wired opt-in `--native-foreign` on `vbs build`/`vbs test` plus four everyday DX subcommands (`vbs init`, `vbs clean`, `vbs doctor`, `vbs graph --format dot|json`) into `Void::Argparse::Parser` in `src/Main.cpp`, verified end-to-end in `tests/FullV1Tests.cpp` and 32 CLI contracts in `tests/CliContracts.cmake`. + - Authored comprehensive 5-track post-v1 expansion plan in [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) (Track A zero-CMake self-host & full `VOID_TEST` suite; Track B extended foreign translation; Track C macOS/Windows/cross-compilation; Track D shared HTTP CAS & supply-chain provenance; Track E workspaces, daemon & DX). + ## Remaining future scope -- **Plan 20 Slice 2+ ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Extended foreign rule translation (custom commands, foreign C++20 module fileSets, Meson translation), Windows/MSVC & macOS/Apple Clang platform ports, and remote execution remain planned architectural design scope. +- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track A (zero-CMake self-build + full `VOID_TEST` migration), Track B (C driver, custom-command Ninja translation, foreign C++20 modules, Conan2), Track C (macOS/Windows ports + cross-compilation), Track D (remote HTTP CAS + parallel hashing + SBOM/signatures), and Track E2–E4 (`workspace.cpp`, local daemon, `Void::Net`/`Void::Sqlite` alignment). ## Environment notes & upstream boundaries diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 6c7f334..09b6e26 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -1,7 +1,7 @@ # Task graph and ownership Updated: 2026-11-27 -Base HEAD: `363fb82` +Base HEAD: `d3d2666` | Wave | Scope | Status | Primary Deliverables | | --- | --- | --- | --- | @@ -14,4 +14,5 @@ Base HEAD: `363fb82` | Wave 5 (VoidLibrary Reuse & End-to-End Closure) | `Void::Argparse::Parser` across all CLIs, `Void::Algorithms`/`Unicode`/`Async`/`Str`/`Hex`/`Url`/`Scope`/`Stopwatch` adoption, Plan 08 graph lowering (GCC+Clang modules/partitions, unity, header units, sanitizers), live `RegistryClient` + `vbs publish`, full Stage 1 -> Stage 2 `VbsSelfHostRecipe` | COMPLETE & VERIFIED | `src/Main.cpp`, `src/Graph/Graph.cpp`, `src/Package/RegistryClient.cpp`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded test suites | | Wave 6 (Upstream `VL-001`..`VL-013` Pin Bump, Self-Building `vbs build`, Live Logs & Generated CLI Help) | Bump VoidLibrary pin to `3e254055e081a104f08df68dde39711bc7813518`; adopt `Void::Crypto`, `Void::Archive`, `Void::Data::Toml`, `Void::Semver::parse_range`, `Void::FileSystem::FileLock`/`DirectoryWatcher`/`reflink_copy_file`/`atomic_symlink_swap`/`set_canonical_mtime`, `Void::Process`, `Void::Argparse::Parser` subcommands + `option_many` + `parse_detailed`; full self-building root `build.cpp`; live `Void::Log` console progress | COMPLETE & VERIFIED | `CMakeLists.txt`, `cmake/VoidDependency.cmake`, `build.cpp`, `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, `benchmarks/EngineBenchmarks.cpp`, `src/Util/Sha256.cpp`, `src/Package/{Toml,Solver,Archive,Fetch}.cpp`, `src/Platform/{FileOps,ProcessSupervisor}.cpp`, `src/Watch/Watcher.cpp`, `src/Provider/Provider.cpp`, `src/Graph/Graph.cpp`, `src/Execution/Scheduler.cpp`, `recipes/`, updated contracts & docs | | Wave 7 (Plan 20 Slice 1 Bounded CMake Native Translation, Self-Testing `build.cpp`, `VL-009` `VOID_TEST`, & Warm Cache Hardening) | Bounded single-config C++ CMake File API audit + native `Graph::BuildGraph` translation + explicit fallback; self-test target `vbs_self_smoke` in `build.cpp`; `VL-009` `VOID_TEST` zero-CMake basename-collision test; stat-validated `StateStore` cache + `Scheduler` `RunDigestCache` | COMPLETE & VERIFIED | `include/Void/Build/Provider/Translator.hpp`, `src/Provider/Translator.cpp`, `tests/SelfBuildSmoke.cpp`, `src/State/StateStore.{hpp,cpp}`, `src/Execution/Scheduler.cpp`, `build.cpp`, `CMakeLists.txt`, `recipes/SelfHost/VbsSelfHostRecipe.cpp`, expanded tests & docs | -| Future (Plan 20 Slice 2+) | Extended foreign translation (custom commands, Meson) & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | +| Wave 8 (Plan 20 Slice 2A Meson Native Translation, Everyday DX CLI, & Expansion Roadmap) | Bounded Meson `intro-targets.json` + `build.ninja` native translation & unified `resolve_foreign_with_translation`; `vbs build\|test --native-foreign`, `vbs init`, `vbs clean`, `vbs doctor`, `vbs graph`; 5-track post-v1 expansion roadmap | COMPLETE & VERIFIED | `include/Void/Build/Provider/Translator.hpp`, `src/Provider/Translator.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, `tests/CliContracts.cmake`, `docs/roadmap/21-expansion-roadmap.md`, updated docs | +| Future (Tracks A–E / Plan 20 Slices 2B–3) | Zero-CMake self-host & full `VOID_TEST`, C driver & Ninja custom-command translation, macOS/Windows/cross-compile, shared HTTP CAS, `workspace.cpp` & daemon | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 1f588ab..3ebe019 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -36,17 +36,17 @@ dev cpp-gcc -c clang-format --dry-run --Werror \ ```sh dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure ``` -- Exit status: `0` — **8 / 8 passed (100%) in 103.96 sec**: +- Exit status: `0` — **8 / 8 passed (100%) in 107.03 sec**: | # | CTest Name | Scope Verified | Result | Time | | --- | --- | --- | --- | --- | -| 1 | `vbs_sdk_tests` | 17 tests (`SdkDeclarations` 14 + `ExampleContexts` 3 for 7-target self-building/self-testing `build.cpp` and pin `3e254055...`) | Passed | 0.01s | -| 2 | `vbs_core_tests` | 6 tests: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem`), stat-cached `StateStore` CAS recovery/GC, end-to-end native frontend + deterministic build + `RunDigestCache` | Passed | 11.61s | -| 3 | `vbs_v1_tests` | 9 tests: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & security rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration (sanitizers, partitions, unity, header units), AND **Plan 20 Slice 1** bounded native CMake graph translation (equivalence vs official `cmake --build`, adversarial restored-mtime header mutation rebuild, explicit `RequireNative` error + `FallbackToForeignBuild` delegation on `add_custom_command`/`UTILITY`) | Passed | 14.05s | -| 4 | `vbs_registry_tests` | 2 tests: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 4.07s | -| 5 | `vbs_selfhost_tests` | 4 tests: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` (including `Crypto` + `Archive`) + `VoidBuildSdk` + Stage 2, full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` (`stage1/bin/vbs`, zero CMake) -> Stage 2 `stage1/bin/vbs test` with trapped `cmake` on `PATH`, AND **`VL-009` `VOID_TEST(suite, name)`** zero-CMake zero-scanner test binary across colliding basenames (`alpha/Unit.cpp`, `beta/Unit.cpp`) | Passed | 74.12s | +| 1 | `vbs_sdk_tests` | 17 tests (`SdkDeclarations` 14 + `ExampleContexts` 3 for 7-target self-building/self-testing `build.cpp` and pin `3e254055...`) | Passed | 0.02s | +| 2 | `vbs_core_tests` | 6 tests: `Void::Crypto` SHA-256 NIST vectors, `Void::Process` exec-fail & stubborn grandchild `SIGKILL`, profile inheritance/cycles, snapshot mutation/symlinks/header-shadowing (`Void::FileSystem`), stat-cached `StateStore` CAS recovery/GC, end-to-end native frontend + deterministic build + `RunDigestCache` | Passed | 11.16s | +| 3 | `vbs_v1_tests` | 11 tests: CompDB ticket races & `atomic_symlink_swap`, `Void::FileSystem::DirectoryWatcher` + `MetadataOnly` boundary, `Void::Data::Toml` + `Void::Semver::parse_range` PubGrub solver + CAS `vbs.lock`, `Void::Archive` `.tar` determinism & security rejection, real CMake & Meson providers + `VbsDeps.cmake` bridge + relocatable install + CLI `vbs install`/`vbs uninstall`, GCC 16 P1689 modules + full Plan 08 graph integration (sanitizers, partitions, unity, header units), **Plan 20 Slice 1** bounded native CMake translation (equivalence, restored-mtime mutation, `add_custom_command`/`UTILITY` fallback), **Plan 20 Slice 2A** bounded native Meson translation (zero `meson compile`, `custom_target` `RequireNative` rejection + `FallbackToForeignBuild`), AND **Wave 8 DX CLI** E2E (`vbs init` -> `vbs test` -> `vbs graph --format dot\|json` -> `vbs doctor` -> `vbs clean`/`--all`) | Passed | 19.82s | +| 4 | `vbs_registry_tests` | 2 tests: `vbs-registry` HTTP/1.1 security/RBAC/CSRF/XSS/tar-422/backup-restore + full live CLI E2E `vbs publish` -> `vbs deps resolve` -> `vbs build --locked` | Passed | 3.98s | +| 5 | `vbs_selfhost_tests` | 4 tests: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` (including `Crypto` + `Archive`) + `VoidBuildSdk` + Stage 2, full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` (`stage1/bin/vbs`, zero CMake) -> Stage 2 `stage1/bin/vbs test` with trapped `cmake` on `PATH`, AND **`VL-009` `VOID_TEST(suite, name)`** zero-CMake zero-scanner test binary across colliding basenames (`alpha/Unit.cpp`, `beta/Unit.cpp`) | Passed | 71.96s | | 6 | `vbs_sdk_registration` | 17 SDK test registrations verified; named JSON case executed | Passed | 0.01s | -| 7 | `vbs_cli_contract` | 27 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified (`vbs`, `vbs-registry`, `compdb`, `deps`, `build`, `install`, `publish`, etc.) | Passed | 0.04s | +| 7 | `vbs_cli_contract` | 32 native CLI & auto-generated `Void::Argparse::Parser` help/subcommand/error contracts verified (`vbs`, `vbs-registry`, `build --native-foreign`, `init`, `clean`, `doctor`, `graph`, `compdb`, `deps`, `install`, `publish`, etc.) | Passed | 0.05s | | 8 | `vbs_description_contract` | Four runtime profile/compiler contexts (`debug`/`release` x `gcc`/`clang` for 7-target `build.cpp`), auto-generated `vbs_describe --help`, and five error contracts verified | Passed | 0.04s | ## Real Self-Build & Self-Test of VoidBuildSystem (`vbs test`) @@ -56,22 +56,26 @@ dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \ dev cpp-gcc -c build/dev/bin/vbs test --build-dir build/vbs-self --jobs 4 ``` -- Exit status: `0` — **`vbs: [debug] built (39 executed, 0 cached)`** in `42.73s` -> **`vbs test: PASSED 'vbs_self_smoke' (4 ms)`**. +- Exit status: `0` — **`vbs: [debug] built (39 executed, 0 cached)`** in `42.23s` -> **`vbs test: PASSED 'vbs_self_smoke' (4 ms)`**. - Built `libVoidBuildSdk.a`, `libVoidBuildCore.a`, `libVoidBuildRegistry.a`, `bin/vbs`, `bin/vbs-registry`, and `bin/vbs_self_smoke` with live progress logs across all phases. -### Stage 2: Self-built `vbs` verifies warm cached build & self-test +### Stage 2: Self-built `vbs` verifies warm cached build, self-test, `doctor`, and `graph` ```sh VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \ dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs test --build-dir build/vbs-self --jobs 4 +dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs doctor +dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs graph --build-dir build/vbs-self --format dot ``` -- Exit status: `0` — **`vbs: [debug] built (0 executed, 39 cached)`** in `12.16s` (down from `18.82s` prior to `StateStore` stat-validated caching and `RunDigestCache` output invalidation, verifying ~220 MB of `-O0 -g` debug artifacts byte-for-byte via pure-C++ SHA-256) -> **`vbs test: PASSED 'vbs_self_smoke' (3 ms)`**. +- Exit status: `0` — **`vbs: [debug] built (0 executed, 39 cached)`** in `12.21s` -> **`vbs test: PASSED 'vbs_self_smoke' (3 ms)`**. +- `vbs doctor` exited `0`, confirming GCC 16.2.0 (`c++26=yes, reflection=yes, p1689=yes`), `ar`, `git`, `cmake` 4.4.4, `ninja` 1.13.2, `meson` 1.12.1, `clang-scan-deps`, `clang-format`, `Void::Crypto`, and `Void::Archive`. +- `vbs graph --format dot` exited `0`, emitting the 7-target Graphviz DOT dependency graph for `VoidBuildSystem`. ## Clang 23.1.3 Target Matrix (`dev cpp`) ```sh dev cpp -c build/dev/bin/vbs_v1_tests --no-color --filter clang23 ``` -- Exit status: `0` — `1 tests: 1 ✔ in 876.7ms` (`clang23_target_toolchain_and_p1689_module_scan`). +- Exit status: `0` — `1 tests: 1 ✔ in 780.0ms` (`clang23_target_toolchain_and_p1689_module_scan`). - Verified inside `dev cpp`: Clang 23.1.3 + `clang-scan-deps` target probing, C++20 compilation, and full `Graph::lower_project_graph` + `Execution::execute_graph` build of module partition (`vbs.clangcalc:part`) + primary interface (`vbs.clangcalc`) + consumer `main.cpp` using two-step `--precompile` `.pcm` -> `.o` with transitive `-fmodule-file=`. ## Benchmarks (`dev cpp-gcc`) @@ -81,9 +85,8 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 ``` - Exit status: `0`: ```json - {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":25,"cold_build_ms":486,"cold_executed":17,"warm_noop_ms":4,"warm_executed":0,"warm_cached":17} + {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":19,"cold_build_ms":335,"cold_executed":17,"warm_noop_ms":5,"warm_executed":0,"warm_cached":17} ``` - (`warm_noop_ms` improved 4x from `16ms` to `4ms`.) ## Limits and Unrun Checks @@ -91,4 +94,4 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). 3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection. 4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. -5. **Plan 20 Slice 2+ ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Extended foreign rule translation (custom commands, foreign C++20 module fileSets, Meson translation), Windows/MSVC & macOS/Apple Clang platform ports, and remote execution remain unimplemented planned scope. +5. **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Track A (zero-CMake self-build + full `VOID_TEST` suite), Track B (C driver, Ninja custom-command translation, foreign C++20 module fileSets, Conan2), Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D (shared HTTP CAS, parallel hashing, SBOM/signatures), and Track E2–E4 (`workspace.cpp`, local daemon, `Void::Net`/`Void::Sqlite` alignment) remain planned scope. diff --git a/docs/roadmap/20-future-translation-platforms.md b/docs/roadmap/20-future-translation-platforms.md index 8a10eae..0f10d35 100644 --- a/docs/roadmap/20-future-translation-platforms.md +++ b/docs/roadmap/20-future-translation-platforms.md @@ -1,6 +1,6 @@ # 20 — Later native foreign execution and platform ports -Implementation status: **Slice 1 implemented & verified** (bounded single-config C++ CMake File API codemodel audit, native `Graph::BuildGraph` translation, equivalence & restored-mtime mutation tests, and explicit `RequireNative` / `FallbackToForeignBuild` policy in [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp) and [Translator.cpp](../../src/Provider/Translator.cpp)); **extended foreign rules (custom commands, foreign C++20 module fileSets, Meson translation), Windows/MSVC & macOS/Apple Clang ports, and remote execution remain planned scope**. See [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md). +Implementation status: **Slices 1 & 2A implemented & verified** (bounded single-config C++ CMake File API codemodel and Meson `intro-targets.json` + `build.ninja` audits, native `Graph::BuildGraph` translation, unified `resolve_foreign_with_translation`, CLI `vbs build|test --native-foreign`, equivalence & restored-mtime mutation tests, and explicit `RequireNative` / `FallbackToForeignBuild` policy in [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp) and [Translator.cpp](../../src/Provider/Translator.cpp)); **Slices 2B/2C (C driver, custom-command translation, foreign C++20 module fileSets), Slice 3 (Windows/MSVC & macOS/Apple Clang ports), and remote execution remain planned scope** — see [21-expansion-roadmap.md](21-expansion-roadmap.md), [STATE](../agent-workflow/STATE.md), and [VERIFICATION](../agent-workflow/VERIFICATION.md). ## Requirements and ownership diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md new file mode 100644 index 0000000..0d39f28 --- /dev/null +++ b/docs/roadmap/21-expansion-roadmap.md @@ -0,0 +1,87 @@ +# 21 — Post-v1 Expansion Roadmap + +Status: Planning & active execution guide (Plans **01–19** and **Plan 20 Slices 1 & 2A** are implemented and verified; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). + +This roadmap defines five orthogonal expansion tracks for taking VoidBuildSystem from a verified self-hosting Linux C++26 build system into a multi-platform, distributed, daily-driver ecosystem. Each track preserves core architectural invariants: ordinary C++ descriptions, hermetic content-verified snapshots, isolated profiles, immutable CAS publication, and explicit diagnostics over silent approximation. + +```mermaid +flowchart LR + V1["Verified Core (Plans 01–19 + Plan 20 Slice 1/2A)"] + V1 --> TA["Track A: Full Zero-CMake Self-Host"] + V1 --> TB["Track B: Foreign Translation (2B/2C)"] + V1 --> TC["Track C: Cross-Platform & Cross-Compile"] + V1 --> TD["Track D: Remote Cache & Attestations"] + V1 --> TE["Track E: Workspaces, Daemon & DX"] +``` + +--- + +## Track A — Full Zero-CMake Self-Hosting & Native Test Suite + +**Goal**: Make `VoidBuildSystem` build `VoidLibrary` and all of its own binaries **and** full test suites purely via `vbs test` without invoking CMake at all. + +| Phase | Concrete Scope | Acceptance Gate | +| --- | --- | --- | +| **A1 — Native VoidLibrary Recipe Integration** | Expose a `project.native_recipe(...)` or built-in `Void::Build::Recipes::add_void_library_native` hook callable directly from root `build.cpp` so `build.cpp` does not even need the CMake provider for `VoidLibrary`. | `vbs build` builds `VoidBuildSystem` + `VoidLibrary` with a trapped `cmake` on `PATH`. | +| **A2 — Full `VOID_TEST` (`VL-009`) Suite Migration** | Port `tests/{SdkDeclarations,ExampleContexts,CoreEngineTests,FullV1Tests,RegistryTests,SelfHostTests}.cpp` to VoidLibrary's self-registering `VOID_TEST(suite, name)` macro and declare all 5 test binaries in root `build.cpp`. | `vbs test` runs every unit, integration, registry, and self-host test directly without CMake or `VoidTestScanner.cmake`. | +| **A3 — Reproducible Stage 2 == Stage 3 Bit-Identical Bootstrap** | Build `stage1/vbs` -> `stage2/vbs` -> `stage3/vbs` with fixed `SOURCE_DATE_EPOCH` and verify `sha256(stage2/vbs) == sha256(stage3/vbs)`. | Automated bit-for-bit equality check in CI. | + +--- + +## Track B — Foreign Build Translation Expansion (Plan 20 Slices 2B & 2C) + +**Goal**: Expand bounded native translation beyond single-config C++ libraries/executables while never silently dropping unsupported rules. + +| Phase | Concrete Scope | Acceptance Gate | +| --- | --- | --- | +| **B1 — Native C Compiler Driver (`C` + Mixed `C`/`C++`)** | Extend `ToolchainCapabilities` with `c_compiler` (`gcc`/`clang`), C standard flags (`c11`/`c17`/`c23`), and multi-compile-group lowering in `Graph.cpp` + `Translator.cpp`. | Mixed C/C++ CMake and Meson projects (e.g., zlib/sqlite3-style fixtures) translate natively and match official tool outputs. | +| **B2 — Bounded `build.ninja` Custom-Command Translation** | Parse configured Ninja `rule` / `build` edges for hermetic `add_custom_command` / `custom_target` code generators into VBS `ActionKind::Custom` nodes, strictly rejecting unverified side-effecting rules. | Generated-header CMake/Meson fixtures execute natively under VBS CAS caching and rebuild correctly under generator-input mutations. | +| **B3 — Foreign C++20 `CXX_MODULES` Translation & Conan2 Binary Adapter** | Lower CMake `CXX_MODULES` `fileSets` onto VBS's P1689 scanner + `ModuleBmi` pipeline; implement live Conan2 `conan install --format=json` consumer adapter when `conan` is available. | Foreign CMake C++20 module fixture builds natively under GCC 16 and Clang 23; Conan2 fixture verified in a container with `conan` installed. | + +--- + +## Track C — Cross-Platform Portability & Cross-Compilation (Plan 20 Slice 3) + +**Goal**: Bring Linux-grade process supervision, filesystem atomicity, and toolchain probing to macOS and Windows without weakening invariants. + +| Phase | Concrete Scope | Acceptance Gate | +| --- | --- | --- | +| **C1 — Platform Backend Split** | Split `src/Platform/` into `Linux/`, `MacOS/`, and `Windows/` behind clean interfaces (`FileOps`, `ProcessSupervisor`, `DirectoryWatcher`), delegating to `Void::System` as upstream adds OS backends. | Zero Linux regressions; clean platform abstraction boundary. | +| **C2 — macOS / Apple Clang & `ld64`** | Apple Clang toolchain probes, `.dylib` + `@rpath`/`@loader_path` install-name lowering, `FSEvents` watcher, Mach-O deterministic timestamps. | Real macOS CI runner passing all SDK, core, module, and install tests. | +| **C3 — Windows / MSVC & `clang-cl`** | MSVC (`cl.exe`, `lib.exe`, `link.exe`, `/showIncludes`, `.pdb`, `/FS`, `.dll`/`.lib` import libraries), Job Object process-tree kill, `ReadDirectoryChangesW` watcher, case-insensitive path conflict detection. | Real Windows CI runner passing process-tree kill, header-shadowing, and install relocation tests. | +| **C4 — True Host-vs-Target Cross-Compilation** | Dual-context evaluation (`host` profile for code generators and `build_dependency` tools vs `target` profile for cross-compiled products), sysroot & `--target=` triple propagation. | `linux-x86_64` host cross-compiling `linux-aarch64` fixture while executing host-compiled generator natively. | + +--- + +## Track D — Distributed Caching, Remote Execution & Supply-Chain Security + +**Goal**: Enable CI/team-wide action reuse and verifiable provenance without compromising local hermeticity. + +| Phase | Concrete Scope | Acceptance Gate | +| --- | --- | --- | +| **D1 — Shared HTTP Content-Addressed Action Cache (CAS)** | Push/pull action records and output blobs (`PUT/GET /v1/cas/blobs/{sha256}`, `/v1/cas/actions/{action_key}`) against `vbs-registry` or any compatible HTTP CAS server with bearer auth and digest verification on every read. | Cold CI build populates remote CAS; second clean machine achieves 100% cache hit with verified SHA-256 outputs. | +| **D2 — Fast Hashing & Parallel Snapshot Pipeline** | Adopt `Void::Crypto` BLAKE2b / hardware-accelerated SHA-256 (when available) + parallel snapshot hashing across `Void::Concurrency::ThreadPool` + optional `Void::Sqlite` indexed state store for >10k-file monorepos. | Sub-second warm no-op on 5,000-file synthetic benchmark fixture (`vbs_benchmarks`). | +| **D3 — Supply-Chain Provenance & Signed Packages** | Emit SPDX/CycloneDX SBOM JSON from `vbs.lock` + `BuildGraph`; optional Ed25519 package & binary signature verification in `vbs publish` and `vbs build --locked`. | Tampered archive or signature fails closed before extraction. | + +--- + +## Track E — Developer Experience, Workspaces & Ecosystem + +**Goal**: Make VBS effortless for multi-package teams, editors, and everyday C++ workflows. + +| Phase | Concrete Scope | Acceptance Gate | +| --- | --- | --- | +| **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. | +| **E2 — Multi-Package Workspaces (`workspace.cpp`)** | Shared `vbs.lock`, shared CAS, cross-member local target linking, and affected-target graph selection (`vbs build --member ` / `--changed-since `). | 3-package workspace fixture building shared library + app + tests with unified lockfile. | +| **E3 — Background Build/Metadata Daemon & IDE Integration** | Optional local Unix-socket daemon (`vbs daemon`) holding warm `StateStore`, `RunDigestCache`, and `DirectoryWatcher` so editor `compile_commands.json` refreshes and incremental `vbs build` respond in <50ms. | Daemon auto-restarts on binary upgrade, honors `SignalWatcher` graceful shutdown, and preserves ticket ordering. | +| **E4 — Transport & Storage Upstream Alignment** | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains. | + +--- + +## Recommended Next Execution Order + +1. **Track A1 + A2** (highest ROI for VBS itself): zero-CMake self-build + full `VOID_TEST` native suite via `vbs test`. +2. **Track B1 + B2**: C compiler driver + bounded Ninja custom-command translation so real-world C/C++ CMake/Meson dependencies execute natively. +3. **Track D1 + D2**: shared HTTP CAS cache on `vbs-registry` + parallel snapshot hashing for large repos. +4. **Track E2**: multi-package `workspace.cpp` support. +5. **Track C1–C4**: macOS / Windows platform ports + dual-profile cross-compilation once host CI runners are provisioned. diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index a91ae07..190b58c 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -1,7 +1,7 @@ # Roadmap and delivery graph -Plans **01–19** and **Plan 20 Slice 1** (bounded native CMake graph translation on Linux) are implemented and verified in the native codebase and CTest -suites; **Plan 20 Slice 2+** (extended custom-command/Meson translation, Windows/macOS ports, remote execution) remains future architectural design scope. For implemented +Plans **01–19** and **Plan 20 Slices 1 & 2A** (bounded native CMake & Meson graph translation on Linux) are implemented and verified in the native codebase and CTest +suites; **Plan 20 Slices 2B/2C & 3** and the five post-v1 expansion tracks in [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) define the next phases. For implemented commands, targets, and workflow usage, see the [project README](../../README.md) and [verification record](../agent-workflow/VERIFICATION.md). @@ -31,7 +31,8 @@ Authority: [requirements](REQUIREMENTS.md), [architecture](ARCHITECTURE.md), | [17 — Registry web administration](17-registry-ui.md) | Implemented & Verified | [registry/web/](../../registry/web/index.html) | | [18 — Native self-hosting and VoidLibrary migration](18-self-host-voidlibrary.md) | Implemented & Verified | [VoidLibraryRecipe.cpp](../../recipes/VoidLibrary/VoidLibraryRecipe.cpp), [TestRegistryGen.cpp](../../src/SelfHost/TestRegistryGen.cpp) | | [19 — Quality, performance and CI](19-quality-performance-ci.md) | Implemented & Verified | [tests/](../../tests/CMakeLists.txt), [EngineBenchmarks.cpp](../../benchmarks/EngineBenchmarks.cpp), [.github/workflows/ci.yml](../../.github/workflows/ci.yml) | -| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | Slice 1 Implemented & Verified; OS ports planned | [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp), [Translator.cpp](../../src/Provider/Translator.cpp) (bounded CMake native translation + fallback); Windows/macOS ports & extended foreign translation planned | +| [20 — Later native foreign execution and platform ports](20-future-translation-platforms.md) | Slices 1 & 2A Implemented & Verified; 2B/2C & OS ports planned | [Translator.hpp](../../include/Void/Build/Provider/Translator.hpp), [Translator.cpp](../../src/Provider/Translator.cpp) (bounded CMake & Meson native translation + unified fallback + `--native-foreign`); C driver, custom commands, Windows/macOS ports planned | +| [21 — Post-v1 expansion roadmap](21-expansion-roadmap.md) | Track E1 Implemented; Tracks A–E Planned | Five-track expansion roadmap (zero-CMake self-host & full `VOID_TEST`, extended foreign translation, cross-platform/cross-compile, remote HTTP CAS & attestations, workspaces/daemon/DX) | ## Dependency graph diff --git a/include/Void/Build/Provider/Translator.hpp b/include/Void/Build/Provider/Translator.hpp index 3ccd15d..ad3194f 100644 --- a/include/Void/Build/Provider/Translator.hpp +++ b/include/Void/Build/Provider/Translator.hpp @@ -90,4 +90,37 @@ resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore TranslationPolicy policy = TranslationPolicy::FallbackToForeignBuild, std::stop_token stop = {}); +// Configures Meson ONLY (`meson setup`, never `meson compile`) and returns `meson-info/`. +[[nodiscard]] Void::Result::Result +configure_meson_for_translation(const ProviderRequest &request, + const std::filesystem::path &configure_dir, + std::stop_token stop = {}); + +// Audits a configured Meson `meson-info/intro-targets.json` against Plan 20's bounded native +// subset: pure C++ `static library`, `shared library`, and `executable` targets without custom +// targets, generated sources, non-C++ languages, or untracked link artifacts. +[[nodiscard]] Void::Result::Result +audit_meson_introspection(const std::filesystem::path &configure_dir); + +// Translates an audited Meson project directly into a native VBS BuildGraph (zero `meson compile`). +[[nodiscard]] Void::Result::Result +translate_meson_to_native_graph(const ProviderRequest &request, + const std::filesystem::path &configure_dir, + const std::filesystem::path &native_build_root, + const Snapshot::InputSnapshot *snapshot = nullptr); + +// End-to-end Plan 20 Slice 2A resolver for Meson dependencies. +[[nodiscard]] Void::Result::Result +resolve_meson_with_translation(const ProviderRequest &request, State::StateStore &state, + TranslationPolicy policy = TranslationPolicy::FallbackToForeignBuild, + std::stop_token stop = {}); + +// Unified Plan 20 dispatcher: translates `cmake` and `meson` dependencies natively under `policy`, +// and delegates other builders cleanly to `resolve_foreign_provider`. +[[nodiscard]] Void::Result::Result +resolve_foreign_with_translation( + const ProviderRequest &request, State::StateStore &state, + TranslationPolicy policy = TranslationPolicy::FallbackToForeignBuild, + std::stop_token stop = {}); + } // namespace Void::Build::Provider diff --git a/src/Main.cpp b/src/Main.cpp index 1d2b47f..05c78e8 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -496,6 +497,7 @@ struct BuildCmdOptions { bool no_cache{false}; bool locked{false}; bool offline{false}; + bool native_foreign{false}; }; int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { @@ -695,16 +697,34 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { build_root / ".vbs" / "providers", Provider::ProviderMode::FullBuild, {}}; - auto exp = Provider::resolve_foreign_provider(preq); - if (!exp) { - std::cerr << "vbs: " << exp.error().message() << '\n'; - return 1; - } - Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})", - prof_name, exp->targets.size(), effective_dep.name, - exp->from_cache ? "cached" : "built"); - for (const auto &[k, v] : exp->targets) { - imported_targets[k] = v; + if (opts.native_foreign && + (effective_dep.builder == "cmake" || effective_dep.builder == "meson")) { + auto tr = Provider::resolve_foreign_with_translation( + preq, *state, Provider::TranslationPolicy::FallbackToForeignBuild); + if (!tr) { + std::cerr << "vbs: " << tr.error().message() << '\n'; + return 1; + } + Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})", + prof_name, tr->exported.targets.size(), effective_dep.name, + tr->executed_natively + ? "native-translated" + : (tr->exported.from_cache ? "cached" : "built")); + for (const auto &[k, v] : tr->exported.targets) { + imported_targets[k] = v; + } + } else { + auto exp = Provider::resolve_foreign_provider(preq); + if (!exp) { + std::cerr << "vbs: " << exp.error().message() << '\n'; + return 1; + } + Void::Log::info("Provider", "[{}] Imported {} target(s) from '{}' ({})", + prof_name, exp->targets.size(), effective_dep.name, + exp->from_cache ? "cached" : "built"); + for (const auto &[k, v] : exp->targets) { + imported_targets[k] = v; + } } } } @@ -1353,6 +1373,318 @@ int execute_deps_command(std::string_view sub, const DepsCmdOptions &opts) { return 0; } +struct InitCmdOptions { + std::string dir_arg; + std::optional name_arg; + bool library{false}; + bool with_toml{false}; + bool force{false}; +}; + +int execute_init_command(const InitCmdOptions &opts) { + std::error_code ec; + const std::filesystem::path target_dir = std::filesystem::path{opts.dir_arg}.lexically_normal(); + std::filesystem::create_directories(target_dir, ec); + if (ec) { + std::cerr << "vbs init: cannot create directory '" << target_dir.string() + << "': " << ec.message() << '\n'; + return 1; + } + + const auto canon = std::filesystem::weakly_canonical(target_dir, ec); + std::string raw_name = + (opts.name_arg && !opts.name_arg->empty()) ? *opts.name_arg : canon.filename().string(); + if (raw_name.empty()) { + raw_name = "app"; + } + std::string ident; + for (const char c : raw_name) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '_') { + ident.push_back(c); + } else if (c == '-' || c == ' ') { + ident.push_back('_'); + } + } + if (ident.empty() || (ident.front() >= '0' && ident.front() <= '9')) { + ident = "vbs_" + ident; + } + + const auto build_cpp = target_dir / "build.cpp"; + if (!opts.force && std::filesystem::exists(build_cpp, ec)) { + std::cerr << "vbs init: '" << build_cpp.string() + << "' already exists (pass --force to overwrite)\n"; + return 2; + } + + auto write_checked = [&](const std::filesystem::path &p, std::string_view content) -> bool { + auto w = Platform::atomic_write_file(p, content, false); + if (!w) { + std::cerr << "vbs init: failed writing '" << p.string() << "': " << w.error().message() + << '\n'; + return false; + } + return true; + }; + + std::string build_src = + "#include \n\nvoid build(Void::Build::Project &project) {\n"; + if (opts.with_toml) { + build_src += " project.dependencies_file(\"vbs.deps.toml\");\n\n"; + } + if (opts.library) { + build_src += " auto lib = project.static_library(\"" + raw_name + + "\");\n" + " lib.cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"src/" + + ident + + ".cpp\"})\n" + " .include_directory(\"include\", Void::Build::Visibility::Public)\n" + " .install(\"lib\");\n" + " project.install_directory(\"include\", \"include\");\n\n" + " auto t = project.test(\"" + + ident + + "_tests\");\n" + " t.cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"tests/test_main.cpp\"})\n" + " .link(lib);\n"; + } else { + build_src += " auto lib = project.static_library(\"" + ident + + "_lib\");\n" + " lib.cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"src/" + + ident + + ".cpp\"})\n" + " .include_directory(\"include\", Void::Build::Visibility::Public);\n\n" + " auto app = project.executable(\"" + + raw_name + + "\");\n" + " app.cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"src/main.cpp\"})\n" + " .link(lib)\n" + " .install(\"bin\");\n\n" + " auto t = project.test(\"" + + ident + + "_tests\");\n" + " t.cxx_standard(Void::Build::CxxStandard::Cxx26)\n" + " .sources({\"tests/test_main.cpp\"})\n" + " .link(lib);\n"; + } + build_src += "}\n"; + + if (!write_checked(build_cpp, build_src)) { + return 1; + } + if (!write_checked(target_dir / "include" / (ident + ".hpp"), + "#pragma once\n\nnamespace " + ident + " {\nint answer();\n}\n")) { + return 1; + } + if (!write_checked(target_dir / "src" / (ident + ".cpp"), + "#include \"" + ident + ".hpp\"\n\nnamespace " + ident + + " {\nint answer() { return 42; }\n}\n")) { + return 1; + } + if (!opts.library) { + if (!write_checked(target_dir / "src" / "main.cpp", + "#include \"" + ident + + ".hpp\"\n#include \n\nint main() {\n std::cout << \"" + + raw_name + ": answer=\" << " + ident + + "::answer() << '\\n';\n return 0;\n}\n")) { + return 1; + } + } + if (!write_checked(target_dir / "tests" / "test_main.cpp", + "#include \"" + ident + ".hpp\"\n\nint main() { return " + ident + + "::answer() == 42 ? 0 : 1; }\n")) { + return 1; + } + if (!write_checked(target_dir / ".gitignore", + "/build/\n/.vbs/\n/compile_commands.json\n.env\n")) { + return 1; + } + if (opts.with_toml) { + if (!write_checked(target_dir / "vbs.deps.toml", + "# Declarative dependency manifest for " + raw_name + "\n")) { + return 1; + } + } + + Void::Log::info("Init", "Initialized VBS {} project '{}' in '{}'", + opts.library ? "library" : "application", raw_name, target_dir.string()); + std::cout << "initialized " << raw_name << " in " << target_dir.string() << '\n'; + return 0; +} + +struct CleanCmdOptions { + std::string build_arg; + bool clean_all{false}; +}; + +int execute_clean_command(const CleanCmdOptions &opts) { + const std::filesystem::path build_root{opts.build_arg}; + std::error_code ec; + if (!std::filesystem::exists(build_root, ec)) { + std::cout << "clean: nothing to remove in " << build_root.string() << '\n'; + return 0; + } + if (opts.clean_all) { + Void::Log::info("Clean", "Removing entire build directory '{}'...", build_root.string()); + std::filesystem::remove_all(build_root, ec); + if (ec) { + std::cerr << "vbs clean: failed removing '" << build_root.string() + << "': " << ec.message() << '\n'; + return 1; + } + std::cout << "cleaned " << build_root.string() << " (all)\n"; + return 0; + } + const auto profiles_dir = build_root / "profiles"; + std::size_t removed = 0; + if (std::filesystem::exists(profiles_dir, ec)) { + Void::Log::info("Clean", "Removing profile outputs under '{}' (preserving .vbs/cache)...", + profiles_dir.string()); + removed += static_cast(std::filesystem::remove_all(profiles_dir, ec)); + } + const auto compdb = build_root / "compile_commands.json"; + if (std::filesystem::exists(compdb, ec) || std::filesystem::is_symlink(compdb, ec)) { + std::filesystem::remove(compdb, ec); + ++removed; + } + std::cout << "cleaned " << removed << " path(s) in " << build_root.string() + << " (preserved .vbs cache/state)\n"; + return 0; +} + +int execute_doctor_command() { + std::cout << "VoidBuildSystem " << Bootstrap::version << " (" << Bootstrap::os << "/" + << Bootstrap::architecture << ")\n"; + auto check_tool = [](std::string_view label, const char *bin, bool required) { + auto found = Platform::resolve_executable(bin); + std::cout << " " << (found ? "[ok] " : (required ? "[FAIL]" : "[opt] ")) << " " << label + << ": " << (found ? found->string() : std::string{"not found"}) << '\n'; + return found.has_value(); + }; + const bool has_gcc = check_tool("g++", "g++", true); + (void)check_tool("clang++", "clang++", false); + (void)check_tool("clang-scan-deps", "clang-scan-deps", false); + (void)check_tool("ar", "ar", true); + (void)check_tool("git", "git", false); + (void)check_tool("cmake", "cmake", false); + (void)check_tool("ninja", "ninja", false); + (void)check_tool("meson", "meson", false); + (void)check_tool("conan", "conan", false); + (void)check_tool("clang-format", "clang-format", false); + + std::cout << " [ok] Void::Crypto built-in SHA-256: enabled\n"; + std::cout << " [ok] Void::Archive built-in USTAR/PAX: enabled\n"; + + if (has_gcc) { + Void::FileSystem::TempDir tmp{"vbs_doc_"}; + auto ctx = + default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + if (auto tc = Toolchain::discover_and_probe(ctx, tmp.path()); tc) { + std::cout << " [ok] GCC probe: " << tc->version_banner + << " (c++26=" << (tc->supports_cxx26 ? "yes" : "no") + << ", reflection=" << (tc->supports_reflection ? "yes" : "no") + << ", p1689=" << (tc->supports_p1689_scan ? "yes" : "no") << ")\n"; + } + } + return has_gcc ? 0 : 1; +} + +struct GraphCmdOptions { + std::string project_arg; + std::optional build_arg; + std::string profile_name{"debug"}; + std::optional compiler_arg; + std::string format{"dot"}; +}; + +int execute_graph_command(const GraphCmdOptions &opts) { + if (opts.format != "dot" && opts.format != "json") { + std::cerr << "vbs graph: unsupported --format '" << opts.format + << "' (expected 'dot' or 'json')\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 graph: " << 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 graph: " << compiled.error().message() << '\n'; + return 1; + } + auto profs = Config::discover_profiles(*compiled, fopts); + if (!profs) { + std::cerr << "vbs graph: " << profs.error().message() << '\n'; + return 1; + } + ProfileContext ctx; + try { + ctx = profs->resolve(opts.profile_name, compiler_override, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + } catch (const std::exception &ex) { + std::cerr << "vbs graph: " << ex.what() << '\n'; + return 2; + } + auto desc = Config::evaluate_project(*compiled, ctx, fopts); + if (!desc) { + std::cerr << "vbs graph: " << desc.error().message() << '\n'; + return 1; + } + + if (opts.format == "json") { + std::cout << "{\"profile\":" << Util::json_quote(desc->profile.name) << ",\"targets\":"; + std::cout << Util::json_array(desc->targets, [](const TargetRecord &t) { + return "{\"name\":" + Util::json_quote(t.name) + + ",\"kind\":" + Util::json_quote(target_kind_name(t.kind)) + ",\"links\":" + + Util::json_array(t.links, + [](const LinkRecord &l) { + return Util::json_quote( + l.kind == LinkKind::Imported + ? (l.dependency + "::" + l.target) + : l.target); + }) + + '}'; + }); + std::cout << "}\n"; + return 0; + } + + std::cout << "digraph vbs_targets {\n"; + std::cout << " rankdir=LR;\n"; + for (const auto &t : desc->targets) { + std::cout << " " << Util::json_quote(t.name) << " [label=" + << Util::json_quote(t.name + "\n(" + std::string{target_kind_name(t.kind)} + ")") + << "];\n"; + } + for (const auto &t : desc->targets) { + for (const auto &pre : t.prerequisites) { + std::cout << " " << Util::json_quote(t.name) << " -> " << Util::json_quote(pre) + << " [style=dashed];\n"; + } + for (const auto &l : t.links) { + const std::string dst = + l.kind == LinkKind::Imported ? (l.dependency + "::" + l.target) : l.target; + std::cout << " " << Util::json_quote(t.name) << " -> " << Util::json_quote(dst) + << ";\n"; + } + } + std::cout << "}\n"; + return 0; +} + } // namespace int main(int argc, char **argv) { @@ -1382,6 +1714,12 @@ int main(int argc, char **argv) { GcCmdOptions gc_opts; gc_opts.build_arg = (std::filesystem::path{cwd} / "build").string(); GenTestsCmdOptions gen_tests_opts; + InitCmdOptions init_opts; + init_opts.dir_arg = cwd; + CleanCmdOptions clean_opts; + clean_opts.build_arg = (std::filesystem::path{cwd} / "build").string(); + GraphCmdOptions graph_opts; + graph_opts.project_arg = cwd; auto add_log_flags = [&](Void::Argparse::Parser &p, bool allow_short_v = true) { p.flag("--verbose", allow_short_v ? "-v" : "", "Enable verbose debug logs", verbose) @@ -1402,7 +1740,10 @@ int main(int argc, char **argv) { .option("--jobs", "-j", "Maximum parallel compilation/link jobs", build_opts.jobs_arg) .flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked) .flag("--offline", "", "Disallow network fetches", build_opts.offline) - .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache); + .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) + .flag("--native-foreign", "", + "Translate supported CMake/Meson dependencies to native VBS actions (Plan 20)", + build_opts.native_foreign); add_log_flags(p); }; @@ -1536,6 +1877,39 @@ int main(int argc, char **argv) { gen_tests_opts.out_arg); add_log_flags(gen_tests_cmd); + auto &init_cmd = + root.subcommand("init", "Scaffold a new ready-to-build C++26 VoidBuildSystem project"); + init_cmd.option_default("--dir", "-C", "Target project directory", init_opts.dir_arg, cwd) + .option("--name", "-n", "Project/target name (defaults to directory name)", + init_opts.name_arg) + .flag("--library", "", "Scaffold a static library project instead of an executable", + init_opts.library) + .flag("--with-toml", "", "Include a vbs.deps.toml dependency manifest", init_opts.with_toml) + .flag("--force", "", "Overwrite existing build.cpp if present", init_opts.force); + add_log_flags(init_cmd); + + auto &clean_cmd = + root.subcommand("clean", "Remove generated profile build artifacts (preserving cache)"); + clean_cmd + .option_default("--build-dir", "-B", "Build directory", clean_opts.build_arg, + clean_opts.build_arg) + .flag("--all", "", "Also delete .vbs cache, snapshots, and state store", + clean_opts.clean_all); + add_log_flags(clean_cmd); + + auto &doctor_cmd = + root.subcommand("doctor", "Check host compilers, tools, and VBS runtime capabilities"); + add_log_flags(doctor_cmd); + + auto &graph_cmd = + root.subcommand("graph", "Export target dependency graph in Graphviz DOT or JSON format"); + graph_cmd.option_default("--project", "-C", "Project directory", graph_opts.project_arg, cwd) + .option("--build-dir", "-B", "Build output directory", graph_opts.build_arg) + .option_default("--profile", "-p", "Profile name", graph_opts.profile_name, "debug") + .option("--compiler", "", "Override compiler family (gcc|clang)", graph_opts.compiler_arg) + .option_default("--format", "-f", "Output format (dot|json)", graph_opts.format, "dot"); + add_log_flags(graph_cmd); + const auto parsed = root.parse_detailed(argc, argv); if (parsed.is_help()) { std::cout << parsed.message; @@ -1560,8 +1934,9 @@ int main(int argc, char **argv) { const std::string_view cmd = parsed.matched_command_path.front(); const bool machine_quiet_default = - (cmd == "describe") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && - parsed.matched_command_path[1] == "show"); + (cmd == "describe") || (cmd == "graph") || (cmd == "doctor") || + (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && + parsed.matched_command_path[1] == "show"); const Void::Log::Level log_level = verbose ? Void::Log::Level::Debug : ((quiet || machine_quiet_default) ? Void::Log::Level::Warning @@ -1607,6 +1982,18 @@ int main(int argc, char **argv) { if (cmd == "gen-tests") { return execute_gen_tests_command(gen_tests_opts); } + if (cmd == "init") { + return execute_init_command(init_opts); + } + if (cmd == "clean") { + return execute_clean_command(clean_opts); + } + if (cmd == "doctor") { + return execute_doctor_command(); + } + if (cmd == "graph") { + return execute_graph_command(graph_opts); + } std::cerr << "vbs: unhandled subcommand '" << cmd << "'\n"; return 2; diff --git a/src/Provider/Translator.cpp b/src/Provider/Translator.cpp index 3c54f44..4d01545 100644 --- a/src/Provider/Translator.cpp +++ b/src/Provider/Translator.cpp @@ -853,4 +853,569 @@ resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore return res; } +namespace { + +std::string meson_option_value(const OptionValue &v) { + return std::visit( + [](const auto &inner) -> std::string { + using T = std::remove_cvref_t; + if constexpr (std::same_as) { + return inner; + } else if constexpr (std::same_as) { + return inner ? "true" : "false"; + } else { + return std::to_string(inner); + } + }, + v.value); +} + +std::vector get_str_array(const JsonVal::Object &obj, const std::string &k) { + std::vector out; + const auto *v = find_key(obj, k); + if (!v) { + return out; + } + if (const auto *arr = std::get_if(&v->value)) { + for (const auto &item : *arr) { + if (const auto *s = std::get_if(&item.value)) { + out.push_back(*s); + } + } + } + return out; +} + +struct ParsedMesonTarget { + std::string id; + std::string name; + std::string type; + std::vector filenames; + std::vector sources; + std::vector> includes; + std::vector defines; + std::vector compile_options; + std::vector link_options; + CxxStandard cxx_standard{CxxStandard::Default}; + std::vector dep_ids; +}; + +struct ParsedMesonModel { + TranslationAuditReport audit; + std::map> targets_by_id; + std::vector target_order; +}; + +Void::Result::Result +load_and_audit_meson(const std::filesystem::path &configure_dir) { + const auto intro_targets = configure_dir / "meson-info" / "intro-targets.json"; + auto parsed = parse_json_file(intro_targets); + if (!parsed) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::not_found, + std::format("Meson introspection file missing or invalid at '{}'", + intro_targets.string()))}; + } + const auto *arr = std::get_if(&parsed->value); + if (!arr) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "Meson intro-targets.json root must be an array")}; + } + + ParsedMesonModel out; + auto add_unsupported = [&](std::string target_name, std::string kind, std::string detail) { + out.audit.status = TranslationStatus::Unsupported; + out.audit.unsupported.push_back( + UnsupportedConstruct{std::move(target_name), std::move(kind), std::move(detail)}); + }; + + // Map known output filenames (relative & absolute) -> target id for link edge recovery. + std::map> artifact_to_id; + + for (const auto &tv : *arr) { + const auto *to = std::get_if(&tv.value); + if (!to) { + continue; + } + ParsedMesonTarget pt; + pt.id = get_str(*to, "id"); + pt.name = get_str(*to, "name"); + pt.type = get_str(*to, "type"); + if (pt.id.empty()) { + pt.id = pt.name; + } + + if (pt.type == "custom" || pt.type == "run") { + add_unsupported( + pt.name, "custom_target", + std::format("Meson target '{}' has type '{}' (custom/run targets cannot be " + "faithfully translated from intro-targets.json)", + pt.name, pt.type)); + continue; + } + if (pt.type != "static library" && pt.type != "shared library" && pt.type != "executable") { + add_unsupported( + pt.name, "unsupported_target_type", + std::format("Meson target '{}' has unsupported type '{}'", pt.name, pt.type)); + continue; + } + + for (const auto &fn : get_str_array(*to, "filename")) { + const std::filesystem::path abs_fn = std::filesystem::path{fn}.lexically_normal(); + pt.filenames.push_back(abs_fn); + artifact_to_id[abs_fn.string()] = pt.id; + artifact_to_id[abs_fn.filename().string()] = pt.id; + const auto rel = abs_fn.lexically_relative(configure_dir); + if (!rel.empty() && !rel.string().starts_with("..")) { + artifact_to_id[rel.generic_string()] = pt.id; + } + } + + if (const auto *ts = find_key(*to, "target_sources")) { + if (const auto *tsarr = std::get_if(&ts->value)) { + for (const auto &tsv : *tsarr) { + const auto *tso = std::get_if(&tsv.value); + if (!tso) { + continue; + } + const auto lang = get_str(*tso, "language"); + const auto srcs = get_str_array(*tso, "sources"); + const auto gen_srcs = get_str_array(*tso, "generated_sources"); + if (!gen_srcs.empty()) { + add_unsupported( + pt.name, "generated_source", + std::format("Meson target '{}' depends on {} generated source(s) " + "(first: '{}')", + pt.name, gen_srcs.size(), gen_srcs.front())); + } + if (!srcs.empty() && lang != "cpp") { + add_unsupported( + pt.name, "unsupported_language", + std::format("Meson target '{}' compiles language '{}' (bounded subset " + "supports cpp only)", + pt.name, lang)); + } + for (const auto &s : srcs) { + pt.sources.push_back(std::filesystem::path{s}.lexically_normal()); + } + + const auto params = get_str_array(*tso, "parameters"); + for (std::size_t i = 0; i < params.size(); ++i) { + const auto &p = params[i]; + if (p.starts_with("-I") && p.size() > 2) { + std::filesystem::path ip{p.substr(2)}; + if (!ip.is_absolute()) { + ip = (configure_dir / ip).lexically_normal(); + } + if (!std::ranges::contains(pt.includes, std::pair{ip, false})) { + pt.includes.emplace_back(ip, false); + } + } else if (p == "-I" && i + 1 < params.size()) { + std::filesystem::path ip{params[++i]}; + if (!ip.is_absolute()) { + ip = (configure_dir / ip).lexically_normal(); + } + if (!std::ranges::contains(pt.includes, std::pair{ip, false})) { + pt.includes.emplace_back(ip, false); + } + } else if (p == "-isystem" && i + 1 < params.size()) { + std::filesystem::path ip{params[++i]}; + if (!ip.is_absolute()) { + ip = (configure_dir / ip).lexically_normal(); + } + if (!std::ranges::contains(pt.includes, std::pair{ip, true})) { + pt.includes.emplace_back(ip, true); + } + } else if (p.starts_with("-D") && p.size() > 2) { + const std::string def = p.substr(2); + if (!std::ranges::contains(pt.defines, def)) { + pt.defines.push_back(def); + } + } else if (p == "-D" && i + 1 < params.size()) { + const std::string def = params[++i]; + if (!std::ranges::contains(pt.defines, def)) { + pt.defines.push_back(def); + } + } else if (p == "-std=c++17" || p == "-std=gnu++17") { + pt.cxx_standard = CxxStandard::Cxx17; + } else if (p == "-std=c++20" || p == "-std=gnu++20") { + pt.cxx_standard = CxxStandard::Cxx20; + } else if (p == "-std=c++23" || p == "-std=gnu++23") { + pt.cxx_standard = CxxStandard::Cxx23; + } else if (p == "-std=c++26" || p == "-std=gnu++26") { + pt.cxx_standard = CxxStandard::Cxx26; + } else if (p == "-fPIC" || p == "-fpic" || + p == "-fdiagnostics-color=always" || p == "-pipe" || + p == "-D_FILE_OFFSET_BITS=64") { + continue; + } else if (p == "-pthread") { + if (!std::ranges::contains(pt.compile_options, p)) { + pt.compile_options.push_back(p); + } + if (!std::ranges::contains(pt.link_options, p)) { + pt.link_options.push_back(p); + } + } else if (!p.empty() && p[0] == '-') { + if (!std::ranges::contains(pt.compile_options, p)) { + pt.compile_options.push_back(p); + } + } + } + } + } + } + + out.audit.supported_targets.push_back(pt.name); + out.target_order.push_back(pt.id); + out.targets_by_id[pt.id] = std::move(pt); + } + + // Recover internal target link edges cleanly from Meson's configured `build.ninja` + // (`build : cpp_LINKER ... | ` + `LINK_ARGS = ...`). + if (auto ninja_text = Void::FileSystem::read_file(configure_dir / "build.ninja"); ninja_text) { + std::string cur_target_id; + std::size_t pos = 0; + while (pos < ninja_text->size()) { + const auto nl = ninja_text->find('\n', pos); + std::string_view line = std::string_view{*ninja_text}.substr( + pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + pos = (nl == std::string_view::npos) ? ninja_text->size() : (nl + 1); + + if (line.starts_with("build ")) { + cur_target_id.clear(); + const auto colon = line.find(':'); + if (colon != std::string_view::npos) { + const auto outs_part = line.substr(6, colon - 6); + for (const auto &tok : split_shell_tokens(outs_part)) { + if (const auto ait = artifact_to_id.find(tok); + ait != artifact_to_id.end()) { + cur_target_id = ait->second; + break; + } + } + if (!cur_target_id.empty()) { + auto &pt = out.targets_by_id.at(cur_target_id); + const auto rhs = line.substr(colon + 1); + for (const auto &tok : split_shell_tokens(rhs)) { + if (const auto ait = artifact_to_id.find(tok); + ait != artifact_to_id.end() && ait->second != cur_target_id) { + if (!std::ranges::contains(pt.dep_ids, ait->second)) { + pt.dep_ids.push_back(ait->second); + } + } + } + } + } + } else if (!cur_target_id.empty() && line.starts_with(" LINK_ARGS = ")) { + auto &pt = out.targets_by_id.at(cur_target_id); + const auto args_part = line.substr(13); + for (const auto &tok : split_shell_tokens(args_part)) { + if (tok.empty() || tok == "-Wl,--as-needed" || tok == "-Wl,--no-undefined" || + tok == "-Wl,--start-group" || tok == "-Wl,--end-group" || + tok == "-Wl,--allow-shlib-undefined" || tok.starts_with("-Wl,-rpath") || + tok.starts_with("-Wl,-soname") || tok == "-shared" || tok == "-fPIC") { + continue; + } + if (is_safe_system_link_flag(tok)) { + if (!std::ranges::contains(pt.link_options, tok)) { + pt.link_options.push_back(tok); + } + } else if (const auto ait = artifact_to_id.find(tok); + ait != artifact_to_id.end()) { + if (ait->second != cur_target_id && + !std::ranges::contains(pt.dep_ids, ait->second)) { + pt.dep_ids.push_back(ait->second); + } + } else if (tok.ends_with(".a") || tok.ends_with(".so") || + tok.starts_with("-l")) { + add_unsupported( + pt.name, "unsupported_link_fragment", + std::format("Meson target '{}' has untranslated link argument '{}'", + pt.name, tok)); + } + } + } else if (line.empty()) { + cur_target_id.clear(); + } + } + } + + if (out.audit.is_supported()) { + out.audit.summary = std::format("all {} Meson target(s) fit the bounded native subset", + out.audit.supported_targets.size()); + } else { + out.audit.summary = std::format("{} unsupported construct(s) detected across Meson project", + out.audit.unsupported.size()); + } + return out; +} + +} // namespace + +Void::Result::Result +configure_meson_for_translation(const ProviderRequest &request, + const std::filesystem::path &configure_dir, std::stop_token stop) { + auto meson_bin = Platform::resolve_executable("meson"); + if (!meson_bin) { + return std::unexpected{make_error(Void::System::SystemErrorCode::not_found, + "Meson translation requires 'meson' in PATH")}; + } + + std::error_code ec; + std::filesystem::remove_all(configure_dir, ec); + std::filesystem::create_directories(configure_dir.parent_path(), ec); + + Void::Log::info("Translate", "Configuring Meson dependency '{}' for native graph audit...", + request.dependency.name); + + Platform::ProcessRequest req; + req.executable = *meson_bin; + req.arguments = {"setup", configure_dir.string(), request.source.source_dir.string()}; + const std::string btype = + (request.profile.name == "release" || request.profile.name == "Release") ? "release" + : "debug"; + req.arguments.push_back("-Dbuildtype=" + btype); + for (const auto &[k, v] : request.dependency.options) { + req.arguments.push_back("-D" + k + "=" + meson_option_value(v)); + } + req.environment.set_vars["CXX"] = request.toolchain.cxx_compiler.string(); + req.timeout = std::chrono::seconds{180}; + auto proc = Platform::run_supervised(req, stop); + if (!proc || !proc->succeeded()) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("Meson setup failed for '{}':\n{}", request.dependency.name, + proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))}; + } + return configure_dir / "meson-info"; +} + +Void::Result::Result +audit_meson_introspection(const std::filesystem::path &configure_dir) { + auto loaded = load_and_audit_meson(configure_dir); + if (!loaded) { + return std::unexpected{loaded.error()}; + } + return std::move(loaded->audit); +} + +Void::Result::Result translate_meson_to_native_graph( + const ProviderRequest &request, const std::filesystem::path &configure_dir, + const std::filesystem::path &native_build_root, const Snapshot::InputSnapshot *snapshot) { + auto loaded = load_and_audit_meson(configure_dir); + if (!loaded) { + return std::unexpected{loaded.error()}; + } + if (!loaded->audit.is_supported()) { + return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported, + format_unsupported_diagnostics(loaded->audit))}; + } + + Graph::ProjectDescription desc; + desc.profile = request.profile; + desc.profile.compile_options.clear(); + desc.profile.defines.clear(); + + for (const auto &tid : loaded->target_order) { + const auto &pt = loaded->targets_by_id.at(tid); + TargetRecord tr; + tr.name = pt.name; + if (pt.type == "static library") { + tr.kind = TargetKind::StaticLibrary; + } else if (pt.type == "shared library") { + tr.kind = TargetKind::SharedLibrary; + } else { + tr.kind = TargetKind::Executable; + } + tr.cxx_standard = pt.cxx_standard; + + for (const auto &src : pt.sources) { + tr.sources.push_back(SourceRecord{SourceKind::File, src.string()}); + } + for (const auto &[inc, is_sys] : pt.includes) { + tr.include_directories.push_back( + IncludeDirectory{inc.string(), Visibility::Public, is_sys}); + } + for (const auto &def : pt.defines) { + tr.defines.push_back(ScopedOption{def, Visibility::Public}); + } + for (const auto &opt : pt.compile_options) { + tr.compile_options.push_back(opt); + tr.scoped_compile_options.push_back(ScopedOption{opt, Visibility::Private}); + } + for (const auto &lo : pt.link_options) { + tr.link_options.push_back(ScopedOption{lo, Visibility::Public}); + } + for (const auto &dep_id : pt.dep_ids) { + const auto &dep_target = loaded->targets_by_id.at(dep_id); + tr.links.push_back( + LinkRecord{LinkKind::Local, dep_target.name, {}, Visibility::Public}); + } + desc.targets.push_back(std::move(tr)); + } + + Graph::GraphLowerOptions gopts{ + request.source.source_dir, native_build_root, snapshot, {}, 32768}; + auto graph = Graph::lower_project_graph(desc, request.toolchain, gopts); + if (!graph) { + return std::unexpected{graph.error()}; + } + + TranslatedCMakeGraph result; + result.audit = std::move(loaded->audit); + + std::map> summary_by_name; + for (const auto &s : graph->targets) { + summary_by_name[s.name] = &s; + } + + std::error_code ec; + for (const auto &tid : loaded->target_order) { + const auto &pt = loaded->targets_by_id.at(tid); + const auto sit = summary_by_name.find(pt.name); + if (sit == summary_by_name.end()) { + continue; + } + Graph::ImportedTargetInterface iface; + iface.dependency_name = request.dependency.name; + iface.target_name = pt.name; + iface.include_dirs = pt.includes; + if (std::filesystem::is_directory(request.source.source_dir / "include", ec)) { + const auto inc = (request.source.source_dir / "include").lexically_normal(); + if (!std::ranges::contains(iface.include_dirs, std::pair{inc, false})) { + iface.include_dirs.emplace_back(inc, false); + } + } + iface.defines = pt.defines; + iface.link_options = pt.link_options; + + if (!sit->second->primary_outputs.empty()) { + const auto &primary = sit->second->primary_outputs.front(); + if (pt.type == "static library") { + iface.static_libraries.push_back(primary); + } else if (pt.type == "shared library") { + iface.shared_libraries.push_back(primary); + iface.runtime_files.push_back(primary); + } + } + result.exported_targets[pt.name] = iface; + result.exported_targets[request.dependency.name + "::" + pt.name] = std::move(iface); + } + + result.graph = std::move(*graph); + return result; +} + +Void::Result::Result +resolve_meson_with_translation(const ProviderRequest &request, State::StateStore &state, + TranslationPolicy policy, std::stop_token stop) { + if (request.dependency.builder != "meson") { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("resolve_meson_with_translation requires builder='meson', got '{}'", + request.dependency.builder))}; + } + + const auto sw = Void::Time::Stopwatch::started(); + const std::string input_hash = compute_provider_input_hash(request); + const auto slot_dir = + request.provider_build_root / + ("translate_meson_" + request.dependency.name + "_" + input_hash.substr(0, 16)); + const auto cfg_dir = slot_dir / "meson-setup"; + const auto native_build_root = slot_dir / "native-build"; + + auto info_dir = configure_meson_for_translation(request, cfg_dir, stop); + if (!info_dir) { + return std::unexpected{info_dir.error()}; + } + + auto audit = audit_meson_introspection(cfg_dir); + if (!audit) { + return std::unexpected{audit.error()}; + } + + if (!audit->is_supported()) { + if (policy == TranslationPolicy::RequireNative) { + return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported, + format_unsupported_diagnostics(*audit))}; + } + Void::Log::warn("Translate", + "Meson dependency '{}' has unsupported constructs ({}); falling back to " + "foreign Meson provider", + request.dependency.name, audit->summary); + auto fallback = resolve_foreign_provider(request, stop); + if (!fallback) { + return std::unexpected{fallback.error()}; + } + TranslationResolution res; + res.executed_natively = false; + res.audit = std::move(*audit); + res.exported = std::move(*fallback); + return res; + } + + auto translated = translate_meson_to_native_graph(request, cfg_dir, native_build_root, nullptr); + if (!translated) { + return std::unexpected{translated.error()}; + } + + Void::Log::info("Translate", + "Executing Meson dependency '{}' natively ({} actions, 0 meson compile)...", + request.dependency.name, translated->graph.actions.size()); + + auto exec = Execution::execute_graph(translated->graph, state, {}, stop); + if (!exec) { + return std::unexpected{exec.error()}; + } + if (!exec->succeeded) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("native execution of translated Meson dependency '{}' failed: {}", + request.dependency.name, exec->diagnostic))}; + } + + Void::Log::info("Translate", + "Native Meson translation '{}' finished in {}ms ({} executed, {} cached)", + request.dependency.name, sw.elapsed_as().count(), + exec->executed_count, exec->cached_count); + + ProviderExport exp; + exp.dependency_name = request.dependency.name; + exp.builder = "meson-native-translated"; + exp.input_identity_hash = input_hash; + exp.from_cache = (exec->executed_count == 0); + exp.targets = std::move(translated->exported_targets); + + TranslationResolution res; + res.executed_natively = true; + res.audit = std::move(translated->audit); + res.exported = std::move(exp); + res.native_execution = std::move(*exec); + return res; +} + +Void::Result::Result +resolve_foreign_with_translation(const ProviderRequest &request, State::StateStore &state, + TranslationPolicy policy, std::stop_token stop) { + if (request.dependency.builder == "cmake") { + return resolve_cmake_with_translation(request, state, policy, stop); + } + if (request.dependency.builder == "meson") { + return resolve_meson_with_translation(request, state, policy, stop); + } + auto fb = resolve_foreign_provider(request, stop); + if (!fb) { + return std::unexpected{fb.error()}; + } + TranslationResolution res; + res.executed_natively = false; + res.audit.status = TranslationStatus::Unsupported; + res.audit.summary = "builder '" + request.dependency.builder + "' uses foreign provider"; + res.exported = std::move(*fb); + return res; +} + } // namespace Void::Build::Provider diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index 577cf0a..2fe48bd 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -22,8 +22,13 @@ check_process(0 "^vbs ${VBS_VERSION}\n$" "" -V) check_process(2 "" "unknown option: --invalid" --version --invalid) check_process(2 "" "--version cannot be combined with subcommands" --version build) check_process(2 "" "unknown subcommand: invalid" invalid) -check_process(0 "Usage: vbs build .*--profile.*\\(repeatable\\)" "" build --help) +check_process(0 "Usage: vbs build .*--native-foreign.*--profile.*\\(repeatable\\)" "" build --help) check_process(0 "Usage: vbs test " "" test --help) +check_process(0 "Usage: vbs init " "" init --help) +check_process(0 "Usage: vbs clean " "" clean --help) +check_process(0 "Usage: vbs doctor " "" doctor --help) +check_process(0 "Usage: vbs graph " "" graph --help) +check_process(2 "" "unsupported --format" graph --format xml) check_process(2 "" "multi-profile build requires --editor-profile" build --profile debug --profile release) check_process(2 "" "must be one of the requested profiles" build --profile debug --profile release --editor-profile custom) check_process(0 "Usage: vbs compdb .*Commands:.*use.*show.*export.*watch" "" compdb --help) @@ -46,4 +51,4 @@ execute_process(COMMAND "${VBS_REGISTRY}" --help if(NOT "${reg_code}" STREQUAL "0" OR NOT reg_out MATCHES "Usage: vbs-registry") message(FATAL_ERROR "vbs-registry --help failed: code=${reg_code}\nstdout=[${reg_out}]\nstderr=[${reg_err}]") endif() -message(STATUS "27 native CLI and auto-generated Argparse help contracts verified") +message(STATUS "32 native CLI and auto-generated Argparse help contracts verified") diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index ecd1c9e..0b096f9 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -1214,3 +1214,188 @@ target_include_directories(p20_genlib PUBLIC "${CMAKE_CURRENT_BINARY_DIR}") Void::Testing::expect(fb_res->exported.targets.contains("p20_gen::p20_genlib")); } } + +// === Plan 20 Slice 2A: Bounded native Meson graph translation + unsupported custom_target fallback +// === +Void::Testing::Test plan20_bounded_meson_translation_equivalence_and_fallback() { + if (!Platform::resolve_executable("meson").has_value()) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_plan20_meson_"}; + auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(), + Toolchain::host_architecture_name()); + auto tc = Toolchain::discover_and_probe(ctx, tmp / "probes"); + Void::Testing::expect(tc.has_value()); + if (!tc) + return; + + auto state = State::StateStore::open(tmp / "state"); + Void::Testing::expect(state.has_value()); + if (!state) + return; + + // 1. Supported C++ Meson project (static library + executable): configure ONLY (`meson setup`, + // zero `meson compile`!), audit, translate natively, execute via VBS, verify stdout + header + // mutation! + const auto m_src = tmp / "meson_supported"; + write_file(m_src / "meson.build", R"meson( +project('p20m', 'cpp', default_options: ['cpp_std=c++20']) +inc = include_directories('include') +lib = static_library('mcore', 'src/core.cpp', include_directories: inc, cpp_args: ['-DM_DELTA=5']) +executable('mapp', 'src/main.cpp', include_directories: inc, link_with: lib) +)meson"); + write_file(m_src / "include" / "mcore.hpp", + "#pragma once\ninline constexpr int kMBase = 37;\nint m_answer();\n"); + write_file(m_src / "src" / "core.cpp", + "#include \"mcore.hpp\"\nint m_answer() { return kMBase + M_DELTA; }\n"); + write_file(m_src / "src" / "main.cpp", + "#include \"mcore.hpp\"\n#include \n" + "int main() { std::cout << m_answer() << '\\n'; return 0; }\n"); + + DependencyRecord mdep; + mdep.name = "p20m"; + mdep.source_kind = DependencySourceKind::Path; + mdep.location = m_src.string(); + mdep.builder = "meson"; + + auto mat = Package::materialize_dependency_source(mdep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(mat.has_value()); + if (!mat) + return; + + Provider::ProviderRequest req{ + mdep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto native_res = Provider::resolve_foreign_with_translation( + req, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect_eq(native_res ? std::string{} : native_res.error().message(), + std::string{}); + Void::Testing::expect(native_res.has_value()); + if (!native_res) + return; + Void::Testing::expect(native_res->executed_natively); + Void::Testing::expect(native_res->audit.is_supported()); + Void::Testing::expect(native_res->exported.targets.contains("p20m::mcore")); + + const auto hash = Provider::compute_provider_input_hash(req); + const auto slot_dir = tmp / "prov" / ("translate_meson_p20m_" + hash.substr(0, 16)); + const auto native_exe = + slot_dir / "native-build" / "profiles" / "debug" / "out" / "bin" / "mapp"; + Void::Testing::expect(std::filesystem::exists(native_exe)); + + Platform::ProcessRequest run_req; + run_req.executable = native_exe; + auto run_out = Platform::run_supervised(run_req); + Void::Testing::expect(run_out.has_value() && run_out->succeeded()); + if (run_out) { + Void::Testing::expect_eq(run_out->stdout_data, std::string{"42\n"}); + } + + // 2. Unsupported Meson `custom_target`: RequireNative MUST fail cleanly; FallbackToForeignBuild + // MUST build via foreign Meson provider! + const auto u_src = tmp / "meson_custom"; + write_file(u_src / "meson.build", R"meson( +project('p20m_custom', 'cpp') +gen = custom_target('gen_hdr', + output: 'gen_num.hpp', + command: ['/bin/sh', '-c', 'printf "#define M_GEN_NUM 88\n" > "$1"', '--', '@OUTPUT@']) +static_library('mgenlib', ['src/gen.cpp', gen]) +)meson"); + write_file(u_src / "src" / "gen.cpp", + "#include \"gen_num.hpp\"\nint m_gen_fn() { return M_GEN_NUM; }\n"); + + DependencyRecord udep; + udep.name = "p20m_custom"; + udep.source_kind = DependencySourceKind::Path; + udep.location = u_src.string(); + udep.builder = "meson"; + auto umat = + Package::materialize_dependency_source(udep, {tmp / "cache", tmp.path(), false, {}}); + Void::Testing::expect(umat.has_value()); + if (!umat) + return; + + Provider::ProviderRequest ureq{ + udep, *umat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}}; + auto strict = Provider::resolve_foreign_with_translation( + ureq, *state, Provider::TranslationPolicy::RequireNative); + Void::Testing::expect(!strict.has_value()); + + auto fallback = Provider::resolve_foreign_with_translation( + ureq, *state, Provider::TranslationPolicy::FallbackToForeignBuild); + Void::Testing::expect_eq(fallback ? std::string{} : fallback.error().message(), std::string{}); + Void::Testing::expect(fallback.has_value()); + if (fallback) { + Void::Testing::expect(!fallback->executed_natively); + Void::Testing::expect(!fallback->audit.is_supported()); + Void::Testing::expect(fallback->exported.targets.contains("p20m_custom::mgenlib")); + } +} + +// === Wave 8 DX CLI: vbs init -> vbs test -> vbs graph -> vbs doctor -> vbs clean === +Void::Testing::Test cli_init_graph_clean_doctor_end_to_end() { + const auto vbs_bin = std::filesystem::path{Bootstrap::binary_dir} / "bin" / "vbs"; + if (!std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_dx_"}; + const auto proj = tmp / "hello_vbs"; + const auto bdir = tmp / "hello_build"; + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{120}; + return Platform::run_supervised(req); + }; + + // 1. `vbs init` scaffolds a ready-to-build-and-test C++26 project. + auto r_init = run_vbs({"init", "--dir", proj.string(), "--name", "hello_vbs"}); + Void::Testing::expect(r_init.has_value() && r_init->succeeded()); + Void::Testing::expect(std::filesystem::exists(proj / "build.cpp")); + Void::Testing::expect(std::filesystem::exists(proj / "src" / "main.cpp")); + Void::Testing::expect(std::filesystem::exists(proj / "tests" / "test_main.cpp")); + + // 2. `vbs test` builds & passes the freshly scaffolded project out of the box! + auto r_test = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string()}); + Void::Testing::expect(r_test.has_value() && r_test->succeeded()); + if (r_test) { + Void::Testing::expect(r_test->stdout_data.find("PASSED 'hello_vbs_tests'") != + std::string::npos); + } + + // 3. `vbs graph --format dot` & `--format json` emit valid target dependency graphs. + auto r_dot = run_vbs( + {"graph", "--project", proj.string(), "--build-dir", bdir.string(), "--format", "dot"}); + Void::Testing::expect(r_dot.has_value() && r_dot->succeeded()); + if (r_dot) { + Void::Testing::expect(r_dot->stdout_data.find("digraph vbs_targets") != std::string::npos); + Void::Testing::expect(r_dot->stdout_data.find("\"hello_vbs\" -> \"hello_vbs_lib\"") != + std::string::npos); + } + auto r_json = run_vbs( + {"graph", "--project", proj.string(), "--build-dir", bdir.string(), "--format", "json"}); + Void::Testing::expect(r_json.has_value() && r_json->succeeded()); + if (r_json) { + auto parsed = Void::Json::Strict::parse(r_json->stdout_data); + Void::Testing::expect(parsed.has_value()); + } + + // 4. `vbs doctor` succeeds and reports GCC + Void::Crypto + Void::Archive. + auto r_doc = run_vbs({"doctor"}); + Void::Testing::expect(r_doc.has_value() && r_doc->succeeded()); + if (r_doc) { + Void::Testing::expect(r_doc->stdout_data.find("Void::Crypto") != std::string::npos); + Void::Testing::expect(r_doc->stdout_data.find("GCC probe:") != std::string::npos); + } + + // 5. `vbs clean` removes profile outputs while preserving .vbs/state; `--all` removes all. + auto r_clean = run_vbs({"clean", "--build-dir", bdir.string()}); + Void::Testing::expect(r_clean.has_value() && r_clean->succeeded()); + Void::Testing::expect(!std::filesystem::exists(bdir / "profiles")); + Void::Testing::expect(std::filesystem::exists(bdir / ".vbs")); + + auto r_clean_all = run_vbs({"clean", "--build-dir", bdir.string(), "--all"}); + Void::Testing::expect(r_clean_all.has_value() && r_clean_all->succeeded()); + Void::Testing::expect(!std::filesystem::exists(bdir)); +}