quern

quern is a reusable Go build engine for Swift applications on Apple platforms. Projects supply a JSON recipe describing packages, generators, native tools and bundle assembly. SwiftPM evaluates manifests; compilation invokes swiftc and clang directly. Sources stay in their worktree, and completed actions are shared through a content cache across builds and worktrees.

Build and install

Use macOS and Go at the version declared in go.mod to build quern. Swift builds require a full Xcode installation selected with xcode-select. Recipes may require additional tools on their declared PATH. The cache and delivery directories must support APFS cloning and macOS atomic directory exchange.

go vet ./...
go build -trimpath -o /tmp/quern ./cmd/quern
go install ./cmd/quern

go install writes to GOBIN, or $(go env GOPATH)/bin when unset. Put that directory on PATH.

With quern installed and its cache configured, run these from this repository:

quern -output /tmp/quern-build  # writes /tmp/quern-build/quern
quern vet                     # checks the Go packages under cmd and internal
quern -all -background        # warms both actions using byre's background CPU leases

Use

Set the shared cache budget once, then run in a project's recipe directory. Budgets count physical file data, deduplicating shared APFS clone ranges. For example, to give the default cache a 1 TiB budget:

quern set cache-limit 1099511627776
quern set -cache /path/to/cache cache-limit 1099511627776

quern set creates the cache directory if needed and atomically saves its config.json ({"cache_limit":1099511627776}). Builds only read this setting; there is no build flag that changes it. If the budget is missing or invalid, use quern set with the same cache directory to set it. quern has no compiled-in byte budget.

quern -output /tmp/my-app default
quern -recipe /path/to/quern.json -jobs 4 mac-bundle tests
quern tests
quern -all
quern -action test/combat -action test/hands
quern -resolve mac
quern -update mac
quern -generate docs
quern -check docs
quern -sandbox tests
quern -rerun -action test/combat
quern -gc
quern stats
quern stats -since 168h
quern stats -cache /path/to/cache -since 0 -json

quern stats shows live physical cache usage against the saved budget, followed by storage, build and cache activity by project, and daily activity in UTC. Storage rows sort by physical size, and project activity rows sort by build count, largest first with ties sorted by name. Daily rows cover days with recorded activity. The default activity window is 24h. Use -since 0 to include activity from all retained logs. A log can be retained without a recorded invocation event if the process stopped before writing its first complete record. Use -json for structured output with live measurements in usage and the last GC snapshot in collection. Stats uses the same physical-extents scan as GC without collecting or writing to the cache. After setting the budget for a new cache, run a build or quern -gc on that cache before running stats. Each report scans the cache again, so runtime grows with the cache's file and extent count. Stats can scan alongside builds and measure the cache while builds publish results. The measurement can wait for cache maintenance that needs exclusive access. Stats shows its phases on standard error as described for -gc below. Physical size, recent-use working sets and producing-project sizes have a live measurement time, with shared ranges counted once. Last collection time and eviction counts come from gc.json. Use quern -gc with the same -cache setting to request collection. The report lists missing required action results and their dependents without failing stats. In JSON, each usage.missing_artifacts entry gives the missing key as artifact and the dependent key as result. Physical size still counts every scanned file. Retained dependent results count toward the 24-hour and 48-hour usage totals according to their last use. -since controls build and cache activity only. Stats does not repair or remove inconsistent cache entries. The report shows the quern -gc -cache command for the affected cache. That command invalidates the dependent results, including transitive dependents, even when the cache is below its budget. Invalidation removes the action links so later builds can rebuild those results. Their objects stay in the cache until evicted. Running invocations keep their leased objects until they release them.

Build activity includes ordinary builds, -all, -generate and -check. Build counts include successes and failures, and builds per day use the selected window. Unfinished builds started within the window and have no terminal record. They may be active or interrupted. The action hit rate divides hits by the sum of hits and misses for build actions, including decisions from unfinished builds. Misses include cache: false actions, forced test reruns and sandboxed replacements. Cache activity counts published actions and evicted entries. Actions run by -resolve and -update count toward publications but are excluded from hits and misses. Logical output bytes include reused data. The Physical size evicted column counts bytes whose last cache reference was evicted. Files outside the cache and snapshots may still reference those bytes. All activity is limited to retained logs.

Builds group by recorded project identity. By default, temporary recipes and Git worktrees with the same Git origin group together. Equivalent SSH and HTTPS origins such as git@g.fc.run:ai/quern.git and https://g.fc.run/ai/quern.git become g.fc.run/ai/quern. Hostnames are case insensitive; repository paths retain their case, and nonstandard ports remain distinct. A recipe can declare "project": "https://g.fc.run/ai/quern.git" to preserve provenance in source archives without .git. -project name overrides both the recipe and invoking repository. Recipe operations fail before planning if neither explicit project metadata nor a Git origin supplies an identity. Whitespace-only project metadata is rejected. Standalone GC and publish operations use (shared) without an explicit project. Stats uses the recorded project identity; it does not inspect old working directories or infer missing fields. Logs without recorded provenance, publication byte counts or physical eviction accounting fail the report. Physical size assigns compiler state and ranges used by multiple projects to (shared) and puts invocation logs, failure data, and other bytes without an assigned producing project under (unattributed). Eviction activity assigns blobs, compiler state, failure data and logs to (shared).

Clean old invocation logs with an explicit cutoff. Preview the selection first:

quern clean-records -before 2026-11-16T00:00:00Z -dry-run
quern clean-records -before 2026-11-16T00:00:00Z
quern clean-records -cache /path/to/cache -before 2026-11-16T00:00:00Z -dry-run -json

Cleanup removes logs last modified before the cutoff and drops cache-miss history entries for objects that no longer exist. It skips active leased logs and retains cached build artifacts. Removed logs include their diagnostic evidence and no longer contribute to stats. The reported log size (log_bytes in JSON) sums file lengths. -json also includes selected paths and counts. There is no automatic age cutoff. If cleanup stops with an error, it may already have removed some logs. Check the exit status before treating the reported counts as final, including with -json.

