feat: add Plan 20 Slice 1 CMake native translation, self-test smoke target, VL-009 VOID_TEST check, and warm-cache hardening
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 5s

This commit is contained in:
faumaray committed 2026-11-27 05:38:18 +03:00
1 parent 363fb8200e
commit d3d2666965
19 files changed
+1466 -65

No files matched your search

+1
View File
@@ -53,6 +53,7 @@ add_library(VoidBuild_Core STATIC
src/Package/Fetch.cpp
src/Package/RegistryClient.cpp
src/Provider/Provider.cpp
src/Provider/Translator.cpp
src/Install/Installer.cpp
src/Bridge/CMakeBridge.cpp
src/Modules/ModuleScanner.cpp
+6 -5
View File
@@ -9,12 +9,13 @@ profile definitions live in ordinary `build.cpp`, `build.profiles.cpp`, and
**Implemented scope (Plans 01–19):**
- **Declaration SDK (`Void::Build`, `<Void/Build.hpp>`)**: `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 `build.cpp`**: Root [build.cpp](build.cpp) declares the full `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`) so `vbs build` compiles and links `VoidBuildSystem` itself end-to-end.
- **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).
- **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 — Later native foreign execution and platform ports](docs/roadmap/20-future-translation-platforms.md) (native foreign graph translation and Windows/macOS ports) remains planned architectural scope.
- **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.
Start with the [twenty roadmap plans](docs/roadmap/README.md),
[architecture](docs/roadmap/ARCHITECTURE.md),
@@ -52,12 +53,12 @@ dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary
```
### Self-building VoidBuildSystem with `vbs`
### Self-building and self-testing VoidBuildSystem with `vbs`
Once the bootstrap `vbs` binary is built, `VoidBuildSystem` builds itself directly from root [build.cpp](build.cpp) with live progress logs (`-v`/`--verbose` for debug detail, `-q`/`--quiet` for warnings/errors only):
Once the bootstrap `vbs` binary is built, `VoidBuildSystem` builds and smoke-tests itself directly from root [build.cpp](build.cpp) with live progress logs (`-v`/`--verbose` for debug detail, `-q`/`--quiet` for warnings/errors only):
```sh
dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self
dev cpp-gcc -c build/dev/bin/vbs test --build-dir build/vbs-self
build/vbs-self/profiles/debug/out/bin/vbs --version
build/vbs-self/profiles/debug/out/bin/vbs --help
```
+7
View File
@@ -44,6 +44,7 @@ void build(Void::Build::Project &project) {
"src/Package/Fetch.cpp",
"src/Package/RegistryClient.cpp",
"src/Provider/Provider.cpp",
"src/Provider/Translator.cpp",
"src/Install/Installer.cpp",
"src/Bridge/CMakeBridge.cpp",
"src/Modules/ModuleScanner.cpp",
@@ -115,4 +116,10 @@ void build(Void::Build::Project &project) {
.link(registry_lib)
.install("bin");
BuildSupport::compiler_warnings(registry_cli, ctx);
auto smoke_test = project.test("vbs_self_smoke");
smoke_test.cxx_standard(Void::Build::CxxStandard::Cxx26)
.sources({"tests/SelfBuildSmoke.cpp"})
.link(core);
BuildSupport::compiler_warnings(smoke_test, ctx);
}
+7 -2
View File
@@ -2,7 +2,7 @@
Updated: 2026-11-27
Branch: main
Stage: VERIFIED — Full v1 implementation (Plans 01–19) + VoidLibrary `VL-001`..`VL-013` adoption + self-building `vbs build` + live `Void::Log` progress + 100% auto-generated `Void::Argparse` CLI complete
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
## Completed delivery waves
@@ -33,10 +33,15 @@ Stage: VERIFIED — Full v1 implementation (Plans 01–19) + VoidLibrary `VL-001
- Eliminated all custom help text and manual `--help`/subcommand/repeatable-flag parsing across `src/Main.cpp`, `src/Describe.cpp`, `registry/service/Main.cpp`, and `benchmarks/EngineBenchmarks.cpp` — 100% auto-generated via `Void::Argparse::Parser`.
- Upgraded root `build.cpp` to declare the complete `VoidBuildSystem` (`VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`, `vbs`, `VoidBuildRegistry`, `vbs-registry`), fixed snapshot root discovery (`collect_snapshot_inputs`), fixed snapshot remapping of external/build-dir dependency includes in `Graph.cpp`, fixed CMake File API provider `Void::*` alias & header-only `INTERNAL_DEPS` export + transitive link ordering in `Provider.cpp`, and verified real Stage 1 + Stage 2 self-builds of `VoidBuildSystem` via `vbs build`!
- Wired a live thread-safe `Void::Log` console sink in `src/Main.cpp` (`--verbose`/`-v`, `--quiet`/`-q`) logging every build phase (`Config`, `Toolchain`, `Eval`, `Deps`, `Fetch`, `Provider`, `Snapshot`, `Graph`, per-action `[seq/total] Compile/Archive/Link/Action ...` progress, and `Test`) with elapsed timings.
- **Wave 7 (Plan 20 Slice 1 Bounded Native CMake Translation, Self-Testing `build.cpp`, `VL-009` `VOID_TEST`, & Warm Cache Hardening)**:
- Implemented Plan 20 Slice 1 in `include/Void/Build/Provider/Translator.hpp` and `src/Provider/Translator.cpp`: strict CMake File API `codemodel-v2` completeness audit (`audit_cmake_codemodel`), bounded C++ native `Graph::BuildGraph` translation (`translate_cmake_to_native_graph`, executing via VBS's toolchain driver/CAS/depfiles with zero `cmake --build`), and explicit `TranslationPolicy::RequireNative` vs `TranslationPolicy::FallbackToForeignBuild` resolution (`resolve_cmake_with_translation`), verified with equivalence, restored-mtime mutation, and unsupported `add_custom_command`/`UTILITY` fallback tests in `tests/FullV1Tests.cpp`.
- Added `tests/SelfBuildSmoke.cpp` (`project.test("vbs_self_smoke")`) to root `build.cpp` so both `vbs build` and `vbs test` build and execute a self-test directly on `VoidBuildSystem`.
- 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`.
## Remaining future scope
- **Plan 20 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports remain planned architectural design 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.
## Environment notes & upstream boundaries
+3 -2
View File
@@ -1,7 +1,7 @@
# Task graph and ownership
Updated: 2026-11-27
Base HEAD: `ab64147`
Base HEAD: `363fb82`
| Wave | Scope | Status | Primary Deliverables |
| --- | --- | --- | --- |
@@ -13,4 +13,5 @@ Base HEAD: `ab64147`
| Wave 4 (Plans 08, 16–17, 19) | P1689 modules/header units/unity, `vbs-registry` HTTP/1.1 service + web UI, full `vbs` CLI, benchmarks, CI template | COMPLETE & VERIFIED | `Modules/`, `registry/`, `src/Main.cpp`, `benchmarks/`, `.github/workflows/ci.yml`, `tests/RegistryTests.cpp` |
| 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 |
| Future (Plan 20) | Native foreign build translation & Windows/macOS ports | PLANNED (unimplemented) | [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) |
| 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) |
+21 -22
View File
@@ -29,51 +29,49 @@ dev cpp-gcc -c clang-format --dry-run --Werror \
registry/include/Void/Build/Registry/*.hpp registry/service/*.cpp \
benchmarks/*.cpp tests/*.cpp
```
- Exit status: `0` (all 67 owned C++ headers/sources pass with zero formatting diffs).
- Exit status: `0` (all 70 owned C++ headers/sources pass with zero formatting diffs).
## CTest Suite Results (`dev cpp-gcc`)
```sh
dev cpp-gcc -c ctest --test-dir build/dev --output-on-failure
```
- Exit status: `0` — **8 / 8 passed (100%) in 85.66 sec**:
- Exit status: `0` — **8 / 8 passed (100%) in 103.96 sec**:
| # | CTest Name | Scope Verified | Result | Time |
| --- | --- | --- | --- | --- |
| 1 | `vbs_sdk_tests` | 17 tests (`SdkDeclarations` 14 + `ExampleContexts` 3 for 6-target self-building `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` `reflink_copy_file`/`FileLock`/`set_canonical_mtime`), CAS recovery/GC, end-to-end native frontend + deterministic build | Passed | 11.34s |
| 3 | `vbs_v1_tests` | 8 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 & traversal/symlink/duplicate 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) | Passed | 11.13s |
| 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` | 3 tests: basename-collision-safe `vbs gen-tests`, strict non-CMake native `VoidLibrary` (including `Crypto` + `Archive`) + `VoidBuildSdk` + Stage 2, and full Stage 0 -> Stage 1 native `VbsSelfHostRecipe` (`stage1/bin/vbs`, zero CMake) -> Stage 2 `stage1/bin/vbs test` with trapped `cmake` on `PATH` | Passed | 59.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.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 |
| 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 |
| 8 | `vbs_description_contract` | Four runtime profile/compiler contexts (`debug`/`release` x `gcc`/`clang` for 6-target `build.cpp`), auto-generated `vbs_describe --help`, and five error contracts verified | Passed | 0.03s |
| 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 of VoidBuildSystem (`vbs build`)
## Real Self-Build & Self-Test of VoidBuildSystem (`vbs test`)
### Stage 1: Bootstrap `vbs` builds complete `VoidBuildSystem` from root `build.cpp`
### Stage 1: Bootstrap `vbs` builds and smoke-tests complete `VoidBuildSystem` from root `build.cpp`
```sh
VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \
dev cpp-gcc -c build/dev/bin/vbs build --build-dir build/vbs-self --jobs 4
dev cpp-gcc -c build/dev/bin/vbs test --build-dir build/vbs-self --jobs 4
```
- Exit status: `0` — **`vbs: [debug] built (36 executed, 0 cached)`** in `38.79s`.
- Live progress logs verified cleanly across all phases: `[Config]`, `[Toolchain]`, `[Eval]` (`6 target(s), 1 dependenc(ies)`), `[Deps]`, `[Fetch]`, `[Provider]` (`Imported 100 target(s) from 'VoidLibrary'`), `[Snapshot]` (`70 file(s)`), `[Graph]` (`36 action(s)`), and per-action `[ 1/36] Action GenerateBootstrapConfig` .. `[35/36] Link build/vbs-self/profiles/debug/out/bin/vbs` & `[36/36] Link build/vbs-self/profiles/debug/out/bin/vbs-registry`.
- Exit status: `0` — **`vbs: [debug] built (39 executed, 0 cached)`** in `42.73s` -> **`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 cached build & auto-generated CLI
### Stage 2: Self-built `vbs` verifies warm cached build & self-test
```sh
VBS_VOID_SOURCE_DIR=/home/faumaray/Projects/VoidBuildSystem/build/voidlibrary-pinned \
dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs build --build-dir build/vbs-self --jobs 4
build/vbs-self/profiles/debug/out/bin/vbs --version
build/vbs-self/profiles/debug/out/bin/vbs --help
dev cpp-gcc -c build/vbs-self/profiles/debug/out/bin/vbs test --build-dir build/vbs-self --jobs 4
```
- Exit status: `0` — **`vbs: [debug] built (0 executed, 36 cached)`**, `vbs 0.1.0`, and full auto-generated `Void::Argparse::Parser` root help output (`Usage: vbs [--version] [--verbose] [--quiet] <command>`).
- 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)`**.
## 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 745.2ms` (`clang23_target_toolchain_and_p1689_module_scan`).
- Exit status: `0` — `1 tests: 1 ✔ in 876.7ms` (`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`)
@@ -83,13 +81,14 @@ 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":17,"cold_build_ms":350,"cold_executed":17,"warm_noop_ms":16,"warm_executed":0,"warm_cached":17}
{"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}
```
(`warm_noop_ms` improved 4x from `16ms` to `4ms`.)
## Limits and Unrun Checks
1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs build` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`.
1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs test` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`.
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 ([20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Native foreign graph translation and non-Linux OS ports (Windows/macOS) remain unimplemented planned scope.
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.
@@ -1,8 +1,6 @@
# 20 — Later native foreign execution and platform ports
Implementation status: planned, except the initial bootstrap when marked verified in
[STATE](../agent-workflow/STATE.md). This document is an implementation contract,
not a report that the capability exists.
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).
## Requirements and ownership
+3 -3
View File
@@ -1,7 +1,7 @@
# Roadmap and delivery graph
Plans **01–19** are implemented and verified in the v1 native codebase and CTest
suites; **Plan 20** remains future architectural design scope. For implemented
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
commands, targets, and workflow usage, see the [project README](../../README.md) and
[verification record](../agent-workflow/VERIFICATION.md).
@@ -31,7 +31,7 @@ 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) | Planned (future scope) | Future foreign graph translation and Windows/macOS ports |
| [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 |
## Dependency graph
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Build/Execution/Scheduler.hpp>
#include <Void/Build/Graph/Graph.hpp>
#include <Void/Build/Provider/Provider.hpp>
#include <Void/Build/Snapshot/Snapshot.hpp>
#include <Void/Build/State/StateStore.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <filesystem>
#include <map>
#include <optional>
#include <stop_token>
#include <string>
#include <vector>
namespace Void::Build::Provider {
enum class TranslationPolicy {
RequireNative,
FallbackToForeignBuild,
};
enum class TranslationStatus {
Supported,
Unsupported,
};
struct UnsupportedConstruct {
std::string target_name;
std::string construct_kind;
std::string detail;
};
struct TranslationAuditReport {
TranslationStatus status{TranslationStatus::Supported};
std::vector<std::string> supported_targets;
std::vector<UnsupportedConstruct> unsupported;
std::string summary;
[[nodiscard]] bool is_supported() const noexcept {
return status == TranslationStatus::Supported && unsupported.empty();
}
};
struct TranslatedCMakeGraph {
TranslationAuditReport audit;
Graph::BuildGraph graph;
std::map<std::string, Graph::ImportedTargetInterface, std::less<>> exported_targets;
};
struct TranslationResolution {
bool executed_natively{false};
TranslationAuditReport audit;
ProviderExport exported;
std::optional<Execution::ExecutionReport> native_execution;
};
// Configures CMake ONLY (writing File API codemodel-v2 query; never invokes `cmake --build`)
// and returns the configured File API reply directory.
[[nodiscard]] Void::Result::Result<std::filesystem::path, Void::Result::Error>
configure_cmake_for_translation(const ProviderRequest &request,
const std::filesystem::path &configure_dir,
std::stop_token stop = {});
// Audits a configured CMake File API codemodel against Plan 20's bounded native subset:
// C++ STATIC_LIBRARY / SHARED_LIBRARY / OBJECT_LIBRARY / EXECUTABLE targets without
// generated sources, custom UTILITY rules, foreign C++20 module fileSets, precompiled
// headers, non-C++ languages, or untracked link fragments. Any unsupported construct is
// reported explicitly and never silently dropped.
[[nodiscard]] Void::Result::Result<TranslationAuditReport, Void::Result::Error>
audit_cmake_codemodel(const std::filesystem::path &configure_dir);
// Translates an audited CMake codemodel into a native VBS BuildGraph whose actions execute
// through VBS's Toolchain driver, CAS StateStore, depfile tracking, and ProcessSupervisor.
[[nodiscard]] Void::Result::Result<TranslatedCMakeGraph, Void::Result::Error>
translate_cmake_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 1 resolver: configures CMake, audits completeness, and either
// executes the translated native BuildGraph via VBS Execution::execute_graph (without
// running `cmake --build`), fails with explicit unsupported-construct diagnostics
// (RequireNative), or delegates cleanly to the v1 foreign CMake provider
// (FallbackToForeignBuild).
[[nodiscard]] Void::Result::Result<TranslationResolution, Void::Result::Error>
resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore &state,
TranslationPolicy policy = TranslationPolicy::FallbackToForeignBuild,
std::stop_token stop = {});
} // namespace Void::Build::Provider
+4
View File
@@ -8,6 +8,7 @@
#include <cstdint>
#include <filesystem>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
@@ -120,6 +121,8 @@ class StateStore {
std::vector<GraphGenerationRecord> generations;
};
struct CacheState;
explicit StateStore(std::filesystem::path root);
[[nodiscard]] Void::Result::Result<DatabaseSnapshot, Void::Result::Error>
@@ -133,6 +136,7 @@ class StateStore {
std::filesystem::path leases_dir_;
std::filesystem::path db_file_;
std::filesystem::path lock_file_;
std::shared_ptr<CacheState> cache_;
};
} // namespace Void::Build::State
+1
View File
@@ -93,6 +93,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) {
"src/Package/Fetch.cpp",
"src/Package/RegistryClient.cpp",
"src/Provider/Provider.cpp",
"src/Provider/Translator.cpp",
"src/Install/Installer.cpp",
"src/Bridge/CMakeBridge.cpp",
"src/Modules/ModuleScanner.cpp",
+54 -13
View File
@@ -19,6 +19,7 @@
#include <queue>
#include <set>
#include <thread>
#include <unordered_map>
namespace Void::Build::Execution {
namespace {
@@ -28,7 +29,42 @@ Void::Result::Error make_error(std::string msg) {
std::move(msg));
}
std::string compute_effective_action_key(const Graph::ActionNode &action) {
// Run-scoped thread-safe SHA-256 memo table. Every path is hashed at most once per
// execute_graph() run across all worker threads, and invalidated immediately whenever an
// action actually executes and writes its declared outputs.
class RunDigestCache {
public:
[[nodiscard]] std::optional<std::string> hash_file(const std::filesystem::path &path) {
const std::string key = path.lexically_normal().string();
{
std::lock_guard lk{mu_};
if (const auto it = cache_.find(key); it != cache_.end()) {
return it->second;
}
}
auto d = Util::sha256_file_hex(path);
std::optional<std::string> val =
d ? std::optional<std::string>{std::move(*d)} : std::nullopt;
{
std::lock_guard lk{mu_};
cache_.insert_or_assign(key, val);
}
return val;
}
void invalidate(const std::filesystem::path &path) {
const std::string key = path.lexically_normal().string();
std::lock_guard lk{mu_};
cache_.erase(key);
}
private:
std::mutex mu_;
std::unordered_map<std::string, std::optional<std::string>> cache_;
};
std::string compute_effective_action_key(const Graph::ActionNode &action,
RunDigestCache &digest_cache) {
// Re-hash declared input file bytes at execution time (including generated upstream outputs!)
// so downstream compile/archive/link actions invalidate immediately when an upstream artifact
// changes.
@@ -36,7 +72,7 @@ std::string compute_effective_action_key(const Graph::ActionNode &action) {
hasher.update_length_prefixed(action.action_key);
for (const auto &in_path : action.declared_inputs) {
hasher.update_length_prefixed(in_path.string());
if (auto digest = Util::sha256_file_hex(in_path); digest) {
if (auto digest = digest_cache.hash_file(in_path); digest) {
hasher.update_length_prefixed(*digest);
} else {
hasher.update_length_prefixed("<missing>");
@@ -46,9 +82,10 @@ std::string compute_effective_action_key(const Graph::ActionNode &action) {
}
bool verify_discovered_inputs_unchanged(
const std::map<std::string, std::string, std::less<>> &discovered_inputs) {
const std::map<std::string, std::string, std::less<>> &discovered_inputs,
RunDigestCache &digest_cache) {
for (const auto &[path_str, expected_sha] : discovered_inputs) {
auto actual = Util::sha256_file_hex(std::filesystem::path{path_str});
auto actual = digest_cache.hash_file(std::filesystem::path{path_str});
if (!actual || *actual != expected_sha) {
return false;
}
@@ -57,13 +94,14 @@ bool verify_discovered_inputs_unchanged(
}
bool verify_outputs_match_record(const Graph::ActionNode &action,
const State::ActionSuccessRecord &record) {
const State::ActionSuccessRecord &record,
RunDigestCache &digest_cache) {
for (const auto &out_path : action.declared_outputs) {
const auto it = record.outputs.find(out_path.string());
if (it == record.outputs.end()) {
return false;
}
auto actual = Util::sha256_file_hex(out_path);
auto actual = digest_cache.hash_file(out_path);
if (!actual || *actual != it->second.sha256) {
return false;
}
@@ -73,7 +111,7 @@ bool verify_outputs_match_record(const Graph::ActionNode &action,
bool restore_outputs_from_cache(const Graph::ActionNode &action,
const State::ActionSuccessRecord &record,
const State::StateStore &state) {
const State::StateStore &state, RunDigestCache &digest_cache) {
for (const auto &out_path : action.declared_outputs) {
const auto it = record.outputs.find(out_path.string());
if (it == record.outputs.end()) {
@@ -83,6 +121,7 @@ bool restore_outputs_from_cache(const Graph::ActionNode &action,
if (!mat) {
return false;
}
digest_cache.invalidate(out_path);
}
return true;
}
@@ -269,6 +308,7 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
std::size_t completed_count = 0;
std::atomic<std::size_t> started_exec_count{0};
bool abort_scheduling = false;
RunDigestCache digest_cache;
auto action_label = [&](const Graph::ActionNode &act) -> std::string {
auto rel_name = [&](const std::filesystem::path &p) -> std::string {
@@ -325,16 +365,16 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
return res;
}
const std::string effective_key = compute_effective_action_key(act);
const std::string effective_key = compute_effective_action_key(act, digest_cache);
// 1. Cache lookup (ONLY when action is deterministic & cacheable!).
if (act.cacheable && !act.nondeterministic && options.use_cache) {
auto cached = state.lookup_action(effective_key);
if (cached && cached->has_value()) {
const auto &rec = **cached;
if (verify_discovered_inputs_unchanged(rec.discovered_inputs)) {
if (verify_outputs_match_record(act, rec) ||
restore_outputs_from_cache(act, rec, state)) {
if (verify_discovered_inputs_unchanged(rec.discovered_inputs, digest_cache)) {
if (verify_outputs_match_record(act, rec, digest_cache) ||
restore_outputs_from_cache(act, rec, state, digest_cache)) {
res.succeeded = true;
res.from_cache = true;
res.exit_code = 0;
@@ -422,8 +462,9 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
return res;
}
// 4. Validate ALL declared outputs exist after zero exit!
// 4. Validate ALL declared outputs exist after zero exit and drop stale memo entries!
for (const auto &out : act.declared_outputs) {
digest_cache.invalidate(out);
auto meta = Platform::stat_lstat(out);
if (!meta || !meta->exists || !meta->is_regular) {
res.error_message =
@@ -456,7 +497,7 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
act.id, dep_abs.string(), prod_it->second);
return res;
}
if (auto digest = Util::sha256_file_hex(dep_abs); digest) {
if (auto digest = digest_cache.hash_file(dep_abs); digest) {
discovered_inputs[dep_abs.string()] = std::move(*digest);
}
}
+856
View File
@@ -0,0 +1,856 @@
#include <Void/Build/Provider/Translator.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/Log/Log.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Stopwatch.hpp>
#include <algorithm>
#include <format>
#include <set>
#include <type_traits>
namespace Void::Build::Provider {
namespace {
using JsonVal = Void::Json::Strict::Value;
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) {
return Void::System::make_system_error(code, std::move(msg));
}
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &k) {
const auto it = obj.find(k);
return it == obj.end() ? nullptr : &it->second;
}
std::string get_str(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return {};
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? *s : std::string{};
}
bool get_bool(const JsonVal::Object &obj, const std::string &k, bool def = false) {
const auto *v = find_key(obj, k);
if (!v) {
return def;
}
const auto *b = std::get_if<bool>(&v->value);
return b ? *b : def;
}
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &k) {
const auto *v = find_key(obj, k);
if (!v) {
return std::nullopt;
}
const auto *i = std::get_if<std::int64_t>(&v->value);
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
}
std::optional<JsonVal> parse_json_file(const std::filesystem::path &path) {
auto text = Void::FileSystem::read_file(path);
if (!text) {
return std::nullopt;
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return std::nullopt;
}
return std::move(*parsed);
}
std::string cmake_option_value(const OptionValue &v) {
return std::visit(
[](const auto &inner) -> std::string {
using T = std::remove_cvref_t<decltype(inner)>;
if constexpr (std::same_as<T, std::string>) {
return inner;
} else if constexpr (std::same_as<T, bool>) {
return inner ? "ON" : "OFF";
} else {
return std::to_string(inner);
}
},
v.value);
}
std::vector<std::string> split_shell_tokens(std::string_view text) {
std::vector<std::string> tokens;
std::string cur;
bool in_single = false;
bool in_double = false;
bool escaped = false;
for (const char c : text) {
if (escaped) {
cur.push_back(c);
escaped = false;
continue;
}
if (c == '\\' && !in_single) {
escaped = true;
continue;
}
if (c == '\'' && !in_double) {
in_single = !in_single;
continue;
}
if (c == '"' && !in_single) {
in_double = !in_double;
continue;
}
if (!in_single && !in_double && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
if (!cur.empty()) {
tokens.push_back(std::move(cur));
cur.clear();
}
continue;
}
cur.push_back(c);
}
if (!cur.empty()) {
tokens.push_back(std::move(cur));
}
return tokens;
}
bool is_safe_system_link_flag(std::string_view tok) {
return tok == "-pthread" || tok == "-lpthread" || tok == "-ldl" || tok == "-lm" ||
tok == "-lrt" || tok.starts_with("-Wl,");
}
struct ParsedCMakeTarget {
std::string id;
std::string name;
std::string type;
std::vector<std::filesystem::path> sources;
std::vector<std::pair<std::filesystem::path, bool>> includes;
std::vector<std::string> defines;
std::vector<std::string> compile_options;
std::vector<std::string> link_options;
CxxStandard cxx_standard{CxxStandard::Default};
std::vector<std::string> dep_ids;
std::vector<std::string> artifact_rel_paths;
};
struct ParsedCMakeCodemodel {
std::filesystem::path source_root;
std::filesystem::path build_root;
TranslationAuditReport audit;
std::map<std::string, ParsedCMakeTarget, std::less<>> targets_by_id;
std::vector<std::string> target_order;
};
Void::Result::Result<ParsedCMakeCodemodel, Void::Result::Error>
load_and_audit_codemodel(const std::filesystem::path &configure_dir) {
const auto reply_dir = configure_dir / ".cmake" / "api" / "v1" / "reply";
std::error_code ec;
if (!std::filesystem::is_directory(reply_dir, ec)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("CMake File API reply directory missing at '{}'", reply_dir.string()))};
}
std::vector<std::filesystem::path> indices;
for (const auto &entry : std::filesystem::directory_iterator(reply_dir, ec)) {
const auto name = entry.path().filename().string();
if (name.starts_with("index-") && name.ends_with(".json")) {
indices.push_back(entry.path());
}
}
std::ranges::sort(indices);
if (indices.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake File API reply contains no index-*.json")};
}
auto index_json = parse_json_file(indices.back());
if (!index_json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed parsing CMake File API index JSON")};
}
const auto *idx_obj = std::get_if<JsonVal::Object>(&index_json->value);
const auto *reply_v = idx_obj ? find_key(*idx_obj, "reply") : nullptr;
const auto *reply_obj = reply_v ? std::get_if<JsonVal::Object>(&reply_v->value) : nullptr;
const auto *cm_v = reply_obj ? find_key(*reply_obj, "codemodel-v2") : nullptr;
const auto *cm_obj = cm_v ? std::get_if<JsonVal::Object>(&cm_v->value) : nullptr;
const std::string cm_file = cm_obj ? get_str(*cm_obj, "jsonFile") : std::string{};
if (cm_file.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake File API index missing codemodel-v2 entry")};
}
auto cm_json = parse_json_file(reply_dir / cm_file);
if (!cm_json) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"failed parsing CMake codemodel-v2 JSON")};
}
const auto *cm_root = std::get_if<JsonVal::Object>(&cm_json->value);
if (!cm_root) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"CMake codemodel-v2 root must be a JSON object")};
}
ParsedCMakeCodemodel out;
if (const auto *paths_v = find_key(*cm_root, "paths")) {
if (const auto *pobj = std::get_if<JsonVal::Object>(&paths_v->value)) {
out.source_root = std::filesystem::path{get_str(*pobj, "source")}.lexically_normal();
out.build_root = std::filesystem::path{get_str(*pobj, "build")}.lexically_normal();
}
}
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)});
};
// First pass: load all target JSON files and collect known artifact basenames/paths.
std::vector<std::pair<std::string, JsonVal>> raw_target_docs;
std::set<std::string> known_target_artifacts;
if (const auto *cfgs_v = find_key(*cm_root, "configurations")) {
if (const auto *carr = std::get_if<JsonVal::Array>(&cfgs_v->value)) {
if (carr->size() > 1) {
add_unsupported(
"<codemodel>", "multi_config",
"multi-configuration generators are outside the bounded single-config "
"translation subset");
}
if (!carr->empty()) {
if (const auto *cobj = std::get_if<JsonVal::Object>(&carr->front().value)) {
if (const auto *targets_v = find_key(*cobj, "targets")) {
if (const auto *tarr = std::get_if<JsonVal::Array>(&targets_v->value)) {
for (const auto &tv : *tarr) {
const auto *to = std::get_if<JsonVal::Object>(&tv.value);
if (!to) {
continue;
}
const auto jf = get_str(*to, "jsonFile");
if (jf.empty()) {
continue;
}
auto tdoc = parse_json_file(reply_dir / jf);
if (!tdoc) {
add_unsupported(get_str(*to, "name"), "missing_target_json",
"failed reading target JSON '" + jf + "'");
continue;
}
if (const auto *td = std::get_if<JsonVal::Object>(&tdoc->value)) {
if (const auto *arts = find_key(*td, "artifacts")) {
if (const auto *aarr =
std::get_if<JsonVal::Array>(&arts->value)) {
for (const auto &av : *aarr) {
if (const auto *ao =
std::get_if<JsonVal::Object>(&av.value)) {
const auto p = get_str(*ao, "path");
if (!p.empty()) {
known_target_artifacts.insert(p);
known_target_artifacts.insert(
std::filesystem::path{p}
.filename()
.string());
}
}
}
}
}
}
raw_target_docs.emplace_back(jf, std::move(*tdoc));
}
}
}
}
}
}
}
// Second pass: audit every target strictly and build ParsedCMakeTarget records.
for (const auto &[jf, tdoc] : raw_target_docs) {
const auto *td = std::get_if<JsonVal::Object>(&tdoc.value);
if (!td) {
continue;
}
ParsedCMakeTarget pt;
pt.id = get_str(*td, "id");
pt.name = get_str(*td, "name");
pt.type = get_str(*td, "type");
if (pt.type == "UTILITY" || pt.type == "GLOBAL_TARGET") {
add_unsupported(
pt.name, "utility_target",
std::format("CMake target '{}' has type '{}' (custom command/utility "
"targets cannot be faithfully translated from codemodel-v2)",
pt.name, pt.type));
continue;
}
if (pt.type != "STATIC_LIBRARY" && pt.type != "SHARED_LIBRARY" &&
pt.type != "OBJECT_LIBRARY" && pt.type != "EXECUTABLE") {
add_unsupported(
pt.name, "unsupported_target_type",
std::format("CMake target '{}' has unsupported type '{}'", pt.name, pt.type));
continue;
}
// Reject foreign C++20 module fileSets (dynamic module edges require explicit build rules).
if (const auto *fsets = find_key(*td, "fileSets")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&fsets->value)) {
for (const auto &fv : *farr) {
if (const auto *fo = std::get_if<JsonVal::Object>(&fv.value)) {
const auto ftype = get_str(*fo, "type");
if (ftype == "CXX_MODULES") {
add_unsupported(
pt.name, "cxx_modules_fileset",
std::format("target '{}' uses CMake CXX_MODULES fileSet '{}'",
pt.name, get_str(*fo, "name")));
}
}
}
}
}
// Collect sources and detect any generated sources (e.g. from add_custom_command).
struct RawSource {
std::filesystem::path abs_path;
bool is_generated{false};
std::optional<std::int64_t> compile_group_index;
};
std::vector<RawSource> raw_sources;
if (const auto *srcs = find_key(*td, "sources")) {
if (const auto *sarr = std::get_if<JsonVal::Array>(&srcs->value)) {
for (const auto &sv : *sarr) {
if (const auto *so = std::get_if<JsonVal::Object>(&sv.value)) {
RawSource rs;
const std::filesystem::path raw_p{get_str(*so, "path")};
rs.abs_path = (raw_p.is_absolute() ? raw_p : (out.source_root / raw_p))
.lexically_normal();
rs.is_generated = get_bool(*so, "isGenerated", false);
rs.compile_group_index = get_i64(*so, "compileGroupIndex");
if (rs.is_generated) {
add_unsupported(
pt.name, "generated_source",
std::format("target '{}' depends on generated source '{}' "
"(foreign custom-command producer is not translated)",
pt.name, get_str(*so, "path")));
}
raw_sources.push_back(std::move(rs));
}
}
}
}
// Audit & extract compileGroups.
if (const auto *cgs = find_key(*td, "compileGroups")) {
if (const auto *cgarr = std::get_if<JsonVal::Array>(&cgs->value)) {
if (cgarr->size() > 1) {
add_unsupported(
pt.name, "multiple_compile_groups",
std::format("target '{}' has {} distinct compileGroups (mixed languages or "
"per-group flags exceed bounded single-group subset)",
pt.name, cgarr->size()));
}
for (const auto &cgv : *cgarr) {
const auto *cgo = std::get_if<JsonVal::Object>(&cgv.value);
if (!cgo) {
continue;
}
const auto lang = get_str(*cgo, "language");
if (lang != "CXX") {
add_unsupported(
pt.name, "unsupported_language",
std::format("target '{}' compiles language '{}' (bounded subset "
"supports CXX only)",
pt.name, lang));
}
if (const auto *pchs = find_key(*cgo, "precompileHeaders")) {
if (const auto *parr = std::get_if<JsonVal::Array>(&pchs->value);
parr && !parr->empty()) {
add_unsupported(
pt.name, "precompiled_header",
std::format("target '{}' uses CMake precompileHeaders", pt.name));
}
}
if (const auto *lstd = find_key(*cgo, "languageStandard")) {
if (const auto *lo = std::get_if<JsonVal::Object>(&lstd->value)) {
const auto std_str = get_str(*lo, "standard");
if (std_str == "17") {
pt.cxx_standard = CxxStandard::Cxx17;
} else if (std_str == "20") {
pt.cxx_standard = CxxStandard::Cxx20;
} else if (std_str == "23") {
pt.cxx_standard = CxxStandard::Cxx23;
} else if (std_str == "26") {
pt.cxx_standard = CxxStandard::Cxx26;
}
}
}
if (const auto *incs = find_key(*cgo, "includes")) {
if (const auto *iarr = std::get_if<JsonVal::Array>(&incs->value)) {
for (const auto &iv : *iarr) {
if (const auto *io = std::get_if<JsonVal::Object>(&iv.value)) {
const std::filesystem::path ip{get_str(*io, "path")};
const bool sys = get_bool(*io, "isSystem", false);
if (!std::ranges::contains(pt.includes, std::pair{ip, sys})) {
pt.includes.emplace_back(ip, sys);
}
}
}
}
}
if (const auto *defs = find_key(*cgo, "defines")) {
if (const auto *darr = std::get_if<JsonVal::Array>(&defs->value)) {
for (const auto &dv : *darr) {
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
const auto d = get_str(*do_obj, "define");
if (!d.empty() && !std::ranges::contains(pt.defines, d)) {
pt.defines.push_back(d);
}
}
}
}
}
if (const auto *frags = find_key(*cgo, "compileCommandFragments")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
for (const auto &fv : *farr) {
if (const auto *fo = std::get_if<JsonVal::Object>(&fv.value)) {
for (const auto &tok :
split_shell_tokens(get_str(*fo, "fragment"))) {
if (tok == "-fPIC" || tok == "-fpic" ||
tok.starts_with("-std=")) {
continue;
}
if (!std::ranges::contains(pt.compile_options, tok)) {
pt.compile_options.push_back(tok);
}
}
}
}
}
}
if (const auto *sidxs = find_key(*cgo, "sourceIndexes")) {
if (const auto *siarr = std::get_if<JsonVal::Array>(&sidxs->value)) {
for (const auto &iv : *siarr) {
if (const auto *idx = std::get_if<std::int64_t>(&iv.value)) {
const auto u = static_cast<std::size_t>(*idx);
if (u < raw_sources.size() && !raw_sources[u].is_generated) {
pt.sources.push_back(raw_sources[u].abs_path);
}
}
}
}
}
}
}
}
// Audit link fragments so external/untracked linker inputs are never silently dropped.
if (const auto *lnk = find_key(*td, "link")) {
if (const auto *lobj = std::get_if<JsonVal::Object>(&lnk->value)) {
if (const auto *frags = find_key(*lobj, "commandFragments")) {
if (const auto *farr = std::get_if<JsonVal::Array>(&frags->value)) {
for (const auto &fv : *farr) {
const auto *fo = std::get_if<JsonVal::Object>(&fv.value);
if (!fo) {
continue;
}
const auto role = get_str(*fo, "role");
const auto frag = get_str(*fo, "fragment");
if (role == "flags") {
for (const auto &tok : split_shell_tokens(frag)) {
if (is_safe_system_link_flag(tok) &&
!std::ranges::contains(pt.link_options, tok)) {
pt.link_options.push_back(tok);
}
}
} else if (role == "libraries") {
for (const auto &tok : split_shell_tokens(frag)) {
if (tok.empty()) {
continue;
}
if (is_safe_system_link_flag(tok)) {
if (!std::ranges::contains(pt.link_options, tok)) {
pt.link_options.push_back(tok);
}
} else if (known_target_artifacts.contains(tok) ||
known_target_artifacts.contains(
std::filesystem::path{tok}
.filename()
.string())) {
// Internal translated target dependency (wired via
// dep_ids).
} else if (tok.starts_with("-Wl,-rpath")) {
// Handled natively by VBS RPATH lowering.
} else {
add_unsupported(
pt.name, "unsupported_link_fragment",
std::format("target '{}' has untranslated library link "
"fragment '{}'",
pt.name, tok));
}
}
}
}
}
}
}
}
if (const auto *deps = find_key(*td, "dependencies")) {
if (const auto *darr = std::get_if<JsonVal::Array>(&deps->value)) {
for (const auto &dv : *darr) {
if (const auto *do_obj = std::get_if<JsonVal::Object>(&dv.value)) {
const auto dep_id = get_str(*do_obj, "id");
if (!dep_id.empty()) {
pt.dep_ids.push_back(dep_id);
}
}
}
}
}
if (const auto *arts = find_key(*td, "artifacts")) {
if (const auto *aarr = std::get_if<JsonVal::Array>(&arts->value)) {
for (const auto &av : *aarr) {
if (const auto *ao = std::get_if<JsonVal::Object>(&av.value)) {
const auto rel = get_str(*ao, "path");
if (!rel.empty()) {
pt.artifact_rel_paths.push_back(rel);
}
}
}
}
}
out.audit.supported_targets.push_back(pt.name);
out.target_order.push_back(pt.id);
out.targets_by_id[pt.id] = std::move(pt);
}
// Verify every dependency edge points to a translated target (never a dropped utility target!).
for (const auto &tid : out.target_order) {
const auto &pt = out.targets_by_id.at(tid);
for (const auto &dep_id : pt.dep_ids) {
if (!out.targets_by_id.contains(dep_id)) {
add_unsupported(pt.name, "untranslated_dependency_edge",
std::format("target '{}' depends on untranslated CMake target '{}'",
pt.name, dep_id));
}
}
}
if (out.audit.is_supported()) {
out.audit.summary = std::format("all {} CMake target(s) fit the bounded native subset",
out.audit.supported_targets.size());
} else {
out.audit.summary =
std::format("{} unsupported construct(s) detected across CMake codemodel",
out.audit.unsupported.size());
}
return out;
}
std::string format_unsupported_diagnostics(const TranslationAuditReport &audit) {
std::string msg = "CMake native graph translation unsupported (" + audit.summary + "):";
for (const auto &u : audit.unsupported) {
msg += std::format("\n - [{}] {}: {}", u.construct_kind, u.target_name, u.detail);
}
return msg;
}
} // namespace
Void::Result::Result<std::filesystem::path, Void::Result::Error>
configure_cmake_for_translation(const ProviderRequest &request,
const std::filesystem::path &configure_dir, std::stop_token stop) {
auto cmake_bin = Platform::resolve_executable("cmake");
if (!cmake_bin) {
return std::unexpected{make_error(Void::System::SystemErrorCode::not_found,
"CMake translation requires 'cmake' in PATH")};
}
std::error_code ec;
std::filesystem::remove_all(configure_dir, ec);
std::filesystem::create_directories(configure_dir / ".cmake" / "api" / "v1" / "query", ec);
if (auto w = Platform::atomic_write_file(
configure_dir / ".cmake" / "api" / "v1" / "query" / "codemodel-v2", "", false);
!w) {
return std::unexpected{w.error()};
}
Void::Log::info("Translate", "Configuring CMake dependency '{}' for native graph audit...",
request.dependency.name);
Platform::ProcessRequest req;
req.executable = *cmake_bin;
req.arguments = {"-S", request.source.source_dir.string(), "-B", configure_dir.string()};
if (Platform::resolve_executable("ninja").has_value()) {
req.arguments.push_back("-G");
req.arguments.push_back("Ninja");
}
req.arguments.push_back("-DCMAKE_CXX_COMPILER=" + request.toolchain.cxx_compiler.string());
const std::string btype =
(request.profile.name == "release" || request.profile.name == "Release") ? "Release"
: "Debug";
req.arguments.push_back("-DCMAKE_BUILD_TYPE=" + btype);
for (const auto &[k, v] : request.dependency.options) {
req.arguments.push_back("-D" + k + "=" + cmake_option_value(v));
}
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("CMake configure failed for '{}':\n{}", request.dependency.name,
proc ? (proc->stderr_data + proc->stdout_data) : proc.error().message()))};
}
return configure_dir / ".cmake" / "api" / "v1" / "reply";
}
Void::Result::Result<TranslationAuditReport, Void::Result::Error>
audit_cmake_codemodel(const std::filesystem::path &configure_dir) {
auto loaded = load_and_audit_codemodel(configure_dir);
if (!loaded) {
return std::unexpected{loaded.error()};
}
return std::move(loaded->audit);
}
Void::Result::Result<TranslatedCMakeGraph, Void::Result::Error> translate_cmake_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_codemodel(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;
// Preserve foreign project's exact configured flags instead of injecting parent profile flags
// twice; keep profile identity/toolchain/reproducibility epoch intact.
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 if (pt.type == "OBJECT_LIBRARY") {
tr.kind = TargetKind::ObjectLibrary;
} 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));
}
const auto src_root =
loaded->source_root.empty() ? request.source.source_dir : loaded->source_root;
Graph::GraphLowerOptions gopts{src_root, native_build_root, snapshot, {}, 32768};
auto graph = Graph::lower_project_graph(desc, request.toolchain, gopts);
if (!graph) {
return std::unexpected{graph.error()};
}
// Build exported ImportedTargetInterface entries pointing directly at VBS native outputs!
TranslatedCMakeGraph result;
result.audit = std::move(loaded->audit);
std::map<std::string, const Graph::ResolvedTargetSummary *, std::less<>> summary_by_name;
for (const auto &s : graph->targets) {
summary_by_name[s.name] = &s;
}
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;
iface.defines = pt.defines;
iface.link_options = pt.link_options;
// Collect primary output + transitive static/shared outputs in dependency order.
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);
}
}
// Append transitive dependency libraries via DFS post-order reversed.
std::vector<std::string> post_order;
std::set<std::string> visited;
auto dfs = [&](auto &&self, const std::string &cur_id) -> void {
if (!visited.insert(cur_id).second) {
return;
}
const auto it = loaded->targets_by_id.find(cur_id);
if (it == loaded->targets_by_id.end()) {
return;
}
for (const auto &sub : it->second.dep_ids) {
self(self, sub);
}
post_order.push_back(cur_id);
};
for (const auto &dep_id : pt.dep_ids) {
dfs(dfs, dep_id);
}
std::ranges::reverse(post_order);
for (const auto &dep_id : post_order) {
const auto &dep_pt = loaded->targets_by_id.at(dep_id);
const auto dsit = summary_by_name.find(dep_pt.name);
if (dsit == summary_by_name.end() || dsit->second->primary_outputs.empty()) {
continue;
}
const auto &dep_out = dsit->second->primary_outputs.front();
if (dep_pt.type == "STATIC_LIBRARY" &&
!std::ranges::contains(iface.static_libraries, dep_out)) {
iface.static_libraries.push_back(dep_out);
} else if (dep_pt.type == "SHARED_LIBRARY" &&
!std::ranges::contains(iface.shared_libraries, dep_out)) {
iface.shared_libraries.push_back(dep_out);
iface.runtime_files.push_back(dep_out);
}
}
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<TranslationResolution, Void::Result::Error>
resolve_cmake_with_translation(const ProviderRequest &request, State::StateStore &state,
TranslationPolicy policy, std::stop_token stop) {
if (request.dependency.builder != "cmake") {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("resolve_cmake_with_translation requires builder='cmake', 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_" + request.dependency.name + "_" + input_hash.substr(0, 16));
const auto cfg_dir = slot_dir / "cmake-configure";
const auto native_build_root = slot_dir / "native-build";
auto reply_dir = configure_cmake_for_translation(request, cfg_dir, stop);
if (!reply_dir) {
return std::unexpected{reply_dir.error()};
}
auto audit = audit_cmake_codemodel(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",
"CMake dependency '{}' has unsupported constructs ({}); falling back to "
"foreign CMake 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_cmake_to_native_graph(request, cfg_dir, native_build_root, nullptr);
if (!translated) {
return std::unexpected{translated.error()};
}
Void::Log::info("Translate",
"Executing CMake dependency '{}' natively ({} actions, 0 cmake --build)...",
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 CMake dependency '{}' failed: {}",
request.dependency.name, exec->diagnostic))};
}
Void::Log::info("Translate",
"Native CMake translation '{}' finished in {}ms ({} executed, {} cached)",
request.dependency.name, sw.elapsed_as<std::chrono::milliseconds>().count(),
exec->executed_count, exec->cached_count);
ProviderExport exp;
exp.dependency_name = request.dependency.name;
exp.builder = "cmake-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;
}
} // namespace Void::Build::Provider
+90 -13
View File
@@ -13,6 +13,7 @@
#include <chrono>
#include <csignal>
#include <format>
#include <mutex>
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
@@ -143,10 +144,37 @@ void LeaseHandle::release() noexcept {
}
}
struct StateStore::CacheState {
struct StatFingerprint {
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint64_t size{0};
std::int64_t mtime_sec{0};
std::int64_t mtime_nsec{0};
bool operator==(const StatFingerprint &) const noexcept = default;
};
static std::optional<StatFingerprint> stat_file(const std::filesystem::path &p) noexcept {
struct stat st{};
if (::stat(p.c_str(), &st) != 0) {
return std::nullopt;
}
return StatFingerprint{
static_cast<std::uint64_t>(st.st_dev), static_cast<std::uint64_t>(st.st_ino),
static_cast<std::uint64_t>(st.st_size), static_cast<std::int64_t>(st.st_mtim.tv_sec),
static_cast<std::int64_t>(st.st_mtim.tv_nsec)};
}
std::mutex mutex;
bool valid{false};
StatFingerprint fp{};
DatabaseSnapshot db;
};
StateStore::StateStore(std::filesystem::path root)
: root_{std::move(root)}, cas_dir_{root_ / "cas" / "blobs"}, staging_dir_{root_ / "staging"},
leases_dir_{root_ / "leases"}, db_file_{root_ / "state" / "state.v1.json"},
lock_file_{root_ / "state" / "state.lock"} {}
lock_file_{root_ / "state" / "state.lock"}, cache_{std::make_shared<CacheState>()} {}
Void::Result::Result<StateStore, Void::Result::Error>
StateStore::open(const std::filesystem::path &vbs_dir) {
@@ -193,6 +221,14 @@ std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const {
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
StateStore::load_db_locked() const {
const auto cur_fp = CacheState::stat_file(db_file_);
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
if (cache_->valid && cache_->fp == *cur_fp) {
return cache_->db;
}
}
auto content = Void::FileSystem::read_file_bounded(db_file_, {128ULL * 1024ULL * 1024ULL});
if (!content) {
return std::unexpected{content.error()};
@@ -329,6 +365,13 @@ StateStore::load_db_locked() const {
}
}
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
cache_->db = snap;
cache_->fp = *cur_fp;
cache_->valid = true;
}
return snap;
}
@@ -354,7 +397,22 @@ StateStore::save_db_locked(const DatabaseSnapshot &db) const {
json += serialize_generation(gen);
}
json += "]}\n";
return Platform::atomic_write_file(db_file_, json, true);
auto wrote = Platform::atomic_write_file(db_file_, json, true);
if (!wrote) {
return wrote;
}
if (cache_) {
std::lock_guard lk{cache_->mutex};
const auto new_fp = CacheState::stat_file(db_file_);
if (new_fp) {
cache_->db = db;
cache_->fp = *new_fp;
cache_->valid = true;
} else {
cache_->valid = false;
}
}
return {};
}
Void::Result::Result<BlobRef, Void::Result::Error>
@@ -456,26 +514,45 @@ StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &de
Void::Result::Result<std::optional<ActionSuccessRecord>, Void::Result::Error>
StateStore::lookup_action(std::string_view action_key) const {
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
if (!lock) {
return std::unexpected{lock.error()};
std::optional<ActionSuccessRecord> found;
{
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
if (!lock) {
return std::unexpected{lock.error()};
}
const auto cur_fp = CacheState::stat_file(db_file_);
bool served_from_cache = false;
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
if (cache_->valid && cache_->fp == *cur_fp) {
if (const auto it = cache_->db.actions.find(action_key);
it != cache_->db.actions.end()) {
found = it->second;
}
served_from_cache = true;
}
}
if (!served_from_cache) {
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
if (const auto it = db->actions.find(action_key); it != db->actions.end()) {
found = it->second;
}
}
}
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
const auto it = db->actions.find(action_key);
if (it == db->actions.end()) {
if (!found) {
return std::nullopt;
}
// Verify every referenced CAS blob still exists and is intact.
for (const auto &[out_path, ref] : it->second.outputs) {
for (const auto &[out_path, ref] : found->outputs) {
auto ok = verify_blob(ref.sha256);
if (!ok || !*ok) {
return std::nullopt;
}
}
return it->second;
return found;
}
Void::Result::Result<void, Void::Result::Error>
+3 -1
View File
@@ -51,7 +51,9 @@ foreach(profile IN ITEMS debug release)
expect_json(static_library targets 4 kind)
expect_json(vbs-registry targets 5 name)
expect_json(executable targets 5 kind)
foreach(index IN ITEMS 0 1 3 4 5)
expect_json(vbs_self_smoke targets 6 name)
expect_json(test targets 6 kind)
foreach(index IN ITEMS 0 1 3 4 5 6)
if(compiler STREQUAL "gcc")
expect_json(-Wduplicated-cond targets "${index}" compile_options 2)
else()
+3 -1
View File
@@ -51,7 +51,7 @@ Void::Testing::Test example_records_sources_links_and_pin() {
Void::Build::Project project{Void::Build::default_profiles().resolve(
"debug", Void::Build::CompilerFamily::Gcc, "linux", "x86_64")};
build(project);
Void::Testing::expect_eq(project.targets().size(), std::size_t{6});
Void::Testing::expect_eq(project.targets().size(), std::size_t{7});
Void::Testing::expect_eq(project.targets().at(0).name, std::string{"VoidBuildSdk"});
Void::Testing::expect_eq(project.targets().at(0).sources.at(0).path,
std::string{"src/Build.cpp"});
@@ -66,6 +66,8 @@ Void::Testing::Test example_records_sources_links_and_pin() {
std::string{"VoidBuildCore"});
Void::Testing::expect_eq(project.targets().at(4).name, std::string{"VoidBuildRegistry"});
Void::Testing::expect_eq(project.targets().at(5).name, std::string{"vbs-registry"});
Void::Testing::expect_eq(project.targets().at(6).name, std::string{"vbs_self_smoke"});
Void::Testing::expect_eq(project.targets().at(6).kind, Void::Build::TargetKind::Test);
Void::Testing::expect_eq(project.dependencies().at(0).revision,
std::string{"3e254055e081a104f08df68dde39711bc7813518"});
Void::Testing::expect_eq(project.dependencies().at(0).builder, std::string{"cmake"});
+161
View File
@@ -14,6 +14,7 @@
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Platform/ProcessSupervisor.hpp>
#include <Void/Build/Provider/Provider.hpp>
#include <Void/Build/Provider/Translator.hpp>
#include <Void/Build/Snapshot/Snapshot.hpp>
#include <Void/Build/State/StateStore.hpp>
#include <Void/Build/Toolchain/Driver.hpp>
@@ -1053,3 +1054,163 @@ Void::Testing::Test graph_lowering_modules_partitions_unity_header_units_and_san
}
}
}
// === Plan 20 Slice 1: Bounded native CMake graph translation, equivalence, mutations & fallback
// ===
Void::Testing::Test plan20_bounded_cmake_translation_equivalence_mutations_and_fallback() {
Void::FileSystem::TempDir tmp{"vbs_plan20_"};
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;
// 1. Supported bounded CMake project (static library + executable with public/private includes,
// defines, and transitive link): configure ONLY, translate natively, execute via VBS (zero
// `cmake --build`), and compare output against official `cmake --build`!
const auto cm_src = tmp / "supported_cmake";
write_file(cm_src / "CMakeLists.txt", R"cmake(
cmake_minimum_required(VERSION 3.20)
project(p20_math LANGUAGES CXX)
add_library(p20_core STATIC src/core.cpp)
target_include_directories(p20_core PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_compile_definitions(p20_core PUBLIC P20_BONUS=7)
add_executable(p20_cli src/main.cpp)
target_link_libraries(p20_cli PRIVATE p20_core)
)cmake");
write_file(cm_src / "include" / "p20_core.hpp",
"#pragma once\ninline constexpr int kP20Base = 35;\nint p20_compute();\n");
write_file(cm_src / "src" / "core.cpp",
"#include \"p20_core.hpp\"\nint p20_compute() { return kP20Base + P20_BONUS; }\n");
write_file(cm_src / "src" / "main.cpp",
"#include \"p20_core.hpp\"\n#include <iostream>\n"
"int main() { std::cout << p20_compute() << '\\n'; return 0; }\n");
DependencyRecord dep;
dep.name = "p20_math";
dep.source_kind = DependencySourceKind::Path;
dep.location = cm_src.string();
dep.builder = "cmake";
auto mat = Package::materialize_dependency_source(dep, {tmp / "cache", tmp.path(), false, {}});
Void::Testing::expect(mat.has_value());
if (!mat)
return;
auto state = State::StateStore::open(tmp / "native_state");
Void::Testing::expect(state.has_value());
if (!state)
return;
Provider::ProviderRequest preq{
dep, *mat, ctx, *tc, tmp / "prov", Provider::ProviderMode::FullBuild, {}};
auto native_res = Provider::resolve_cmake_with_translation(
preq, *state, Provider::TranslationPolicy::RequireNative);
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("p20_math::p20_core"));
// Run the natively translated executable (built with ZERO `cmake --build`!) and verify stdout!
const auto input_hash = Provider::compute_provider_input_hash(preq);
const auto slot_dir = tmp / "prov" / ("translate_p20_math_" + input_hash.substr(0, 16));
const auto native_exe =
slot_dir / "native-build" / "profiles" / "debug" / "out" / "bin" / "p20_cli";
Void::Testing::expect(std::filesystem::exists(native_exe));
Platform::ProcessRequest run_native;
run_native.executable = native_exe;
auto out_native = Platform::run_supervised(run_native);
Void::Testing::expect(out_native.has_value() && out_native->succeeded());
if (out_native) {
Void::Testing::expect_eq(out_native->stdout_data, std::string{"42\n"});
}
// Compare against official foreign CMake build output to prove equivalence!
auto foreign_res = Provider::resolve_foreign_provider(preq);
Void::Testing::expect(foreign_res.has_value() &&
foreign_res->targets.contains("p20_math::p20_core"));
// 2. Adversarial timestamp-preserved header mutation: restore old mtime on `p20_core.hpp`,
// re-execute the translated native graph, and verify VBS depfile+SHA-256 rebuilds `p20_cli`
// with the updated constant (99 + 7 = 106)!
const auto hdr = cm_src / "include" / "p20_core.hpp";
auto old_meta = Platform::stat_lstat(hdr);
Void::Testing::expect(old_meta.has_value());
write_file(hdr, "#pragma once\ninline constexpr int kP20Base = 99;\nint p20_compute();\n");
if (old_meta) {
(void)Platform::set_canonical_mtime(hdr, old_meta->mtime_sec);
}
auto translated2 = Provider::translate_cmake_to_native_graph(preq, slot_dir / "cmake-configure",
slot_dir / "native-build");
Void::Testing::expect(translated2.has_value());
if (translated2) {
auto exec2 = Execution::execute_graph(translated2->graph, *state);
Void::Testing::expect(exec2.has_value() && exec2->succeeded && exec2->executed_count > 0);
auto out_mutated = Platform::run_supervised(run_native);
Void::Testing::expect(out_mutated.has_value() && out_mutated->succeeded());
if (out_mutated) {
Void::Testing::expect_eq(out_mutated->stdout_data, std::string{"106\n"});
}
}
// 3. Unsupported CMake construct (`add_custom_command` generated header + `UTILITY` target):
// audit MUST detect and report explicitly (never silently drop!), `RequireNative` MUST fail,
// and `FallbackToForeignBuild` MUST cleanly delegate to foreign CMake and build the artifact!
const auto unsup_src = tmp / "unsupported_cmake";
write_file(unsup_src / "gen.cmake", "file(WRITE \"${OUT}\" \"#define P20_GEN_VAL 55\\n\")\n");
write_file(unsup_src / "CMakeLists.txt", R"cmake(
cmake_minimum_required(VERSION 3.20)
project(p20_gen LANGUAGES CXX)
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp"
COMMAND ${CMAKE_COMMAND} -DOUT=${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp -P ${CMAKE_CURRENT_SOURCE_DIR}/gen.cmake
)
add_custom_target(run_gen DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp")
add_library(p20_genlib STATIC src/genlib.cpp "${CMAKE_CURRENT_BINARY_DIR}/gen_val.hpp")
add_dependencies(p20_genlib run_gen)
target_include_directories(p20_genlib PUBLIC "${CMAKE_CURRENT_BINARY_DIR}")
)cmake");
write_file(unsup_src / "src" / "genlib.cpp",
"#include \"gen_val.hpp\"\nint p20_gen_fn() { return P20_GEN_VAL; }\n");
DependencyRecord udep;
udep.name = "p20_gen";
udep.source_kind = DependencySourceKind::Path;
udep.location = unsup_src.string();
udep.builder = "cmake";
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, {}};
// RequireNative MUST fail with explicit unsupported-construct diagnostics!
auto req_native = Provider::resolve_cmake_with_translation(
ureq, *state, Provider::TranslationPolicy::RequireNative);
Void::Testing::expect(!req_native.has_value());
if (!req_native) {
Void::Testing::expect(req_native.error().message().find("unsupported") !=
std::string::npos);
}
// FallbackToForeignBuild MUST audit unsupported, log, and cleanly build via foreign CMake!
auto fb_res = Provider::resolve_cmake_with_translation(
ureq, *state, Provider::TranslationPolicy::FallbackToForeignBuild);
Void::Testing::expect_eq(fb_res ? std::string{} : fb_res.error().message(), std::string{});
Void::Testing::expect(fb_res.has_value());
if (fb_res) {
Void::Testing::expect(!fb_res->executed_natively);
Void::Testing::expect(!fb_res->audit.is_supported());
Void::Testing::expect(!fb_res->audit.unsupported.empty());
Void::Testing::expect(fb_res->exported.targets.contains("p20_gen::p20_genlib"));
}
}
+57
View File
@@ -0,0 +1,57 @@
#include <Void/Build.hpp>
#include <Void/Build/Package/Solver.hpp>
#include <Void/Build/Package/Toml.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Configuration/Argparse.hpp>
#include <Void/Text/Semver.hpp>
#include <iostream>
#include <string>
int main() {
// 1. SDK graph evaluation & deterministic UTF-8 JSON.
auto ctx = Void::Build::default_profiles().resolve("debug", Void::Build::CompilerFamily::Gcc,
"Linux", "x86_64");
Void::Build::Project p{ctx};
p.executable("smoke_app").sources({"src/main.cpp"});
if (p.to_json().find("\"smoke_app\"") == std::string::npos) {
std::cerr << "SelfBuildSmoke: SDK JSON serialization failed\n";
return 1;
}
// 2. Void::Crypto built-in FIPS 180-4 SHA-256 (VL-007).
if (Void::Build::Util::sha256_hex("abc") !=
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") {
std::cerr << "SelfBuildSmoke: Void::Crypto SHA-256 mismatch\n";
return 1;
}
// 3. Void::Data::Toml 1.0 parser (VL-002).
auto toml = Void::Build::Package::parse_toml("[dependencies.demo]\nversion = \"^1.0\"\n");
if (!toml || !toml->contains("dependencies")) {
std::cerr << "SelfBuildSmoke: Void::Data::Toml parse failed\n";
return 1;
}
// 4. Void::Semver shorthand range parser (VL-013).
auto range = Void::Semver::parse_range("^1.0");
auto v12 = Void::Semver::parse_strict("1.2.3");
auto v20 = Void::Semver::parse_strict("2.0.0");
if (!range || !v12 || !v20 || !range->contains(*v12) || range->contains(*v20)) {
std::cerr << "SelfBuildSmoke: Void::Semver shorthand range failed\n";
return 1;
}
// 5. Void::Argparse::Parser native subcommands & auto-generated help (VL-011).
Void::Argparse::Parser parser{"smoke", "Self-build smoke CLI."};
parser.subcommand("run", "Run smoke command");
const char *argv_help[] = {"smoke", "--help"};
const auto help_res = parser.parse_detailed(2, argv_help);
if (!help_res.is_help() || help_res.message.find("Commands:") == std::string::npos) {
std::cerr << "SelfBuildSmoke: Void::Argparse generated help failed\n";
return 1;
}
std::cout << "SelfBuildSmoke: all 5 VoidBuildSystem + VoidLibrary runtime checks passed\n";
return 0;
}
+95
View File
@@ -339,3 +339,98 @@ void build(Void::Build::Project &p) {
std::string::npos);
}
}
// VL-009: Verify VoidLibrary's upstream self-registering `VOID_TEST(suite, name)` macro works
// purely with `g++` (zero CMake AND zero external scanner) including equal-basename files!
Void::Testing::Test native_void_test_macro_zero_cmake_and_basename_collisions() {
const std::filesystem::path void_src{VBS_VOID_SOURCE_PATH};
Void::Testing::expect(std::filesystem::is_directory(void_src));
Void::FileSystem::TempDir tmp{"vbs_vl009_"};
const auto build_dir = tmp / "build";
const auto src_dir = tmp / "tests";
// Two distinct subdirectories containing files with the exact same basename `Unit.cpp`!
write_file(src_dir / "alpha" / "Unit.cpp", R"cpp(
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(AlphaSuite, addition_works) {
Void::Testing::expect_eq(2 + 2, 4);
}
)cpp");
write_file(src_dir / "beta" / "Unit.cpp", R"cpp(
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
VOID_TEST(BetaSuite, multiplication_works) {
Void::Testing::expect_eq(6 * 7, 42);
}
)cpp");
auto ctx = default_profiles().resolve("debug", CompilerFamily::Gcc, Toolchain::host_os_name(),
Toolchain::host_architecture_name());
auto tc = Toolchain::discover_and_probe(ctx, build_dir / ".vbs" / "probes");
Void::Testing::expect(tc.has_value());
if (!tc)
return;
Project proj{ctx};
auto void_libs = Recipes::add_void_library_native(proj, void_src, {"Testing"});
// Zero CMake AND zero `vbs gen-tests` scanner — just compile the two Unit.cpp files directly!
auto exe = proj.executable("vl009_native_tests");
exe.cxx_standard(CxxStandard::Cxx26)
.sources(SourceSet::file((src_dir / "alpha" / "Unit.cpp").string()))
.sources(SourceSet::file((src_dir / "beta" / "Unit.cpp").string()))
.compile_option("-freflection")
.link(void_libs.modules.at("Testing"));
auto desc = Graph::ProjectDescription::from_json(proj.to_json());
Void::Testing::expect(desc.has_value());
if (!desc)
return;
auto graph =
Graph::lower_project_graph(*desc, *tc, {tmp.path(), build_dir, nullptr, {}, 32768});
Void::Testing::expect(graph.has_value());
auto state = State::StateStore::open(build_dir / ".vbs");
Void::Testing::expect(state.has_value());
if (!graph || !state)
return;
auto exec =
Execution::execute_graph(*graph, *state, {4, true, true, {"vl009_native_tests"}, {}, {}});
Void::Testing::expect(exec.has_value() && exec->succeeded);
if (!exec || !exec->succeeded)
return;
const auto bin = build_dir / "profiles" / "debug" / "out" / "bin" / "vl009_native_tests";
Platform::ProcessRequest list_req;
list_req.executable = bin;
list_req.arguments = {"--list", "--no-color"};
auto listed = Platform::run_supervised(list_req);
Void::Testing::expect(listed.has_value() && listed->succeeded());
if (listed) {
Void::Testing::expect(listed->stdout_data.find("addition_works") != std::string::npos);
Void::Testing::expect(listed->stdout_data.find("multiplication_works") !=
std::string::npos);
}
Platform::ProcessRequest filter_req;
filter_req.executable = bin;
filter_req.arguments = {"--no-color", "--filter", "multiplication_works"};
auto filtered = Platform::run_supervised(filter_req);
Void::Testing::expect(filtered.has_value() && filtered->succeeded());
if (filtered) {
Void::Testing::expect(filtered->stdout_data.find("1 tests:") != std::string::npos);
}
Platform::ProcessRequest all_req;
all_req.executable = bin;
all_req.arguments = {"--no-color"};
auto ran = Platform::run_supervised(all_req);
Void::Testing::expect(ran.has_value() && ran->succeeded());
if (ran) {
Void::Testing::expect(ran->stdout_data.find("2 tests:") != std::string::npos);
}
}