Tests stage their fixtures under fixed names in the temp directory, fs::temp_directory_path() / "crafter-build-<name>", and two runs at once staged into the same ones: natively every process shares the machine's /tmp, and every sandbox of crafter-build's Flatpak shares the one the app has, whatever checkout it runs in. A test of one run could find what it had staged removed or written over by the same test of the other run, which removes the directory as it starts and stages its copy anew. RunTests now makes a directory for the run in the temp directory, a PrivateDirectory, and runs each test with TMPDIR naming <run>/<name>, so that fs::temp_directory_path() in the test names it and the fixed names are the run's alone. The second test of one name in a run, as two configurations or two targets may each have one, gets <name>-2, so that removing one's directory does not take the other's. RunSingleTest takes the directory as a new last parameter and puts TMPDIR into the env prefix of the test's command, beside a Wayland test's WAYLAND_DISPLAY. env's command is sh, which execs the test's words, as for a Wayland test's: env takes a word with an '=' in it ahead of its command for an assignment, a binary's path among them, and with no command left it printed its environment and exited 0, a pass for a test that never ran. What a test that passes or skips leaves is removed when it ends. What one that fails, crashes or times out leaves is kept for a look, its log says where, as does what is printed of a test that fails or crashes, and the run's directory then outlives the run, unlocked, for a later run to remove a minute after, or, where the run was killed, a minute after its last change to it; PrivateDirectory gains Keep() for that. A test's logs, build/test-logs/<name>.log and <name>.compositor.log, are named as its TMPDIR is, <name>-2 for a later test of one name, so that two failing tests of one name each keep their own, and with it where what each left is kept: with one log for both, the second's was written over the first's. The README's line on the logs says so. The directory is dated as it is let go of, since the removal of abandoned directories goes by its date, which is that of what was last made or removed in it: for the run of a test that fails after a minute, as one that times out at the default 60 s does, a minute old already, and the next run would remove it at once. The removal now reads a directory's date only once it holds the directory's lock: a date read before could be one the holder replaced as it let go. The directory is the run's, not a pass's: every pass of a sweep over targets shares it, so it is made and its surroundings swept once, and let go of once the last pass is done. A pass that made one of its own would have made it once the passes before had let go of theirs, and making it would have removed any of those that had not changed for a minute: a kept one, after a pass of that long, while its test's output said where it was. RunTests becomes the wrapper that holds the run's directory around RunTestsWith, the passes it recurses into, and the directory is kept the moment a test keeps something in it, by the worker that ran the test, so that a later pass that throws, as one does for a target whose runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker that cannot be started does not take it with it; Keep() may be called from several workers at once. TMPDIR reaches the test where its runner hands it on, as running it directly and qemu-user do. Under wine a Windows test does not get TMPDIR, and takes the Wine prefix's TMP, TEMP and temp directory, and wasmtime gives a test no environment at all; RunSingleTest's comment says so. A test under `host` gets its TMPDIR as any test does, so that comment and HostDisplay's now say that `host` leaves the test the display, not the whole environment, as it is. In the runner rather than in each of the 74 tests whose main.cpp uses the temp directory at this commit: a project's own tests are covered the same way, where their runner hands them TMPDIR. Of the 74 only SysrootStdModule has to change. It builds against a sysroot it stages there, and the std module's cache directory is keyed on the sysroot's path, which is a new one every run now, so every run left one more directory, with its lock, in the real cache; it keeps its cache in its scratch directory now, as the tests that have crafter-build fetch a repository they stage do. AGENTS.template.md says what changes for the tests: HostFlatpak, whose /tmp is no longer the temp directory a test is given, is a second test that writes elsewhere, and under `crafter-build test` a staged copy goes with the test's TMPDIR rather than at the test's next run.
48 KiB
AGENTS.md
Guidance for coding agents and contributors working on crafter-build itself. The README is the user-facing manual; this file holds what you need to change the build system. When the two disagree, the code wins: check the interface in interfaces/ and the --help output of the built binary.
Project overview
crafter-build is a C++26 modules build system. A project is described by a project.cpp that returns a Crafter::Configuration, or several of them; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own project.cpp builds crafter-build with crafter-build, and its tests link the library and drive Build() in-process.
| Path | What lives there |
|---|---|
interfaces/Crafter.Build-<Partition>.cppm |
Module interface partitions. Crafter.Build.cppm is the umbrella that re-exports them. |
implementations/Crafter.Build-<Partition>.cpp |
Implementation units, one per partition, named Crafter.Build:<Partition>_impl. main.cpp is a thin wrapper around Crafter::Run. |
project.cpp |
The self-host build description: a crafter.build-lib library, a crafter.build-exe executable, the test declarations, the lint rules and the flatpak and install scripts. |
AGENTS.template.md |
The source of AGENTS.md. Every build and test run writes AGENTS.md from it, with the notes the dependencies ship; AGENTS.md is gitignored, so changes go here. |
tests/<Name>/main.cpp |
One self-test per directory; tests/<Name>/fixture/ holds the sample project it builds. |
examples/ |
Standalone user-facing projects, MIT licensed. |
build.sh |
Bootstrap script. It compiles everything by hand, without crafter-build. |
wasi-runtime/ |
runtime.js and index.html.in, shipped for browser targets. |
lib/ |
Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. |
share/crafter-build/, bin/, build/, lib/*.a |
Generated and gitignored. |
packaging/flatpak/, .forgejo/workflows/ci.yaml |
The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. |
.review-gates/ |
The pre-push review's config.json and this repository's lens sections (lenses/), read by Crafter.Review. Its push/ and trees/ are generated and gitignored. |
Partitions and what they own:
:Toolchainresolves the compiler once per process (GetToolchain): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, libclang, libc++'s std module source and the default sysroots, fromCRAFTER_BUILD_LLVM_DIR, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from/.flatpak-infoor the fileCRAFTER_BUILD_FLATPAK_INFOnames, and the nvcccfg.cudacompiles with:$CUDA_PATH/bin/nvcc, elsebin/nvccunder/opt/cudaor/usr/local/cuda, else the first in an absolute entry of PATH, which it searches itself, andcudaRuntime, thelib64/libcudart_static.abeside that nvcc'sbinwhere there is one, which a configuration with CUDA sources links. In the Flatpak the host's/usrand/etcare under/run/host, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (HostPath); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root.SysrootStdModulepicks the std module source for a sysroot build by the sysroot's libc++ release.MingwSysrootsettles the mingw target's--sysroot: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's/usr, anything whoseinclude/hasfeatures.h), a view in the cache of its mingw-w64 directories, since clang would search itsinclude/andlib/too (issue #43).MingwViewToPrefixturns paths into the view back into paths into the prefix for messages.:ClangholdsConfiguration,Build(),VariantId(),ApplyStandardArgs,HostTarget, the CLI entry pointCrafter::Run, and the lint, test and script data types.:Platformruns commands, implementsLoadConfigurationsandLoadProject(compile and loadproject.cpp), the host PCM cache and#pragma crafter dependency.:Jobsis what build steps run on:JobPool, worker threads behind one queue, started as jobs need them up to a fixed number, withJobPool::Process()the pool of at most one worker per hardware thread thatBuild()andRunBuildCommanduse, andJobGroup, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and whatBuild()reports to it throughFail().:Interfaceand:Implementationmodel module units, their staleness checks and the jobs that compile them (Schedule).:Externalhandles git + cmake dependencies,GitProjectandLocalProject.:TestholdsAddTest,RunTestsandTestRunner, and starts the headless compositor of a test that setsTest::wayland(RunSingleTest), through:Platform'sBackgroundCommandandPrivateDirectory.:Lintis the lint/format driver plus the libclang token and AST layer.:Scriptis the driver behindcrafter-build run: it looks a name up in thescriptsof the configurations it is given, calls the callback and turns what it returns into the exit code.:Agentswrites a project's AGENTS.md from its AGENTS.template.md: it walks the dependenciescfg.dependencyNotesselects, reads each one'sAGENTS.consumer.mdand merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (LoadedProjectOfin:External,PragmaDependenciesin:Platform), because only the Configurations returned by a project file thatGitProjectorLocalProjectloaded have theirpathrebased.:Progressis console output.:Shadercompiles shaders through glslang.:Assetis the hook into Crafter.Asset.:Flatpakis an executable packaged as a Flatpak:FlatpakApp(app-id, runtime, permissions, desktop file, metainfo, icons, share entries, modules), the writer of itsfiles/, which becomes/appin the app's sandbox, and what makes the app of that forinstallandbundle: the host'sflatpak build-finish, which writes the metadata andexport/by flatpak's own rules, thenflatpak build-exportinto a repo, or flatpak-builder from a generated manifest when there are modules. It works on plain data;Build()and theInstallFlatpakAppandBundleFlatpakAppof:Clanggather it from the Configuration. The host's flatpak and flatpak-builder are reached throughRunHostFlatpakandRunHostFlatpakBuilderin:Platform.
Dev environment
The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop.
Prerequisites on Linux: clang (with libclang, which the AST lint rules load at runtime, and clang-scan-deps, which a build reads what each C++ source declares and imports with), lld, LLVM's llvm-ar and llvm-readelf, libc++ with its std module source (share/libc++/v1/std.cppm), cmake, git. crafter-build --version prints which compiler was resolved; CRAFTER_BUILD_LLVM_DIR points it at another LLVM prefix, and build.sh honours the same variable. Network access to forgejo.catcrafts.net and github.com is needed: loading project.cpp fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into ~/.cache/crafter.build/external/, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs git pull on them.
./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/
./bin/crafter-build # self-host build through project.cpp
Three things to know about this loop:
bin/crafter-buildis the bootstrap binary and the harness for every command below. The self-host build writes tobin/crafter.build-exe-<variant>/crafter-buildand does not replace it.- Changes under
implementations/are picked up by the self-host build and by the tests, which link the local library. Changes underinterfaces/are not: the harness compiles against the copies inshare/crafter-build/and the PCM cache built from them, so a new or changed declaration is invisible until you run./build.shagain. The symptom isuse of undeclared identifierfor the symbol you just added. A changed default member initialiser has no symptom at all:project.cppcompiles against the old one and quietly gets the old default, asproject.cpp's sibling loads do with a harness that predatesGitProjectSpec::args = ProjectArgs(). - A new exported symbol that a
project.cppreaches on its default path also needs./build.sh: the old binary does not export it, and loadingproject.cppfails with an undefined symbol.
./build.sh clones and builds glslang on first run and takes several minutes; later runs are faster. ./bin/crafter-build clean deletes bin/ and build/ without loading project.cpp. That takes bin/crafter-build itself with it, and build/flatpak, the state of the local Flatpak build (see "CI and publishing"): about 4 GB after a first run, and the next run flatpak rebuilds LLVM. Set CRAFTER_BUILD_HOME only when running a binary from outside this tree; CRAFTER_BUILD_MARCH and CRAFTER_BUILD_MTUNE default to native.
Build, test and style commands
./bin/crafter-build # build (self-host)
./bin/crafter-build test # build and run every self-test
./bin/crafter-build test 'Incremental*' # name glob
./bin/crafter-build test --list # enumerate without running
./bin/crafter-build test --jobs=1 --timeout=120
./bin/crafter-build lint # dry style gate, exit 1 on any finding
./bin/crafter-build format # apply the transform rules in place
./bin/crafter-build format --check # CI-style dry run
./bin/crafter-build run # list the scripts project.cpp defines
./bin/crafter-build run <name> [args...] # run one; everything after the name is the script's
./bin/crafter-build clean
Before you call a change done, all three must exit 0: format (then re-read your diff), lint, test. CI runs ./build.sh and crafter-build test for every release tag, every pull request into master and every manual run, and has no lint step, so lint is enforced only by you. Failed, crashed and timed-out tests leave their output in build/test-logs/<name>.log.
Testing instructions
Tests are declared, not discovered. Each one is a line in project.cpp:
cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() });
The source is tests/<Name>/main.cpp. The test inherits target, march and the rest from the root configuration and links the local crafter.build-lib, so the engine it calls is the one built from this checkout. A test that loads a project file, through LoadConfigurations, LoadProject, LocalProject, GitProject or Run(), also needs .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"), as the existing ones show. The declarations sit in an if (linuxTarget) block that matches any *-linux-gnu or *-linux-musl target: the suite is Linux-host only today.
A test is an ordinary int main(). Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout.
Conventions the existing tests follow:
- Open
main.cppwith a comment that states the behaviour under test and the failure it guards against.tests/CompilerWarning/main.cppshows the shape. - Collect failures with a
Check(cond, msg)helper that printsFAIL: ...to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. - Drive the engine in-process:
Build(cfg, depResults, depMutex),RunTests, the lint driver. Do not shell out tobin/crafter-buildand grep its stdout. - Fixtures under
tests/<Name>/fixture/are inputs. A test that edits or touches files first stages a copy underfs::temp_directory_path() / "crafter-build-<name>", after removing what an earlier run left there, which matters where the test runs by hand: undercrafter-build testthe copy is in the test's ownTMPDIR, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as*.infiles and copied over the original inside the staged copy. - Use a fresh
depResultsmap per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe.Build()itself is safe to call repeatedly on the sameConfiguration. - Set
cfg.pathbefore callingGetInterfacesAndImplementations, and spellcFilesas absolute paths: both resolve against the working directory, not the configuration. GetInterfacesAndImplementationsonly lists the sources. A configuration'sinterfacesandimplementations, its modules and units with what each imports, are made byBuild()from what it reads in them, so a test that looks at them builds first.- A test that needs the host's flatpak goes through
RunHostFlatpak, skips (77) with the reasonHostFlatpakUnavailablegives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a privateFLATPAK_USER_DIRunder its fixture'sbuild/, asFlatpakInstalldoes. It never runs an installed app:flatpak runmakes~/.var/app/<app-id>in the real home. - A test that packages a Flatpak stages the runtime: it writes a
.flatpak-infowhose[Application]group has aruntime=runtime/org.freedesktop.Sdk/x86_64/26.08line, as the parser takes only that group's, and pointsCRAFTER_BUILD_FLATPAK_INFOat it withsetenv, first thing inmain, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak;FlatpakNativestages an empty one for the native case.
A bug fix ships with a test that fails before the fix and passes after it, in its own test: commit when it documents the behaviour on its own.
Cross-target runs use test --target=<triple> with --runner=local or --runner=cmd:<wrapper> (wine, qemu-user, valgrind), or CRAFTER_BUILD_RUNNER_<TRIPLE> as the persistent form. A failed runner probe skips its tests rather than failing the suite.
Code style
project.cpp pulls in Crafter.LintRules through #pragma crafter dependency and applies its lite set, LintRules::AddLiteRules: the 8 rules that ask for different code, without the ones that only decide layout, whitespace and naming. lint reports all 8; format applies the two transforms among them, format-concat and fixed-width-types, and leaves everything else as written. Enforced:
- The first three lines of every source:
// SPDX-License-Identifier: LGPL-3.0-only,// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®, blank. Examples use MIT. enum classonly.std::printlninstead of iostream.std::formatinstead of string concatenation.std::int32_tand friends instead ofintorlong(exempt:main,argc/argv,extern "C"and foreign API signatures). Nochar*outside C interop.conston scalar locals that are never written;constexpron constants with constant initialisers.
Not checked, so match the surrounding code:
- Four-space indentation, no tabs, no trailing whitespace, final newline.
PascalCasefor types, functions, statics and constants;camelCasefor variables; a trailing_is allowed.- One declaration per statement. K&R braces.
if (x) return;on one line when it fits, and no hand-wrapping of a statement that fits on one line.if (andfor (with a space; no space before a call's(.
Suppress one finding with // lint-disable-next-line <rule> or a whole file with // lint-disable-file <rule>. Both are rare in this tree and need a reason.
Beyond the rules:
import std;everywhere; standard headers are never#included. C headers (clang-c/Index.h,dlfcn.h) go in the global module fragment aftermodule;.- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule.
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on
cfg.targetstrings at runtime, in the library as well as inproject.cppand tests. - A build step fails when its command exits nonzero, never because it printed. Use
RunBuildCommandorRunCommandChecked; warnings go toProgress::Diagnostic. - Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its
JobGroupinBuild(), after the jobs whose output it reads; run a step that stands by itself, as a link does, throughRunBuildCommand, which runs on a worker ofJobPool::Process()whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: aJobGroupmade on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group. - Every output path goes through
Configuration::BinDir(),BuildDir(),PcmDir()andProgramDir(). Hand-rolledpath / "bin" / ...clobbered variants before; do not add new ones.ProgramDir()is where an executable and the files it reads beside it land, its shaders,cfg.files, assets and what its dependencies forward, and the directory-rruns a host executable in and serves a browser build from (a Flatpak'scfg.flatpak.shareentries go tofiles/shareinstead);ExpectedOutput()names the executable in it. A Flatpak's bundle and the directoryinstallandbundlework in areFlatpakBundlePath()andFlatpakAppDir(). ObjectPath()names the object of a.cpp,.cor.cu, from where its source lies:objects/a/Thing_impl.oin the build directory fora/Thing.cpp. Do not name one from its source's file name: two sources of one name in different directories then share an object, each compiled over the other (issue #50). A step that takes every object of a configuration reads them from a response file, as the link does, and not from its command, which the system holds to a length.- A static library's archive and the list of objects a step reads are written under another name beside them and renamed into place (
WrittenBesideandMoveIntoPlaceinCrafter.Build-Clang.cpp), not removed first or written over where they lie: a link or archive step of another crafter-build may be reading them. Two crafter-builds can build a project loaded withGitProjectat once, in the clone the cache keeps for its source, and one then links against the library, or reads that list, while the other writes it. Write anything else such a step reads the same way. - Anything that changes what gets compiled or bundled belongs in
VariantId(). It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (StdPcmKey), uninterpreted project args, the toolchain (Toolchain::Key()), the GPU architecture (cudaArch), fornativecrafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists withCUDA_VISIBLE_DEVICESandCUDA_DEVICE_ORDER(Toolchain::cudaNativeKey, which is not what nvcc detects), and the nvcc (Toolchain::nvccStamp;Toolchain::Key()leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (FlatpakApp) is not hashed: it changesfiles/share, which the writer rewrites in place, and whatinstallandbundlefinish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them forinstallandbundleinFlatpakAppDir(), one per app, outside any variant's directory.
Design rules
These were decided deliberately. Do not undo them without the maintainer's say-so.
- Configuration is C++. No JSON, YAML, TOML or DSL for project, runner or lint configuration. Lint rules are C++ callbacks; there is no clang-format or clang-tidy integration and no separate "format rule" type. A rule that calls
ctx.SetContentis a transform, and that is the whole mechanism. - Per-project artifacts go in
<project>/buildand<project>/bin. Only cross-project things go in~/.cache/crafter.build/: the std PCM and Crafter.Build PCMs per target, march, toolchain and std module flags, external clones keyed by their spec hash, the mingw sysroot views keyed by prefix, and the locksinstallholds on the remotes of the user's installation (flatpak-remotes/, found byHOMEand never byXDG_CACHE_HOME, in the Flatpak as well, so that every crafter-build installing for the user takes the same one; that of a private installation,FLATPAK_USER_DIR, is kept in it). - Sources ship, PCMs build locally. The Flatpak installs
*.cppmunder/app/share/crafter-build/. Nothing target-baked ships except the executable and the toolchain beside it, and the executable is built for a portable-march. - crafter-build is a monolithic executable with
--export-dynamic.project.soresolvesCrafter::symbols from the running binary at dlopen time. There is no Windows host;x86_64-w64-mingw32is a cross-compile target for user projects only. - Convention over configuration. Lead with the zero-config path. Env var, then CLI flag, then full
project.cppare the escalation, not the entry point. - One skip mechanism (runner probe plus exit 77) and one
TestRunnershape (template fields with{bin},{bundle}and similar placeholders;Cmd(...)covers any wrapper). Do not add a special-case runner class or a hardcoded "skip on this OS" branch. - The house-style rules stay in their own repo. They are not library API of crafter-build and are not forced on downstream projects.
- Fix warts inline; do not stack workarounds. The previous version of this tool died of accumulated hacks. If a change needs a shortcut, say so in its commit message rather than hiding it.
project.cppkeeps the library/executable split.crafter.build-libowns the sources, dependencies and glslang;crafter.build-exeismain.cppplus link flags.- Host-tooling builds (the target of a
#pragma crafter dependency) get-fPICand the host triple scoped to that build. Keep it scoped.
Commit and push guidelines
- Branch from
master; issue work usesclaude/issue-<n>branch names. Once the owner approves its frozen hash, a range goes straight tomasteron the project's Forgejo atforgejo.catcrafts.net/Catcrafts/Crafter.Build, as a fast-forward push with no merge commit and no pull request; open a pull request againstmasteronly when the owner asks for one. Ifmasterhas moved since the freeze, rebase onto it, then freeze and review the rebased range again. Pushes go over SSH; HTTPS push is disabled on the server. - Subject line:
type(scope): imperative summary, withfeat,fix,refactor,docsortest; the scope (lint,incremental, ...) is optional. Body: what was wrong, why, and why the fix has this shape, wrapped at about 75 columns. Readgit logfor the voice. - Separate commits for the fix, its test and the README change when each stands on its own.
- Update the README in the same push when user-visible behaviour changes.
format,lintandtestgreen before pushing. CI builds the Flatpak and runs the suite inside it for every release tag, every pull request intomasterand every manual run. Without a pull request, CI does not run on a range before it reachesmasterunless someone starts it by hand (workflow_dispatch), so the review's gate0, the commands in.review-gates/config.json, is the check before the push.- Every push to
masteris a release, made by the signed tag pushed with it (see "CI and publishing"). Every pushed range adds a<release>entry for its version at the top ofpackaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml, in a commit of its own (docs(packaging): add the X.Y.Z release entry), dated the day of the push in UTC. Its notes have up to three sections,<p>New</p>,<p>Fixes</p>and<p>Breaking</p>in that order, each followed by a<ul>of its items, the most important first, and nothing after the last section. The version follows from them: a Breaking section makes it a major, New items a minor, and Fixes alone a patch. Once the owner has approved the frozen hash, the commitmasteris to receive gets the signed tag of that version, made locally, and both go out in one push:git tag -s X.Y.Z -m 'crafter-build X.Y.Z', thengit push --atomic origin HEAD:master X.Y.Z. That commit is the range's last one, or, when the owner asks for a pull request instead, the merge of the reviewed branch intomaster. - Every push of new commits goes through Crafter.Review's pre-push review first, and goes out only once the owner approves the frozen hash. Run
flatpak run net.catcrafts.CrafterReview initonce in a fresh checkout or worktree: it writes the/prepushskill that drives the review, and the skill stays untracked.freezerefuses merge commits: a range reachesmasteras a fast-forward, and when the owner asks for a pull request instead, the merge of the reviewed branch intomasteris pushed without a freeze of its own. - Every commit of a pushed range is GPG-signed, has
jorijnvdgraaf@catcrafts.netas its author and committer, and carries no AI attribution trailer in its message, neitherCo-Authored-By:norAssisted-by:.freezerefuses a range with a commit that breaks any of these (requireSigned,authorsandaiTrailersin.review-gates/config.json). - Never commit
bin/,build/,share/crafter-build/,lib/*.a,AGENTS.mdor fixture build outputs (all gitignored), and never edit the vendored files inlib/. - Keep
CRAFTER_BUILD_MARCH=x86-64-v2in the manifest for the shipped binary: it has to run on any x86_64 machine. User projects still default tonative.
Security considerations
project.cppis compiled and loaded into the crafter-build process, and everyGitProject,#pragma crafter dependencyandExternalDependencyclones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin withcommitwhen adding anything else, and whenever reproducibility matters.- Unpinned dependencies
git pullon every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. --runner=cmd:<command>executes the named wrapper around every test binary. Wrappers come from--runner=orCRAFTER_BUILD_RUNNER_*; do not hardcode hosts, wrappers or credentials inproject.cppor tests.--compositor=andCRAFTER_BUILD_COMPOSITORname the command that crafter-build runs throughshbeside every test that setsTest::wayland, unless they namehost; the default is the weston onPATH.crafter-build run <name>executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's:runleaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (KeptBy); keep it that way.- The linter loads
libclangat runtime by name.CRAFTER_BUILD_LIBCLANGpins an exact path and must fail loudly when wrong, never fall back to another library. - crafter-build's Flatpak has
--talk-name=org.freedesktop.Flatpak, and the permission is the whole sandbox's: anything that runs there can run commands on the host throughflatpak-spawn --host. That is every process of crafter-build's sandbox: crafter-build itself, everyproject.cppit loads with its scripts, the builds of its dependencies and pragma dependencies, the programs-randteststart, and whateverflatpak run --command=andflatpak enterstart in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only throughHostCommandin:Platform, which builds the command lines ofRunHostFlatpak,RunHostFlatpakBuilderandHostFlatpakUnavailable's probes, for the host'sflatpakandflatpak-builderbehindinstallandbundle; add no other host command to crafter-build.RunHostFlatpakis exported for the tests, and gives aproject.cppnothing the sandbox does not. The trust model allows the permission because--filesystem=hostalready lets sandboxed code write~/.bashrc,~/.config/autostartand~/.config/systemd/user: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. - CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it.
- Tests write only under
fs::temp_directory_path()and the fixture's ownbin/andbuild/, and in the caches of what they run, unless they pointXDG_CACHE_HOMEelsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make:tests/HeadlessCompositor, which makes its compositors' directories in a directory of its own in$XDG_RUNTIME_DIR, or in/tmpwhen that is not a directory, and has one made in/tmpitself, as crafter-build makes it where there is no$XDG_RUNTIME_DIR, because a socket's path holds 107 bytes and a temp directory's path can use them up, and a later run removes what a killed run of it left once that has not changed for a minute (PrivateDirectory); andtests/HostFlatpak, which in the Flatpak makes its two projects in the sandbox's/tmp, the place it asks the host about, under fixed names, so that its next run that makes them removes what a killed one left.
CI and publishing
.forgejo/workflows/ci.yaml runs on the crafter-flatpak runner label: a dedicated privileged forgejo-runner on the Hetzner box (forgejo-runner-flatpak.service, config /etc/forgejo-runner/config-flatpak.yaml), registered to this repository only and the only runner with that label. It is privileged because bubblewrap inside the job container needs it, and no other repository's job runs on it. Its config allows four volumes, which the workflow mounts: crafter-flatpak-system (the Sdk install at /var/lib/flatpak), crafter-flatpak-builder (flatpak-builder state and ccache, which later runs reuse: flatpak-builder builds a module again when its sources or its build-commands change, and every module after it with it, so a new version of swig or libedit, which come before LLVM, also rebuilds the LLVM and WASI modules), /var/www/flatpak, the web root Caddy serves as https://flatpak.catcrafts.net/, and /etc/crafter-flatpak, which holds the repo signing key (signing-key.asc, no passphrase, and key-id), generated once on the host and mounted read-only into the job; nothing is stored in the forge. The web root and the key are not this runner's alone: the organisation-wide flatpak runner (forgejo-runner-org-flatpak.service), which serves every Catcrafts repository, mounts both for Crafter.Review's publish job, and the volumes a runner allows (valid_volumes in its config) are open to every job it runs, so a job of any Catcrafts repository that runs there can mount them as well. The live repo at /var/www/flatpak/repo is canonical; builds are promoted into it with flatpak build-commit-from, never built into it. Crafter.Review's workflow publishes into the same repo, and each workflow holds an flock on /var/www/flatpak/.publish.lock while it commits and updates the summary.
Keep the label unique to that runner. Plain flatpak belongs to the organisation-wide runner. When this job still asked for flatpak and that runner took it (runs #368 and #370, in October 2026), the runner allowed none of the job's volumes, and flatpak-builder stopped with The state dir (/root/.cache/flatpak-builder) is not on the same filesystem as the target dir; the top of such a job's log shows which runner took it and lists every volume it ignored.
The key is made once, as root on the runner host, and the step fails with a message pointing here when it is missing:
install -d -m 700 /etc/crafter-flatpak/gnupg && export GNUPGHOME=/etc/crafter-flatpak/gnupg
gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key 'Catcrafts Flatpak Repository <flatpak@catcrafts.net>' ed25519 sign never
KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5; exit}')
gpg --batch --pinentry-mode loopback --passphrase '' --export-secret-keys --armor "$KEYID" > /etc/crafter-flatpak/signing-key.asc
printf '%s\n' "$KEYID" > /etc/crafter-flatpak/key-id && chmod 600 /etc/crafter-flatpak/signing-key.asc /etc/crafter-flatpak/key-id
A release is a tag X.Y.Z, annotated and signed, pushed with the master it releases; a push to master without one runs nothing. Before building, every run renders the release notes from the newest <release> entry in packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml, and stops when the metainfo does not parse or the notes come out empty. A tag run also checks that Forgejo verifies the tag as signed by the address the workflow's RELEASE_SIGNER names, that the tag's commit is on master, that its version has the form X.Y.Z and is newer than every release the forge has published, its own included, and that the newest entry is that version. Once the build and the suite inside it pass, the tag run publishes stable and creates the release, with the notes, the bundle, the .flatpakref and SHA256SUMS attached. Release runs queue one behind another, and a failed one can be re-run while no newer release exists, once a release it left half made is deleted; when the fix needs a commit of its own, that push is the next version's release. Pull requests and manual runs publish nothing. The beta branch, which every push to master used to go to, gets no more builds: the publish step marks its last build end-of-life, once, and the next flatpak update of a beta installation prints the reason.
Local builds are two scripts in project.cpp. Run them with the native binary: they run flatpak and flatpak-builder themselves, which the Flatpak build of crafter-build has none of. crafter-build's own install and bundle reach the host's through RunHostFlatpak and RunHostFlatpakBuilder instead.
./bin/crafter-build run flatpak [--jobs=<N>] # build the Flatpak, then print its version from inside the sandbox
./bin/crafter-build run install # install that build as branch `local` and make it current
run flatpak needs flatpak-builder or the org.flatpak.Builder app, and the Sdk (flatpak install flathub org.freedesktop.Sdk//26.08). It builds the working tree, uncommitted changes included, runs the whole suite inside the sandbox and reports version 0.0.0-dev. Its state is build/flatpak/ (state/, repo/, build-dir/). The first run builds every module, LLVM with lldb, the WASI sysroot and the Vulkan validation layer among them, in about 30 minutes with 56 CPU threads; later runs rebuild only the crafter-build module while the manifest is unchanged, a few minutes, because flatpak-builder never caches a type: dir source. The checkout must not be under /tmp, which org.flatpak.Builder cannot see. Use it for anything toolchain-sensitive: the native loop compiles with the distro's clang and the Flatpak with its bundled LLVM, and the two can be a major version apart.
run install does not build; it installs what run flatpak last exported. It points the user remote crafter-build-local at build/flatpak/repo, installs net.catcrafts.CrafterBuild//local from it next to whichever published branch is installed, and makes it the branch flatpak run net.catcrafts.CrafterBuild starts. flatpak make-current --user net.catcrafts.CrafterBuild <branch> switches back. Before crafter-build clean, or before deleting the checkout, run flatpak uninstall --user net.catcrafts.CrafterBuild//local and flatpak remote-delete --user crafter-build-local; otherwise the remote is left pointing at a repo that is gone.
Gotchas
- A new partition is listed in four places, in import order:
PARTITIONSinbuild.sh,CrafterBuildModulesinCrafter.Build-Platform.cpp, both arrays inproject.cpp, and the umbrellaCrafter.Build.cppm. Then./build.sh. - A
#pragma crafter dependencytarget is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. - A host-tooling library such as Crafter.LintRules may
import Crafter.Build;without declaring it as a dependency, because loading a project file fills the cache it resolves from. Listing Crafter.Build in itscfg.dependencieswould clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behindIsTopLevelProject(): without the guard, crafter-build loading the library as a dependency would load its ownproject.cppagain through the test'sGitProjectand hit the cycle guard. crafter-build cleanleaves a pragma dependency's build alone; it lives with the clone in the cache.- A project file returns one configuration from
CrafterBuildProjector several fromCrafterBuildConfigurations, andCrafter::Runworks on the listLoadConfigurationsgives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's:testandrunleave out a configuration that another project's file returned and this one returns in turn, whichLoadedProjectOftells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (KeptBy): one the loader took down when that project's file was loaded, among what the configurations the file returned led to throughdependenciesandtests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. - The limit of as many steps at once as there are hardware threads holds for what runs on
JobPool::Process(): the jobsBuild()adds and the commands ofRunBuildCommand. Among what runs outside it: anExternalDependency'scmake --build, whichBuildCMakegives--parallel <hardware threads>of its own; the testsRunTestsruns,--jobs=of them at once on threads of its own, while other tests may still be building; the Crafter.Build modulesEnsureCrafterBuildPcmsprecompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. - An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done.
Checkreads staleness off the BMI; the object isSchedule's to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. Build()reads what each.cppmand.cppdeclares and imports with clang-scan-deps (ReadSourcesinCrafter.Build-Clang.cpp) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, soDuplicateModuleErrorandImportCycleErrorrefuse a graph there, after the dependencies are built and before any.cppmor.cppof the configuration is compiled; its.cand.cusources, which compile while the dependencies are built, may have been by then. A scan is kept in the build directory as an object is, inscans/or, for a source outsidecfg.path, inscans-outside/, as JSON holding the compile command it was taken for and what clang-scan-deps wrote, with a dependency file beside it, and taken again when that command differs, when the source or a file the dependency file lists is newer, and when it cannot be read; clang-scan-deps is given that command with its first word made the compiler where clang started with that command takes itself to be: the directory it is installed in, or, for a command whose last of-canonical-prefixesand-no-canonical-prefixesis-no-canonical-prefixes, that of the compiler as written (ScannedAs,Toolchain::InstalledClangxx). ABuild()makes its own configuration's modules and units, never a dependency's: those are the dependency's ownBuild()'s to make, and the builds of other configurations built on it read them, through the pass record (BuildResult::built): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build.- Units see a std module rebuilt in place, because their depfiles list the BMIs they import (
-fmodule-file-deps), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes intoStdPcmFlags, whichBuildStdPcmcompiles with andStdPcmKeyhashes.VariantId()hashesStdPcmKey, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - A CMake external whose recorded configure inputs (
<build>/.crafter-options) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or--sysrootcompiled, and the check results it cached. - The bootstrap binary is compiled without
CRAFTER_BUILD_HAS_ASSET, socfg.assetsonly works in the self-hosted binary. What an asset is compressed to is decided in one place,CompressedAssetNameinCrafter.Build-Clang.cpp, which an executable's own assets, the ones its dependencies forward and the browser runtime'sfiles.jsonall use; a Flatpak'sfiles/binkeeps what those copies record as placed.CompressAssetinCrafter.Build-Asset.cppdoes the compressing and has to load every extension that function maps. - A warning is printed only when its unit actually recompiles. A build with nothing to do is silent, which is not evidence that a warning is gone.
RunCommandWithTimeoutruns its command undertimeout, which can only start programs, so a shell builtin such ascommand -vfails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe throughRunCommandChecked, which goes throughsh, orstd::systemin a test.- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under
share/crafter-build/libc++-modules/<major>/, onelibcxx-<major>-modulesmanifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand undershare/crafter-build/to test against a foreign sysroot. - The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the
llvmmodule, withLLDB_ENABLE_PYTHON,LIBEDIT,CURSES,LIBXML2andLZMAset ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and theswigandlibeditmodules come before it. The Khronos validation layer is thevulkan-validation-layersmodule plus four modules before it, build-only except for SPIRV-Tools' programs (spirv-valand the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: whenruntime-versionmoves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release'sscripts/known_good.json. - The Flatpak carries weston for the tests that set
Test::wayland: thelibevdev,libinput,libdisplay-infoandwestonmodules, just beforecrafter-build, so that bumping them rebuilds only them and crafter-build. weston's frontend links the first three whatever the backend, so they ship. weston is configured with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. libinput is agitsource pinned by commit, since its 1.32.0 release has no tarball attached.tests/HeadlessCompositorstands in a fake compositor, so the suite needs no weston: only a project's own tests that setTest::waylandrun the real one. - The wasm compile flags live in one place,
WasmBaselineFlagsinCrafter.Build-Clang.cppm: the std module and every unit have to agree on them, andVariantId()and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot'slib/<triple>/eh/(wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with theWasmBaselineProbesnamed invariants.json. WasiBrowserRuntimeExitrunswasi-runtime/runtime.jsunder node and skips where there is none. The Flatpak has no node, so CI never runs it: after touchingruntime.js, run the suite in the native loop with node onPATH.CudaCompilebuilds with a real CUDA toolkit whoselib64besidebin/nvccholdslibcudart_static.a, and skips everywhere else, and nothing in CI installs one: after touching howcfg.cudais compiled, or how the CUDA runtime is linked and handed on throughBuildResult::runtimeLibs, run it in the native loop on a machine with such a toolkit, as Arch's/opt/cudais. Where nvcc is looked for,/run/hostand its links included, isToolchainResolve's to check, on staged directories, so that one runs everywhere, and so is whether thelib64beside it holds the static runtime.CudaMissingchecks what a build with a.cusays when no nvcc is found, and needs no toolkit either.VariantId()names the output directory, so CI globsbin/crafter.build-exe-<target>-<march>-*/rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay inbin/andbuild/untilclean, and such a glob matches both.- AGENTS.md is build output: the self-host build and
testwrite it fromAGENTS.template.md, with theAGENTS.consumer.mdof each dependency that ships one (Crafter.Math, today) merged in, and it is gitignored. Edit the template; an edit made in AGENTS.md is gone after the next build. A fresh clone or worktree has no AGENTS.md until its first./bin/crafter-buildortest, since./build.shdoes not write it. A harness from before the template (3.0.0 and older) never creates one and keeps its section in one it finds; the next build with a current harness writes it over.