Build usage is quern [flags] [targets ...]. Put all flags before target names. If the first target shares a name with a subcommand (set, stats, or clean-records), put -- before that target. For example, quern -- stats builds the stats target. Any number of named targets shares one build graph: shared dependencies execute once and freshness checks are combined. By default, quern publishes outputs groups keyed by the selected target names or explicit -action IDs. With no operation or action selected and no target names, quern builds default. Repeating a target has no additional effect. Unknown targets fail the invocation. Choose one of -all, -publish, -gc, -gc-if-due, -resolve, -update, -generate, or -check when running a separate operation. Each is exclusive with positional targets and -action. Conflicts are rejected before cache setup or recipe planning.

The former -target NAME flag is removed. For example, quern -target mac-bundle -jobs 4 becomes quern -jobs 4 mac-bundle. Selection-aware generators must read the targets array instead of the former target string in ${selection}. Invocation metrics also record targets.

Flag Meaning
-verbose Show detailed console diagnostics instead of live progress.
-recipe path Recipe path; defaults to quern.json in the working directory.
-project identity Project identity recorded for statistics; overrides recipe project and the invoking repository's origin.
-all Build and test all eligible actions, including conditional fragments and all configured package targets. Exclude cache:false actions, actions with a skip note, and their transitive dependents. Check generated sets referenced by targets and fail on stale placements, skipping sets whose checks require excluded actions. Keep results in cache without applying outputs placements or writing generated sources. Cannot combine with positional targets, -action, -output, or another operation flag.
-param name=value Pass name=value to recipe generators through ${selection}; repeatable, with unique names. Values are strings.
-action ID Select this action ID instead of a target; repeatable. Apply the recipe outputs group keyed by this ID unless -output is set. Cannot be combined with positional targets.
-cache directory Shared cache; defaults to quern/v1 inside Go's user cache directory (~/Library/Caches/quern/v1 on macOS).
-jobs count Process/compiler job budget for builds, including build-time package planning. Defaults to 4. Concurrent builds have separate budgets. -resolve and -update do not use this flag.
-priority Request priority for every byre lease in this invocation. Defaults to false and omits the priority field from requests; enabling it requires byre support for priority requests.
-background Request every byre lease in this invocation as background class. The byre server must support background lease requests. It grants them only while the resource has room and no normal or priority request waits for it. Each lease is returned after its action instead of passing to the next one. Cannot combine with -priority. quern -all -background keeps the cache warm on idle capacity. It requires the recipe's Git checkout to contain the local default branch tip (branch name from origin/HEAD) and exits with status 1 if the tip changes, including during a lease wait.
-output directory Replace the entire destination atomically. Builds place owner-writable copies of explicitly selected action outputs there and skip recipe output groups. Actions reached only through dependencies or generated-set checks contribute no outputs. With -publish, the prepared directory moves there. Cannot combine with -all, -generate, or -check.
-whole-module Enable whole-module optimization for package profiles.
-resolve profile Create Package.resolved or reconcile its pins for a manifest-backed package profile declared in the main recipe, without compiling.
-update profile Refresh dependency pins in Package.resolved for a manifest-backed package profile declared in the main recipe, using its resolution policy.
-gc Run cache collection in the foreground regardless of the automatic interval. Invalidate results that require missing action results, reset oversized idle Swift compiler namespaces, and retire oversized ones still in use so later builds start a new generation. Evict least-recently-used entries if the cache exceeds its budget. Skip if another collector is running.
-gc-if-due Run cache collection in the foreground if it is due and no collector is running. This is also the mode used by the separate process that builds start for automatic collection.
-gc-interval duration Minimum time since the last completed collection, including an explicit -gc, before automatic collection is due. Defaults to 24h. 0 makes every automatic collection attempt due.
-publish directory Atomically move this prepared directory to -output, without building.
-generate set Build a named generated set and update its stale placements.
-check set Build the actions needed to check a named generated set. Fail if any placement is stale and leave all placement destinations unchanged.
-sandbox Restrict reads under recipe roots to keyed inputs and resolved tools during build actions, including package compilation. Package-planning actions are exempt. Keep the cache outside recipe roots so actions can read cached dependencies and staged outputs. Directory and glob inputs honor their exclusions. Allow listing the immediate parent folders of readable inputs and tools for discovery. Results that depend on directory membership must declare it, and keyed glob matches reach commands through ${inputs:name}. Covered actions that ran unsandboxed execute again.
-rerun Execute every test reached by the build, including test dependencies, even when it has a cached pass. A new pass replaces the old one for the same key. A failed replacement can invalidate the cached pass. See Reruns.
-notify glob Print an OSC 9 notification (ESC ]9;quern: <id> succeeded or failed, then BEL) to the controlling terminal when an action whose ID matches this glob completes, including cache hits; repeatable. Actions blocked when the byre lease connection retry window expires send no notification. * and ? do not match / in IDs. Writes to /dev/tty, so redirecting quern's output does not suppress it. Fails without a controlling terminal or with -publish, -gc, -gc-if-due, -resolve or -update.

By default, stderr shows live progress with completed actions out of all actions discovered so far, cache hit rate, unsuccessful actions, and elapsed time on the first row. Up to five active activities appear below it, longest-running first, each with its phase, action and time in that stage. Activities without a detail row are counted by phase on the rows below it. Short terminals reduce the number of detail and count rows to fit. Activities include hashing, cache lookup, preparation, package planning commands, preconditions, execution, testing, publication, failure handling, cache invalidation, resolution, validation, generated set checks and updates, and output delivery. A freshness check names its generated set, and -output delivery names its destination directory. Dependency waits, overall planning, and scheduler waits appear only in the activity counts while work is active. When no work is active, the oldest activity gets its own detail row. waiting for local job slots refers to the invocation's -jobs budget, waiting for byre lease refers to machine-wide admission, and waiting for another invocation means another quern invocation is filling the cache for the same action key. Narrow terminals truncate individual rows that still exceed the width. The total includes dependencies and grows as fragment and package planning discovers actions. The unsuccessful count is part of the completed count and includes actions blocked by dependency or lease errors and canceled actions. Cache hit rate is hits divided by the sum of hits and misses. Fresh executions from cache:false, forced test reruns, and sandboxed replacements count as misses. Terminal progress uses green completion counts, cyan hit rates, and red nonzero unsuccessful counts. Set NO_COLOR to disable colors. With nonterminal stderr or TERM=dumb, the progress display prints a single plain summary at completion. Live progress still runs when only stdout is redirected. When stderr is not a terminal, the invocation log records build progress events with integer completed and total fields, including with -verbose. The first event has completed: 0. quern emits another event on each action completion and whenever further discovery adds actions to the total. Without -verbose, -gc and -gc-if-due show collection phases instead of action progress. On a terminal one updating line names the current phase and total elapsed time. It shows work done, adding the total and percentage when the phase has a known total. Each phase leaves a quern -gc: <phase> <progress> in <duration> line when it ends, with quern -gc-if-due: as the prefix for that flag. With nonterminal stderr only those progress lines are printed. The scan counts cache entries, the Swift compiler namespace check reports physical bytes removed from the cache footprint, eviction counts physical bytes against the amount over budget, and removal counts evicted entries. The collector can spend time waiting for exclusive access to cache metadata while builds, stats, or other cache maintenance use it. The invocation log records a phase completed event as each phase ends, including the phase in progress if collection fails. It records a phase progress event every minute during a phase. Both events include phase, done, total (0 when unknown), unit (count or bytes) and duration_ns in that phase. Warnings, errors, and failed command output remain visible above the progress line. By default a failed action or test starts with its name and error, followed by indented command output. Terminal log lines use cyan for info, yellow for warnings, and red for errors. Redirected stderr and TERM=dumb use plain text. Use -verbose for detailed log/slog text diagnostics, including ordinary output from non-test commands, instead of live progress. Full diagnostics are always retained in the JSONL log. Successful builds, -all, -generate, and -check write a build results record to the invocation log. With -verbose or when stdout is redirected or piped, quern also writes that record as one JSON line to stdout. The results field maps selected action IDs to their action key, their cached output directory and sandboxed when they ran sandboxed, including producers or verify actions selected through generated-set checks. Actions built only as dependencies are omitted. Each output's path, digest and mode stay in result.json, a sibling of the cached out/ directory named by the output field, so a large bundle's record stays a few kilobytes instead of a megabyte. The optional tests field lists every test the build reached, including dependencies. See Tests for when a failed invocation writes this record. The same record includes metrics (timings in nanoseconds, action hits/misses, scheduler wait, lease wait, Swift job/CAS statistics and collection statistics) and log (the absolute JSONL path). jq -r '.log' extracts the path to the full diagnostics. Builds that check for automatic collection report the last saved cache measurement and exit independently of the collector. The collector writes its own invocation log under the cache's logs/. Record attributes ending in _ns are integer nanoseconds in JSON; the text console prints the same durations with units, such as duration_ns=7.3ms. Command output redirected with the recipe's stdout field goes directly to the named file. quern -h lists the subcommands and build flags. Use quern <command> -h for a subcommand's flags.

Recipe operations, -publish, and cache collection stream their events to a unique JSONL file under <cache>/logs/. The start and terminal records include the log path. Failures and interrupted builds retain the diagnostics already written even if an action never publishes a cache object. The set, stats, and clean-records subcommands do not create invocation logs. See operations and design for retention and audit fields.

Recipe format

Write the recipe as a JSON object. quern rejects unknown fields in the object. Relative root paths resolve against the recipe's directory. Save this minimal recipe as quern.json:

{
  "project": "example",
  "roots": {"project": "."},
  "environment": {"PATH": "/usr/bin:/bin"},
  "actions": [
    {
      "id": "copy",
      "inputs": [{"root": "project", "path": "message.txt"}],
      "commands": [
        {"args": ["/bin/cp", "${root:project}/message.txt", "${out}/message.txt"]}
      ],
      "outputs": ["message.txt"]
    }
  ],
  "targets": {"default": ["copy"]}
}

After setting the cache budget, create message.txt beside the recipe and run quern -output ./result from that directory. The build copies the file to result/message.txt. The project field supplies the identity in a directory without a Git origin.

Top-level fields:

Field Meaning
project Optional Git remote or project name for statistics; survives source archiving and does not affect action keys.
roots Map of logical names to source directories.
environment Base environment map for commands. For omitted keys, quern inherits nonempty PATH, HOME, TMPDIR, and DEVELOPER_DIR values. Declare other variables the recipe needs here.
actions Explicit action declarations, described below.
targets Map of target names to lists of action IDs and generated:<set> freshness checks.
packages Optional Swift package profiles that add actions to the graph.
generated Optional map of set names to checked-in placements of action outputs, described below.
lease Optional byre lease for actions that run a precondition or commands, described under Leases.
fragments Optional selected action outputs that extend the recipe, described under Fragments.
revisions Named source revision inputs, described under Source revisions.
outputs Default output groups keyed by target name or action ID, described under Default outputs.
test_timeout Optional positive duration for every test without its own timeout, described under Tests.

Commands receive the recipe environment plus their own env map. quern also imports PATH, HOME, TMPDIR and DEVELOPER_DIR from its process when absent from the recipe. Other process variables must be declared explicitly. The recipe environment's TMPDIR, imported or declared, reaches commands and ${TMPDIR} expansions. Its value is omitted from the keyed environment, so invocations with different temporary directories can share results. quern has no dedicated environment variables; use -jobs for the engine's job budget.

Actions

An action has a unique id. An action can use files to produce outputs without running commands. A cacheable non-test action must declare at least one path in outputs, relative to its private output directory. Commands run in order. Each command has an args array (the executable first), optional dir and env, and an optional stdout file path. Relative stdout paths resolve against the directory where quern was invoked. To cache the file, write it under ${out} and include it in the action's outputs. quern resolves bare executable names in args[0] and tools using the recipe's PATH. A command's env.PATH applies once the resolved tool runs. Relative entries in the recipe's PATH are relative to the invocation directory. An executable path such as ./tool resolves against the command's working directory. Relative paths in tools resolve against the invocation directory. The default working directory is the action's output directory. Direct executables must exist before cache lookup. Arguments are passed directly; invoke a shell explicitly when needed. If a command fails, the action error identifies the zero-based commands entry or the precondition. Errors binding a direct executable identify its args[0] or tools entry.

Optional action fields:

Field Meaning
inputs Input selections with root, path, optional name, exclude patterns, glob and members. glob expands the input path and requires at least one match before exclusions. members asserts the exact list of scanned paths, as described below. name makes the selected paths available to commands as ${inputs:name}. Exclusions support ** across directories.
deps Dependencies as {"action":"id","paths":["output"]}. For each dependency, quern combines the selected outputs in the cache key. If any entry omits paths or gives an empty list, all of that action's outputs contribute. Every explicitly listed path must exist.
identity Additional JSON data contributing to the action identity.
files Map of output-relative paths to text to write before commands run.
jobs Job weight, default 1, capped by -jobs. Neither the weight nor the expanded value of ${jobs} affects the action key.
lease Set to false for trivial actions or tests that should skip the recipe's CPU lease. Defaults to true; local job limits still apply.
lease_uses Additional byre resources to request with the top-level lease, as a map of resource names to positive amounts, such as {"gpu": 1}. Use resource names distinct from the top-level lease.resource. The action must have commands or a precondition and leave its lease enabled. Excluded from the cache key.
tools Additional executable paths to hash, beyond command executables. Declare tools invoked inside shell scripts.
sdk SDK name or path passed to xcrun when resolving ${tool:name} references. Required for those references.
normalize Output-relative text paths whose physical source-root paths should be replaced by logical references for reuse.
expand Output-relative text paths whose logical ${root:name} references should be restored after copies and seed, before files and commands. Other text stays literal. Use with copied normalized artifacts to restore paths for the current invocation. Missing files and unknown roots fail the action.
copies Artifacts to clone as owner-writable copies before commands: {"action":"id","path":"output","to":"destination"}. Each source action must also appear in deps. Copied artifacts contribute to the action key alongside any outputs selected by deps.paths.
seed Output paths of the action's previous result to clone into its output directory before files are written and commands run, on a cache miss. The previous result is the miss comparison's baseline. Replacement runs skip seeding, including forced test reruns, sandboxed replacements, and runs replacing links to missing objects. Commands must produce the same outputs from any seed as from none.
test Make this action a test, described under Tests.
cache Defaults to true. false executes this action once per invocation, keeping dependencies reusable. An optional precondition can skip its commands. Separate action IDs execute separately even when their commands match. Results remain in normal storage for dependencies and diagnostics, under normal collection policy. No previous result is seeded. Actions with cache:false may declare outputs: [] for external side effects.
skip A note explaining why quern -all excludes this action and its transitive dependents, such as "slow; run before release". The note is logged as the exclusion reason (skip: <note>) and recorded in metrics.excluded. Targets and -action still build the action. Not part of the cache key. A whitespace-only note fails the recipe.
precondition Optional command object, valid only with cache:false. Runs before commands: exit 0 skips them, exit 1 runs them, and any other exit status, signal, or execution error fails the action. Uses the same command fields and expansions.
timeout Wall-time limit for the action's commands together, including its precondition, as a positive Go duration string such as "5m". When it passes, quern kills the commands' process groups and fails the action with exceeded 5m0s timeout. Counted from the first command's start, after any lease wait. Part of the cache key.

A missing dependency action or a dependency cycle reports the actions and zero-based deps[].action positions leading to it. Input discovery errors name the action and the zero-based position in inputs. Errors selecting, copying or storing outputs name the action and the zero-based position in deps[].paths, copies or outputs.

List members as sorted paths relative to the input's root. Include each selected directory itself and its selected descendants, after exclusions. With glob: true, each match is scanned separately and compared with the same members list. To assert membership over a directory tree, declare the directory as path and use exclude to omit entries.

For example, a project can check a remote object's contents against its built archive before uploading it:

{
  "id": "upload",
  "cache": false,
  "deps": [{"action": "archive"}],
  "precondition": {
    "args": ["${root:src}/scripts/check-upload", "${dep:archive}/release.zip", "gs://bucket/releases/release.zip"]
  },
  "commands": [{
    "args": ["${root:src}/scripts/upload", "${dep:archive}/release.zip", "gs://bucket/releases/release.zip"]
  }],
  "outputs": []
}

Here the project's check-upload script returns 0 only when the remote contents match, 1 when upload is needed, and another status when the check fails (for example, authentication or network errors). quern builds dependencies and prepares copies and files before running the precondition. The check uses the action's environment, working directory, sandbox, lease, and shared timeout. Its result is checked afresh each invocation. Declared outputs are still required when the check succeeds: prepare them with copies, files, or the precondition itself, or declare no outputs for a purely external side effect.

Input contents, file modes, tools, commands, declared environment other than TMPDIR, and selected dependency outputs contribute to cache identity. Command arguments and command env entries contribute their recipe text before expansion. A literal TMPDIR override contributes its path. An override written as "TMPDIR": "${TMPDIR}" contributes the reference text. The resolved executable's contents are still hashed. Commands must declare all inputs that can affect outputs, including tools and configuration read by scripts. TMPDIR is scratch space. A value that selects inputs or reaches artifact contents belongs in its own recipe environment variable, which is keyed.

Mark actions with effects outside the cache, such as uploads and notarization, cache:false. quern -all relies on this declaration; it does not inspect command names or prevent network access. It excludes those actions, actions with a skip note, and anything requiring them, while still building their cacheable prerequisites. Action exclusions and their reasons appear in the invocation log and metrics.excluded. Cached tests reuse their passes unless -rerun is supplied. Target generated: freshness checks leave sources unchanged. -all skips the entire set if any producer or verify action selected for its check is excluded. Use -verbose to see each skipped set and its reason in a generated check excluded message.

Expansion is available in command arguments, directories, environment values, stdout paths and generated file contents:

Reference Value
${revision:name} Full commit hash of a named revision source; hashed only by actions referencing it.
${revision:name:describe} Tag-aware git describe --tags --always HEAD value of that source, independently hashed where referenced.
${revision:name:timestamp} Committer timestamp of that source's HEAD in Unix seconds (git show -s --format=%ct HEAD), independently hashed where referenced.
${selection} Invocation selection as one JSON string: operation, targets, actions and params. Referencing it contributes that selection to this action's key only.
${out} Private action output directory.
${root:name} Named source root.
${dep:action-id} The whole output directory of an action listed in deps. If using deps.paths, include every dependency artifact the command reads, either in deps.paths or through copies, so changes to those artifacts invalidate the result.
${jobs} This action's assigned job weight. Use it to set parallelism in tools whose outputs are independent of the job count.
${inputs:name} One absolute path argument per literal input path or glob match with that name that survives exclusions, in declaration order and then glob order. A directory contributes one argument for the directory itself. Its selected contents still contribute to the cache key. Use this reference as a whole command argument. A name that selects no paths fails the action.
${tool:name} Executable resolved with xcrun --sdk <action.sdk> --find <name>. The resolved binary is hashed even when referenced inside a script, argument, environment value or generated file.
${NAME} Recipe environment value, when present. Other names remain literal.

Apple roots are also available to plain actions, without a package profile: ${root:toolchain} is the selected Swift toolchain directory, ${root:xcode} is the selected Xcode Contents directory, and ${root:sdk-macosx} (or ${root:sdk-iphoneos}, ${root:sdk-iphonesimulator}, etc.) is the SDK directory resolved by xcrun. Refer to these names in inputs to hash SDK files, or in commands, tools and files to expand their paths. Only requested roots are resolved; missing SDKs fail the invocation. Recipe-declared roots take precedence. Root discovery uses the recipe environment, including DEVELOPER_DIR. A root reference alone does not hash files inside it; declare the SDK inputs and tools that affect the action.

For example, an SDK tool command can name its executable without knowing where Xcode or an additional toolchain installed it:

{
  "id": "compile-native",
  "sdk": "macosx",
  "inputs": [{"root": "project", "path": "native.c"}],
  "commands": [
    {"args": ["${tool:clang}", "-c", "${root:project}/native.c", "-o", "${out}/native.o"]}
  ],
  "outputs": ["native.o"]
}

Named inputs let a command follow discovered membership. With a directory output, adding a matching source file needs no recipe edit:

{
  "id": "meshes/bake",
  "inputs": [
    {"name": "models", "root": "project", "path": "Assets/*.obj", "glob": true},
    {"name": "models", "root": "project", "path": "Content/Models/*.obj", "glob": true}
  ],
  "deps": [{"action": "mac/mac/BuildMeshes/artifacts", "paths": ["BuildMeshes"]}],
  "commands": [
    {"args": ["${dep:mac/mac/BuildMeshes/artifacts}/BuildMeshes", "${out}/meshes", "${inputs:models}"]}
  ],
  "outputs": ["meshes"]
}

Consumers select the meshes directory in deps and copies. For example, an action can stage an executable beside the resources it loads:

{
  "id": "tests/stage",
  "deps": [
    {"action": "mac/mac/Tests/artifacts", "paths": ["Tests"]},
    {"action": "meshes/bake", "paths": ["meshes"]}
  ],
  "copies": [
    {"action": "mac/mac/Tests/artifacts", "path": "Tests", "to": "tests/Tests"},
    {"action": "meshes/bake", "path": "meshes", "to": "tests/meshes"}
  ],
  "commands": [{"args": ["/usr/bin/true"]}],
  "outputs": ["tests"]
}

SDK tool resolution uses the recipe environment, including DEVELOPER_DIR, and runs once per referenced name per action, before the cache lookup. Command-level env does not affect resolution. A missing SDK or tool fails the action. The sdk field selects tools only; pass the compiler's target and SDK arguments explicitly when required. SDK contents read by a command must still be declared as inputs.

Source revisions

Declare source identity once and reference it only in actions that stamp metadata:

{
  "revisions": {"source": {"root": "project", "archive": "tools/build-commit"}},
  "actions": [{
    "id": "metadata",
    "files": {"revision.txt": "${revision:source}\n${revision:source:describe}\n${revision:source:timestamp}\n"},
    "commands": [],
    "outputs": ["revision.txt"]
  }]
}

The root names the repository's top-level source directory. With .git present, quern reads Git directly; Git errors fail the build. Without .git, archive is a required clean relative path to an archive stamp. Omit archive to require a Git checkout. The stamp's first line is a full 40- or 64-digit commit hash; its second line is the describe value and its third line is the committer timestamp in Unix seconds. Each additional line is required only when its value is referenced. Projects create archive stamps as part of their source export (for example, Git's export-subst can supply the hash).

quern reads these values before running sandboxed commands, so actions can use revision metadata without declaring or reading Git data themselves.

Revision references work in the same command and file fields as normal action expansion. Each action hashes only the revision values it references. A tag added at the same commit invalidates an action using :describe, while an action using only the hash remains reusable. Compilation and asset generation do not change keys unless they also reference those values. Each revision expansion is captured when first referenced during planning and reused for the invocation, including publication and delivery. Values first referenced by later fragments are captured at that later planning step. Metadata changes alone do not reject the build; declared source inputs still undergo change validation.

Default outputs

An output group publishes selected artifacts without a delivery wrapper:

{
  "targets": {"default": ["delivery/mac"]},
  "outputs": {
    "default": [{
      "action": "delivery/mac",
      "path": "Example.app",
      "to": {"root": "project", "path": "build/Example.app"}
    }]
  }
}

Each entry uses the placement fields action, path and to. The producer must be an action explicitly selected by the invocation, and verify is not supported. The path can be a file or directory. Publication runs after successful actions and freshness checks, including on cache hits. Stale destinations are replaced atomically with owner-writable copies; sibling paths remain in place. Current destinations keep their existing permissions. The placement validation and rollback under Generated sources also apply to default outputs.

For positional targets, quern combines outputs groups keyed by each selected target name. For explicit -action selection, quern combines outputs groups keyed by each selected action ID. Duplicate selections and identical placements count once; distinct placements must not have overlapping destinations. On a mixed test failure, only placements produced by passed tests are published, including cached passes, and the invocation still fails. Failed or errored tests and non-test producers are not published in that case.

Explicit -output overrides these defaults and replaces the entire destination with one directory containing the selected action outputs. If two selected actions produce different entries at the same output path, quern names both action IDs in the conflict error. -generate and -check do not use output defaults. Fragments may declare outputs for new targets or action selections; redeclaring an existing output group fails.

Tests

A test is an action with "test": true. It passes when the action succeeds. Tests use every action field, including the optional precondition on a cache:false action. Test commands can run installed tools just like other actions. For an executable built by another action, select it in deps and reference its cached path or stage it with copies. Declare files read at run time through inputs:

{
  "id": "test/combat",
  "test": true,
  "inputs": [{"root": "project", "path": "Content"}],
  "deps": [{"action": "tests/stage", "paths": ["tests"]}],
  "commands": [
    {
      "args": ["${dep:tests/stage}/tests/Tests", "--seed", "7"],
      "dir": "${root:project}",
      "env": {"CONTENT_DIR": "${root:project}/Content"}
    }
  ]
}

A recipe-wide "test_timeout": "5m" limits every test that declares no timeout of its own, so a test that runs longer fails instead of becoming a cached pass. A test's own positive timeout overrides the recipe limit. Zero is rejected for both fields. The effective limit is part of each test's cache key: changing it reruns the tests it applies to, so every cached pass ran under the current limit.

Select tests with an ordinary target, such as "tests": ["test/combat", ...], or with -action. A variant with different arguments or environment is a separate test action.

quern picks randomly among eligible tests in its job queue, preferring tests that can reuse a released lease. A test waiting for a byre lease leaves local job slots available for other work.

The combined stdout and stderr of a test's commands are written to a test.log kept in the cache entry beside the test's output directory, not inside it, so it is never materialized by -output and several tests' logs cannot collide. Its path is reported with each test's result. outputs is optional for tests and lists files the test writes into ${out}, such as reports or images. A command with stdout still writes that stream to its file instead.

A passing cacheable test is published and reused like any cacheable action, keyed by its commands, inputs, tools, environment and the selected dependency outputs. Rerunning with the same key reports the cached pass without running the test. Changing anything that contributes to the key reruns it. A test must declare everything it reads, or a stale pass can be reused. Failures are not cached: a failed test reruns next time. Tests with the same key share one execution, and each selected test ID reports that execution's outcome.

A failing test doesn't stop other selected tests. Recorded test outcomes have one of these states:

Status Meaning
passed The action succeeded in this invocation or returned a cached pass.
failed A test command failed or the test exceeded its timeout. Its test.log and output directory, with any partial outputs, are kept under <cache>/failures/.
error quern could not finish the test, for example because a dependency failed, the invocation was canceled, or the result could not be published.

Passing tests' output stays in test.log and the invocation log. A failed test's console report starts with its name and error, followed by its indented test.log and the path to that file. With -verbose, the test output is shown as command output records with stream=test.log, followed by a test failed record with its log and output paths. When the build phase reaches test reporting, it logs tests completed if it recorded any test outcomes. passed includes cached passes, and cached counts how many of those passes were reused. failed and errors count the other two outcomes. A failing selected non-test action cancels the build.

If the byre lease connection retry window expires, blocked tests have no outcome, and quern exits 75 without a tests completed summary or a build results record.

When the main build phase finishes with test failures and source validation succeeds, quern writes build results and exits 1. results contains the selected actions that succeeded. An earlier failure, such as a failing selected non-test action or changed source inputs, can end the invocation with only diagnostics. The tests field maps each test ID to its status, cached, and, when available, duration_ns, log, output, and error. metrics.tests holds the counts. When quern reports test failures this way, it skips -output materialization and generated placement. Default output groups can still publish passed-test artifacts as described above. Failed test logs and outputs are subject to normal cache collection.

Leases

lease takes machine-wide CPU admission from byre's leases:

{
  "lease": {"resource": "cpu_cores", "note": "my-project"}
}

An action that takes a lease requests resource at its job weight before preparing its output directory and holds it through its commands. The request also includes the action's lease_uses, so an action that renders on a shared GPU can wait for its cores and a gpu slot together:

{"id": "tests/walk", "lease_uses": {"gpu": 1}, "...": "..."}

A precondition counts as a command for the lease, including when there are no other commands or the precondition skips them. The lease's note starts with note and the requested action ID. At command start, quern updates it with the action using the lease and the run's completed and total action counts, for example my-project tests/walk (24/30 done). This requires byre's setLeaseNote lease operation. After successful commands, quern can reserve the lease through output publication for a dependent of the same weight and lease_uses that now waits only on this action. The reservation is released if publication must wait for the cache storage gate. When there is no reservation, quern frees the job slots before storing outputs. The lease goes with the freed job slots to the action they let start, when it takes a lease of the same weight and lease_uses, or passes to the next action of that weight and lease_uses waiting for one, or goes back to byre with the CPU its commands used. With -background, every lease goes back to byre after its action. An invocation keeps all its leases on one connection to byre's byre.sock, and byre returns them when it closes, so a killed quern leaves nothing held. If the connection drops, admitted actions finish under their local job slots and waiting work requests fresh leases. quern gives transient connection failures a 30-second retry window, including when first connecting. If the window expires, quern stops admitting work, lets admitted actions finish, and exits with status 75 without a build results record. Actions blocked by the interruption send no -notify notification, and blocked tests have no test outcome. Commands that take a byre lease themselves are recognized by byre as nested in the invocation's lease; byre lends a command's request for something the invocation's leases already hold from them, so it doesn't queue again. Leases don't contribute to cache identity. Package planning actions don't take them. Set "lease": false on a trivial action or test to skip machine-wide admission as well; it still occupies its local job slots and uses the same cache key. Dependencies keep their own lease settings. See operations and design for the protocol.

Fragments

fragments lets actions generate more of the recipe:

{
  "actions": [
    {
      "id": "models/graph",
      "inputs": [{"name": "sources", "root": "project", "path": "Assets/*.obj", "glob": true}],
      "deps": [{"action": "mac/mac/GraphTool/artifacts", "paths": ["GraphTool"]}],
      "commands": [{"args": ["${dep:mac/mac/GraphTool/artifacts}/GraphTool", "${out}/models.json", "${inputs:sources}"]}],
      "outputs": ["models.json"]
    }
  ],
  "fragments": [{"action": "models/graph", "path": "models.json"}]
}

Each fragment names an action and one of its regular file outputs. It is strict JSON with optional roots, packages, actions, targets, outputs and fragments, in the recipe's own format. Relative fragment roots resolve against the original recipe directory and must exist. Roots cannot redeclare existing names. A new package profile ID declares a complete profile. An existing profile ID extends that profile with additional modules and targets; the extension may contain only those two fields and id. For a manifest-backed profile, extra modules augment its loaded manifest targets; the original package and dependency definitions stay intact. Duplicate module and target names fail. Extensions must arrive before the profile is planned, so a generator extending a profile cannot depend on that profile. quern builds the generators first, merges their fragments into the recipe, and repeats with any new fragments until none are left, so a fragment can declare a generator tool and a further fragment that tool produces. A generator is cached like any action: adding a matching source file reruns it through its glob membership, and an unchanged generator costs a cache hit. Fragments can't redeclare an existing action or target. Targets, -action, -generate and -check see the merged recipe.

A fragment can run only for matching invocation selections:

{
  "fragments": [{
    "action": "tests/graph",
    "path": "tests.json",
    "when": {"targets": ["tests", "test/*"], "actions": ["test/*"]}
  }]
}

Omitting when preserves eager expansion. With when, any matching target or selected action activates the fragment. A condition with no matches leaves the fragment out. Patterns support *, ? and character classes; wildcards cross / in IDs. Conditions refer to the original CLI selection, including for nested fragments. -all activates every fragment, with ${selection} containing operation:"all", no selected targets or actions. Selection-aware generators must emit their complete graph for this operation. When -all excludes a generator, quern leaves out its fragment and logs the exclusion reason. The fragment's contents cannot be discovered without executing the generator. For -generate and -check, targets contains the generated set name; for -action, targets is empty. A conditional fragment supplying a generated set's actions must match the set name for standalone -generate or -check, even if it already matches a build target that checks the set. Only activated fragments build generators and add roots or package requirements, so default app builds need no test-only prerequisites.

Pass ${selection} as a whole generator argument or write it to a generated file. It expands to JSON such as {"operation":"build","targets":["test/grips/sword"],"actions":null,"params":{"args":"[\"--seed\",\"7\"]"}}. quern -param suites=grips -param 'args=["--seed","7"]' tests passes strings to the project generator, which owns their meanings and validation. Generators should emit only the selected graph. Commands still receive ordinary argument arrays, with no shell templating or extra scheduler.

Generated sources

Some action outputs are checked in, such as documentation pages or images made from authored content. A generated set places selected outputs at source paths:

{
  "generated": {
    "docs": [
      {"action": "catalog/pages", "path": "pages", "to": {"root": "project", "path": "docs/catalog"}},
      {"action": "map/render", "path": "world.png", "to": {"root": "project", "path": "docs/world.png"}, "verify": "map/compare"}
    ]
  }
}

Each placement names an action, one of its output paths (a file or directory), a destination to (a recipe root and a clean relative path) and an optional verify action. A placement owns its destination: a directory placement replaces the destination directory whole, removing files the action no longer produces. A symlink at the destination is compared and replaced as its own entry. Symlinks in parent directories are followed. Destinations within a set must not overlap or nest.

quern -generate docs builds the placed actions, compares each destination with its selected outputs and atomically replaces stale destinations. Unchanged destinations are not rewritten. After writing, validation fails if any built action's input changed, a destination no longer matches its output, or destinations overlap. On failure quern attempts to undo the writes and reports the first rollback error, if any.

quern -check docs builds the actions needed for the check, caching results as usual. It leaves the placement destinations as they are. It compares contents, file types, symlink targets and executable bits, and fails if any placement is stale. Logs list each added, removed or modified path. For a placement with verify, -check builds that action instead of the placed one. Its success means the checked-in files are current. Use a verify action for outputs that differ between machines, such as rendered images compared within a tolerance, or for a cheaper check that avoids rebuilding expensive outputs. A verify action declares the checked-in files it reads as inputs and fails with its own message when they are stale.

A target can include freshness checks alongside actions:

"targets": {"checks": ["test/protocol", "test/actors", "generated:api"]}

quern checks builds the required producers or verify actions, runs the selected tests, and checks the placements without writing sources. generated: is reserved for generated-set references in target lists. Duplicate references check the set once. Freshness is compared on every invocation even when all producer outputs are cached. A stale placement fails the target and prevents -output materialization. Check producers and verify actions are not materialized unless also listed explicitly as actions in the target. Standalone -check and -generate usage is unchanged.

Swift packages

A profile identifies a package directory, selected targets and a destination:

{
  "id": "mac",
  "package": {"root": "project", "path": "mac"},
  "targets": ["Example"],
  "sdk": "macosx",
  "triple": "arm64-apple-macos15.0",
  "platform": "macos"
}

Put profiles with unique, nonempty IDs in the top-level packages array. A selected executable's artifacts action is <profile>/<profile>/<target>/artifacts for the profile's root package. Dependency packages use their package identity in the second component. Reference that action in targets or assembly dependencies. Executable artifacts include runtime frameworks and resource bundles. Toolchain setup errors identify the package profile. Target planning errors also name the target as <package>/<target>, with a host/ prefix for generator tools. If a local dependency is outside the known roots, add an entry to roots for its directory or an ancestor. Manifest-backed profiles require Package.resolved, even for a package with no dependencies. For a profile declared in the main recipe, run quern -resolve <profile> to create the file or reconcile its pins after a dependency change. Use quern -update <profile> to refresh pins. Keep any -recipe, -cache and -project flags from the build when running either command. Both commands can create the file, even if there are no dependencies to pin. Both skip fragment expansion. Ordinary builds never resolve or update pins.

Profiles also support:

Field Meaning
unbounded During explicit resolution, treat version ranges as minimum versions and allow stable releases across major versions throughout the dependency graph. Defaults to false (SwiftPM resolution).
patches Map of dependency identities to ordered arrays of patch inputs (root and path).
whole_module Compile with whole-module optimization; ordinary compilation is optimized file by file.
traits Map of package identities to enabled Swift package traits.
generators Map of plugin names to explicit generator descriptions.
binaries Map of binary target names to {"action":"id","path":"name.xcframework"} entries. Required for binary targets without a manifest URL and checksum. Remote binary targets can use their evaluated manifest URL and required SHA-256 checksum.
metadata Map of destination Swift target names to App Intents descriptions. Each entry requires platform_family, deployment_target, and a protocols input pointing to a JSON file with "version": 1 and a nonempty constValueProtocols array of protocol names.
link_settings Map of target names to additional inputs and linker flags.
modules Explicit manifest-shaped targets for standalone sources. A nonempty list in the profile declaration defines the profile without reading Package.swift or Package.resolved.

For example, a profile can opt into updates across major versions and carry a source patch:

{
  "unbounded": true,
  "patches": {
    "example-library": [
      {"root": "project", "path": "patches/example-library.patch"}
    ]
  }
}

Patch keys use the lowercase identities in Package.resolved. Patches are Git-style diffs with a/ and b/ paths relative to the dependency package root. quern applies them in order with git apply -p1. Builds evaluate patched manifests and compile patched sources. Missing packages, missing patches and patches that do not apply fail the operation. Patch contents contribute to the prepared package's cache identity. Checkouts and patches are shared by content across host and destination builds. Only source-control dependencies can be patched; local sources stay in place. The default SwiftPM resolver selects pins using upstream manifests, then checks that patched manifests evaluate before writing Package.resolved. Use unbounded when patch changes to manifests must affect dependency selection.

Fetched packages are trusted like the recipe's own sources: quern only builds code the project is about to run, and anything a package could do while it builds it can do when the app runs. Their manifests are evaluated with SwiftPM, their settings (including .unsafeFlags) reach the compiler, and -resolve and -update run SwiftPM and Git with the recipe environment. Fetches clone the pinned location, check out its full commit hash detached, update submodules recursively, and remove .git directories, so a checkout's content is identified by its location and revision. A remote binary target is downloaded from its evaluated manifest URL with curl, and its required SHA-256 checksum is verified before extraction. Local pins still clone.

With unbounded, -update selects the newest stable semantic-version release for version-ranged dependencies, including transitive dependencies. It respects lower bounds and ignores upstream upper bounds. Exact, branch and revision requirements remain explicit constraints. Tags may be 1.2.3 or v1.2.3; prereleases are not selected. Revision requirements use full commit hashes or tag names. Resolution fails on conflicting requirements or a newest release that cannot be evaluated by the selected Swift toolchain; it does not silently select an older release. -resolve preserves saved pins that satisfy the requirements and selects pins for new or unsatisfied dependencies. Both operations atomically write the exact revisions to Package.resolved. Ordinary builds do no release discovery and do not change the lockfile. A cold build fetches the saved revisions as needed.

Each generator declares tool (an executable target), package (identity of the package that provides tool), inputs (paths under the consuming package), args, optional env, and outputs (paths relative to the generator output directory). The tool provider can be the package that uses the plugin or one of its dependencies. Omit package to use one of the consuming package's own targets. Generator arguments and environment support ${package}, ${target}, ${generated}, ${revision} and ${version}, then normal action expansion. Plugin behavior must be expressed in the recipe; quern does not run arbitrary SwiftPM plugins implicitly. Unsupported package constructs fail explicitly.

Keep signing and stamping in project actions: use copies to prepare a writable bundle, run the project's metadata and signing commands, and publish through an outputs group. External delivery scripts can still use quern -publish <prepared-directory> -output <destination>.

See operations and design for cache lifecycle and concurrent build assumptions.

S
Description
Content-addressed Swift build engine
Readme
20 MiB
0 Stars 1 Watchers 0 Forks
Languages
Go 100%