Create a project builder in Rust

A project builder connects Moth to an application environment. This guide presents the accepted target design through a small Wasm package builder, then explains source packages, Rust bindings, configuration, directives and runtime output. See current SDK coverage for the delivered prototype.

The compiler owns language semantics. Your builder owns its application contract and uses the public SDK to request validated compilation and output services.

Read alongside Project structure, Packages and Memory management for their source and lifetime contracts.

Create a builder

A project builder defines what a Moth project can use and turns its compiled assemblies into application artefacts. A game builder can provide engine packages and emit Wasm. A web builder can provide HTML helpers and assemble browser output. Both use the same compiler and build services.

Use the public moth::builder API for this work. The four main values are BuilderDefinition, CompiledProject, BuildContext and BuildArtifacts. ProjectBuilder connects them through two methods:

The build driver calls definition before configuration or source compilation. It retains the resulting immutable definition for the build. It calls build only after the required semantic compilation succeeds. A builder doesn't sequence parsing, type checking or borrow analysis itself.

Current SDK status throughout this guide and its linked sections: A separate crate can register source and host packages, declare one project configuration section and read the project's values through CompiledProject::settings, select a profile, and publish byte artefacts through BuildArtifacts::add and BuiltProject::write_outputs, which share the compiler's central output writer, output roots and build manifest. Destination and ownership failures are detected before any output mutation, and stale cleanup runs only after every artefact was emitted. BuildContext::compile_wasm takes the package handle and returns the opaque WasmModule, but native Wasm compilation of a project package needs the accepted native host ABI lowering, so it returns ErrorKind::UnsupportedCapability until that lands and never a placeholder module. Entry accessors, resource-relative output strings, macros and executable Rust host adapters describe accepted target design, not current SDK APIs. See Packages and Builders Progress and Lappet roadmap.

A Wasm package builder

This builder compiles the application's explicit project package facade to Wasm. It also makes a Moth source package and a Rust host package available. The example package has no output-relative resource strings.

use std::path::PathBuf;

use moth::builder::{
    BuildArtifacts, BuildContext, BuilderDefinition, CompiledProject,
    Error, HostPackage, ProjectBuilder, SourcePackage,
};

#[moth::host_function]
fn has_prefix(text: &str, prefix: &str) -> bool {
    text.starts_with(prefix)
}

struct GameBuilder {
    // Absolute path to the installed package root. `finish` rejects a relative one.
    package_root: PathBuf,
}

impl ProjectBuilder for GameBuilder {
    fn definition(&self) -> Result<BuilderDefinition, Error> {
        BuilderDefinition::new("game")
            .source_package(
                SourcePackage::new("@builder/game/api")
                    .from_dir(&self.package_root),
            )
            .host_package(
                HostPackage::new("@builder/game/platform")
                    .function(moth::host_binding!(has_prefix)),
            )
            .markdown()
            .finish()
    }

    fn build(
        &self,
        project: &CompiledProject,
        context: &mut BuildContext,
    ) -> Result<BuildArtifacts, Error> {
        let package = project.require_package()?;
        let wasm = context.compile_wasm(package)?;

        let mut output = BuildArtifacts::new();
        output.add("game.wasm", wasm)?;
        Ok(output)
    }
}

require_package returns the owner-bound assembly for the authored project facade. A missing facade produces a builder diagnostic. The facade selects its public surface through normal Moth visibility rules. It has no implicit entry work, page output or access to private declarations in other modules.

compile_wasm compiles the selected assembly and its reachable dependencies. The result retains the import, export and runtime contract needed by an embedding host. It doesn't make every source module a separate Wasm binary, create a WIT component or execute the program.

output.add records an artefact under a relative output path. It preserves the artefact's associated contracts and rejects conflicting records. It doesn't write the final file. The central output owner validates destinations, materialises resource bytes and applies manifest-based cleanup.

An assembly containing browser-only operations cannot be compiled for a native Wasm host merely by calling this method. Target validation reports the unsupported reachable operation. Resource-bearing assemblies also require the output context described in Assembly and runtime output.

Invoke the build driver

Use BuildRequest to supply the project location and per-build options. Keep installed builder package locations separate from the application source root. This example obtains the package directory relative to the Rust crate that contains the builder:

use moth::builder::{BuildRequest, build_project};

fn main() -> Result<(), moth::builder::Error> {
    let builder = GameBuilder {
        package_root: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("moth/game/api"),
    };
    let request = BuildRequest::new("game-project");
    let result = build_project(&builder, request)?;

    result.write_outputs()?;
    Ok(())
}

The Moth package directory contains its @package.moth facade and source files. When distributing a builder, install those files at a known location and pass that location explicitly. An absolute installation path locates bytes. It is not the package's semantic identity.

Every builder also compiles the compiler-shipped Core @core/html and @core/css packages. A distributed builder executable needs the compiler's packages/ directory beside it, as in the moth release archive. When that directory is absent, the compiler reads the source checkout that built it, which exists only on the build machine.

Building and writing are separate operations so an embedding tool can inspect results before committing output. An unsuccessful compilation never supplies a partial CompiledProject to build. A failed build never authorises stale output cleanup as though a replacement build had succeeded.

Define once, consume through services

The fluent helpers construct one validated capability surface. finish validates the complete registration and returns an immutable definition or a structured error. Duplicate names, conflicting package roots, invalid defaults and attempts to override compiler-owned facilities fail instead of replacing an earlier registration.

The definition contains builder policy, not an independent compiler. Source packages still use Moth semantic interfaces. Native host packages still use the canonical binding machinery. Helpers don't introduce parallel type tables, configuration parsers or copies of compiler result stores.

Builder identity is a stable declared identity used for ownership and compatibility. It isn't a Rust type name, filesystem path or enum entry that requires editing the compiler for each builder. Source aliases don't change package or output ownership.

Numeric identities and literal defaults belong to the language. Builders don't select a semantic numeric profile. Source annotations and input contracts name exact types, with I32 and F64 as unconstrained literal defaults. Build mode and physical targets don't change them. See Numeric types.

Build-time code and runtime code

The Rust builder uses the compiler as a library. The running application uses a host runtime and its installed bindings. These are separate responsibilities, even when one executable contains both.

Declaring has_prefix makes its interface available during compilation. Installing its adapter in the application's Wasm host makes it callable during execution. Registering an interface alone neither installs a native function in a browser nor sends a request to a server. A target without an implementation rejects reachable calls to that binding.

A project builder reuses compiler backends. Writing a new backend is a different job that consumes validated compiler IR through its own handoff. Ordinary builder code uses assemblies and services rather than public access to HIR, type environments or analysis side tables.

Packages and Rust host functions

Use a source package for reusable Moth code and a host package for functions or resources implemented outside Moth. Both enter normal package resolution. Neither grants special access to another module's private implementation.

Current status: The SDK exposes manual moth::host descriptors only. The macros, Rust-call adapters, resource registration, host-context API and executable runtime below describe accepted target design, not available APIs.

Provide a source package

SourcePackage::new assigns the public package root. from_dir supplies its installed files as an absolute path, and finish rejects a relative one. The installed directory needs a directly contained @package.moth facade. A collocated @entry.moth is allowed but never activates, and an entry-only directory is not an importable source package. Registration through BuilderDefinition::source_package records Builder provenance without asking the caller to construct an internal registry entry. A Builder package root stays below the reserved builder/ prefix and may have several components, such as @builder/game/ui. finish rejects a source package whose path equals, contains or nests inside another registered source or host package path, including case-only variants. Siblings such as @builder/game/ui and @builder/game/audio don't overlap.

let install_root = std::path::PathBuf::from("/srv/game/installed-packages");
let package = SourcePackage::new("@builder/game/ui")
    .from_dir(install_root.join("ui"));

Template scope is not a package registration option. The only implicit .mtf helper scope is the compiler-standard prelude from the mandatory Core @core/html and @core/css packages. The common builder surface registers both roots, so a builder cannot substitute either package, register another root below the reserved core/ prefix or opt arbitrary exported constants into template scope. Application data reaches a template through an explicit qualified reference such as @provider symbol. Ambiguous visible names are still errors.

Packages compile in their own semantic boundaries with the same exact numeric identities and language-owned defaults. Builder source packages don't inherit the application's private project globals. Project-specific compile-time inputs use an explicitly registered synthetic interface with tracked provenance, not ambient state.

Derive a host interface from a Rust signature

Apply #[moth::host_function] to a supported concrete Rust free function. Add its generated descriptor to a package explicitly:

let package = HostPackage::new("@builder/game/platform")
    .function(moth::host_binding!(has_prefix));

The attribute preserves the Rust function and generates a typed binding description and call adapter. host_binding! selects that generated description. Package registration gives it its Moth package and symbol identity. The normal function name is the default exposed name.

The attribute removes duplicate signature declarations. It doesn't register a global plugin, scan the crate for other functions or create an HTTP endpoint. Rust pub visibility and Moth package visibility remain separate from network exposure. The package definition is the place to inspect which functions the builder provides.

Generated descriptions enter the same canonical registration path as manual host descriptors. The macro generates no Moth source to parse again and introduces no alternate semantic type system. Manual descriptors receive the same signature, identity and target validation. They cannot make an invalid Rust adapter safe by claiming a different signature.

The automatic binding profile

The automatic adapter accepts a closed set of Rust signature shapes. Each has one Moth meaning. These are boundary rules, not a claim that Rust and Moth have the same layout or ownership model.

Rust shape

Moth meaning

bool and char

Bool and Char

i8, i16, i32, i64

The matching fixed-width signed type

u8, u16, u32, u64

The matching fixed-width unsigned type

f32 and f64

F32 and F64, with Moth's finite-value checks

moth::host::Byte

Nominal Byte, distinct from U8

&str parameter

Shared string input with call-scoped Rust access

String result

An independent Moth string result

Option<T> for an eligible value type

One optional Moth value

() as the return type

Zero success result slots

Result<T, moth::host::Error> as the outer return type

The success shape plus the built-in Moth error channel

&T or &mut T for an explicitly registered host resource

Shared or exclusive access to that opaque resource

Rust integer and float types name their matching exact Moth types. Rust i32 means I32, f64 means F64 and u8 means U8, never Byte. The Byte wrapper preserves that separate octet identity. No adapter selects a type from a machine word size or builder setting. See Numeric types.

Result<(), moth::host::Error> has zero success slots and an error channel. Result<Option<T>, moth::host::Error> keeps absence distinct from failure. This mapping doesn't create a source-level Result object or tuple in Moth. The error's code is a U32 value. Code zero is valid error data and doesn't turn an error outcome into success.

The automatic profile rejects architecture-dependent usize and isize, raw pointers, borrowed results, arbitrary Rust references, unregistered structs, trait objects, generic functions, impl Trait, async functions and callbacks. Arrays, collections, tuples and arbitrary nested Rust Result values acquire no implicit mapping. A type accepted elsewhere in Moth isn't automatically part of this host profile. Write a concrete wrapper with an eligible surface when a Rust API uses another representation.

A Rust type alias doesn't bypass these restrictions. Generated type obligations let Rust check the resolved type and adapter implementation. The procedural macro examines syntax rather than resolving arbitrary Rust names or analysing function bodies. It doesn't infer purity, absence of panics or application permissions from a function signature.

Values cross through an adapter

The runtime adapter validates scalar encodings, numeric ranges, finite floats, Unicode and string lengths before exposing a value at the receiving boundary. Host float results are the exception. They reach HIR's external binary-float guard as raw carriers. Invalid values don't become successful Moth results through truncation, sentinel substitution or a changed type. A host contract violation is a boundary fault, not an undeclared Moth error return.

A Rust &str parameter grants access only for that call. The adapter may copy into call-owned storage when the runtime cannot safely provide a borrowed view. It promises correct values and lifetimes, not zero-copy access. Host code cannot retain a reference into guest memory after the call.

String results become independent Moth storage. Rust allocator ownership, reference counts and raw pointers don't pass through as Moth ownership. The adapter follows the declared ABI and cleanup contract rather than transmuting Rust layouts. A Rust repr(C) annotation alone supplies none of that contract.

Native host ABI defines the physical carriers, string spans, staged results and frames these adapters use.

A recoverable Rust failure is converted deliberately to moth::host::Error by the wrapper. The attribute doesn't stringify every Rust error, catch every panic or expose sensitive internal details automatically. Assertions, traps, resource exhaustion and faults outside the typed result remain distinct from normal Moth error returns.

Register opaque resources

Use #[moth::host_type] for a Rust-owned resource whose internals stay on the host. Register its type and free-function surface in the package:

#[moth::host_type]
struct Window {
    width: u32,
    height: u32,
}

#[moth::host_function]
fn resize(window: &mut Window, width: u32, height: u32) {
    window.width = width;
    window.height = height;
}

let package = HostPackage::new("@builder/game/window")
    .opaque_type::<Window>()
    .function(moth::host_binding!(resize));

The annotation describes an opaque Moth type, not a serialisable Rust struct. Its fields, native layout and address remain private to Rust. Registering the type creates no resource instance. The host resource API supplies instances under an explicit lifecycle and resolves their handles when functions run.

A resource handle is associated with its registered type, owning runtime and lifecycle. The adapter rejects the wrong type, a stale handle or a handle from another runtime before constructing a Rust reference. Repeated aliases also remain subject to access checks. Two handles do not prove two distinct mutable resources.

&mut Window requires exclusive resource access. It doesn't mean that an arbitrary request is authorised or that the function cannot mutate unrelated host state. Host-side calls and nested invocations obey the resource access contract as well as Moth's static checks.

The package exports free functions. The attribute doesn't manufacture Moth receiver methods or expose every Rust method on the resource. Moth source wrappers can provide a higher-level API through ordinary source-owned types.

Supply host context explicitly

A host-context parameter is supplied by the runtime rather than by the Moth caller. Mark it explicitly and keep it separate from ordinary parameters:

struct HostState {
    user_name: Option<String>,
}

#[moth::host_function]
fn current_user(
    #[moth(context)] host: &HostState,
) -> Option<String> {
    host.user_name.clone()
}

The Moth function takes no argument and returns an optional string. The clone provides an independent result rather than retaining a borrow of host state. The runtime supplies the required HostState for the invocation. An absent or incompatible context is rejected before calling the Rust function.

A binding has at most one marked context parameter. Context is neither a serialised Moth value nor an arbitrary dependency-injection registry. A mutable context has an exclusive access requirement. The host determines its scope, such as an application, session or request, and never shares request-private state accidentally through a global instance.

Install the execution surface

Compilation consumes package descriptions. Execution consumes the matching runtime adapters. The embedding host installs implementations for the import contract recorded on the Wasm artefact and supplies the required resource and context owners. Missing implementations or mismatched contracts fail before normal execution.

A native Rust implementation isn't a JavaScript implementation. Browser and server targets require their own compatible bindings. The SDK doesn't turn a missing browser binding into RPC. A host import is also not a public web route. Authentication, authorisation and HTTP mutation protection belong to the web builder and application boundary that receive the request.

Host-binding attributes are the SDK's narrowly scoped use of procedural macros. They generate checked descriptions and adapters. They don't provide an extension point for arbitrary compiler passes or unrelated metaprogramming.

Configuration and directives

A builder definition describes a constrained source surface. Rust helpers make that description convenient while Moth owns parsing, typing, folding and the retained facts consumed by later stages.

Describe builder configuration

Use the configuration helper for builder-owned settings:

let definition = BuilderDefinition::new("game")
    .config("game", |config| {
        config.string("asset_root").default("assets");
        config.bool("debug_overlay").default(false);
    })
    .finish()?;

The closure constructs a schema. It isn't a callback executed during Moth expression evaluation. The helper records field names, value types, required or optional status and defaults in the normal configuration contract. finish validates the definition. Authored values then use the compiler's configuration service and produce typed builder settings.

A default satisfies an omitted permitted value. It doesn't replace malformed input or an explicitly supplied value. Missing required values, unknown fields, duplicate names and invalid value domains are errors. Optionality and omission are separate rules rather than an instruction to deep-merge records.

game names a builder-owned configuration contract. This helper doesn't add arbitrary fields to the compiler-owned project record or reinstate a separate configuration expression language. Configuration stays a self-contained compile-time source. It doesn't run host functions, import application modules or perform runtime requests.

The selected builder is settled before configuration compilation. A setting doesn't silently select another builder or physical backend. Explicit source input contracts, project metadata and builder-provided globals retain their separate receiving rules. A builder global is stable semantic configuration, not a way to expose host architecture, secrets or operating-system identity to source evaluation.

Keep root slot destinations builder-owned

A builder surface may register statically known named destinations for direct top-level const contributions. The compiler treats that set as read-only input: it recognises a direct const $in only when the insert is the whole root template, validates the destination, folds the contribution and records the name, authored span and structural value in the fragment handoff. It never interprets an HTML slot name or scans constant names for metadata. Each registered name must tokenize as a single source symbol after $in. Builder-definition validation rejects invalid names. A unit test validates the built-in HTML surface.

Slot meaning stays with the builder. The HTML builder interprets its registered title, description, lang, favicon, body_style, stylesheets and head destinations and leaves the default body lane for ordinary fragments. Another builder may register unrelated names. Nested, aliased and runtime inserts remain ordinary template composition and do not route to a builder destination. Runtime named builder slots remain unsettled final design.

This registration belongs to the builder capability surface, not to source packages or arbitrary callbacks. Keep slot-specific validation, escaping, fallbacks and output deduplication in the builder that owns the meaning.

Directives stay compiler-owned

A builder exposes no directive registration path. Directives, their contexts, operand contracts and formatters are compiler-defined, so every builder sees the same set. A builder contributes root-slot destinations, configuration schemas, source kinds, packages and external providers; it cannot add syntax, supply a formatter or name a directive.

Unknown directives, wrong placement and malformed operands remain distinct compiler errors. Ordinary static conditional code doesn't suppress frontend validation. Structural exclusion belongs to the compiler's pre-graph feature-selection contract, not to a builder callback or configuration Boolean.

Builder-owned facts preserve their declared scope. Project settings don't automatically merge with builder slot contributions. A provider's facts aren't inherited by its consumer.

Select source adapters and external providers

markdown enables the compiler-known plain Markdown source adapter. .mtf is a fixed compiler-supported source kind, so every builder compiles .mtf files through normal module compilation without registering it. A .md file contributes rendered content. Builders register only optional source kinds, and registering a filename extension doesn't add a new Moth declaration grammar.

Use external_import_provider for a foreign file format that supplies a typed binding surface. The provider declares its stable kind and supported extensions. It receives a resolved source request and returns typed package facts, diagnostics and any runtime asset requirements.

Provider code can parse its own foreign format. It doesn't reparse Moth imports or perform another module-discovery pass. Source identity, package registration, tracked input access and diagnostic locations come from the supplied services, not from private string or path interners.

Registration conflicts are diagnosed rather than resolved by whichever provider runs first. Provider work records all semantic inputs needed for invalidation. Runtime assets share ordinary resource and output ownership with directly registered host packages. Their consumers don't reconstruct imports by scanning emitted JavaScript, HTML or Wasm.

Reuse the selected surface for tools

Checking and editor analysis use the same builder definition as compilation. Tooling can add analysis and validation roots without creating a competing package registry or output builder. A binding has the same meaning in an editor, a check and a release build, and the directive set is the compiler's in every command.

A definition becomes immutable before source compilation. Changes to packages, signatures or relevant configuration invalidate the affected semantic or physical work through the normal dependency facts. Runtime state, function-pointer addresses and absolute installation paths aren't stable semantic fingerprint keys.

Assembly and runtime output

CompiledProject is the builder-facing view of successful compiler and graph results. Its entries, package surface, metadata and resources stay paired with the compilation that owns them. Handles from one compilation cannot be resolved against another compilation's similarly numbered objects.

Choose an assembly, not a compiler stage

Use entries to inspect selected executable entries and require_package when the builder requires a project facade. Builder-defined callable roots are selected through their explicit builder or tooling contract. The build driver computes their reachable functions, generated instances, resource uses and runtime requirements from compiler-owned facts.

The builder consumes the build system's @entry.moth presence selection rather than guessing entry status from nonempty HIR, a template or rendered output. An API-only support module remains API-only. Importing a module exposes its legal declarations without activating dormant entry work.

A Moth package export isn't automatically a native host export, foreign component interface or network endpoint.

Use BuildContext lowering services for those assemblies. A request to compile_wasm asks for validated Wasm output, including its runtime contract. A browser assembly uses the browser compilation service and its JS/Wasm policy. The service rejects unsupported reachable capabilities before emission.

These services own the compiler handoff. They arrange link-level lifetime validation, capability checks, target partitioning and physical memory planning before lowering. The builder supplies its lifecycle and output policies but never selects a memory strategy, manufactures call summaries or repackages numeric proof tables.

Assembly contracts retain exact numeric identities independently of physical carriers. A wider register doesn't widen an I8 operation or remove F16 completion. Imported constants and successful host returns retain their declared types, and adapters validate values before exposing them to Moth. See Checked arithmetic and External binding contracts. The packages and builders progress matrix records target availability. Exact numeric support doesn't grant a missing package lowering.

Read constant and runtime templates

An entry's template assembly view exposes folded fragments with their body or builder-slot destinations, runtime fragment positions and the executable entry contract. It contains no AST or template-IR handles.

A folded fragment with a named destination is builder metadata, not body output. The builder resolves those values once for its document or artefact; the compiler has already validated the destination against the builder's registered set and preserved the structural value and authored span. A nested or aliased insert never appears as a named destination.

A bare direct top-level [...] template is const-required and already folded when it reaches assembly. An explicit ~[...] remains a runtime entry fragment, even if its content is compile-time foldable. Only the executable entry-root direct form has this requirement. Ordinary expression and nested templates use their normal const/runtime semantics. It may still contain structural resource or site-root pieces whose final characters depend on output placement. Use the context's structural-string rendering service to resolve those pieces. Plain-text extraction is valid only when every piece has concrete characters.

A runtime template is executable Moth code that produces a string. It isn't a second build-time template evaluator. Explicit ~[...] runtime top-level templates contribute to the normal entry's fragment result collection. Compiler-owned $doc metadata attaches to declaration identities and $todo has no output. $note is a discarded child template inside a template body, so a note never reaches this collection. None of them becomes a body fragment or builder slot.

Each folded fragment records how many runtime fragments precede it. For a constant fragment A, a runtime fragment B and another constant fragment C, the assembly records:

A: before runtime position 0
B: runtime position 0
C: before runtime position 1

The shared assembly service interleaves the folded strings and successful runtime results in source order. It doesn't need to recover their positions from rendered HTML or executable IR.

A direct .mtf compilation uses the named template service when only folded content is needed. That service doesn't run a full backend pipeline or invent a page URL context. It returns structural content and the retained facts the builder needs to place its resources.

Consume the entry outcome

A normal executable entry has built-in Error! alongside its fragment-collection success slots. The generated runtime caller invokes it once for that entry activation and branches on the typed outcome.

Only success publishes that invocation's runtime fragments. On error, discard unpublished runtime results and leave existing static content in place. Read neither undefined success slots nor a partial fragment list as success. The failure is a program execution result, not a failed compiler invocation.

Fragment staging isn't rollback. Earlier explicit IO, host calls and DOM changes remain done. The host doesn't retry startup, continue later statements or turn an error into a successful empty page. Error code zero remains an error when it arrives on the error channel.

An embedding host delivers the failure to its caller. A terminal host reports failure and uses a nonzero exit status independently of the error code. A web host uses its application-safe failure presentation instead of inserting raw error messages as HTML. Assertions and unexpected startup faults remain distinct from the declared error result. The wrapper owns this invocation, not every later callback or unrelated script.

A wholly static page doesn't acquire mandatory application runtime code just because the entry contract has an error channel. Reuse and runtime emission remain reachability-driven.

Declare lifecycles without fixing the Wasm engine

A builder's consumer contract supplies lifecycle roots such as an entry, request, frame or host-owned arena. These tell the compiler which execution lifetimes apply. They don't weaken source ownership rules or allow retained values to escape invalid lifetimes.

A lifecycle root is not an instruction to create one Wasm instance. Hosts can use separately created, pooled or longer-lived instances when they preserve isolation, valid access and required cleanup. Persistent host resources and request-scoped context need explicit owners even when the compiled module bytes are reused.

The Rust host installs typed imports and executes compiled Moth through a compatible runtime adapter. Wasmer, Wasmtime and other engine choices belong to the embedding integration, not to Moth source semantics. The adapter validates the artefact's host contract before calling an export. Sharing source between browser and server doesn't share memory or runtime authority.

Plan resources before materialising them

Resource origins, byte sources, destination paths and rendered URLs are different facts. The compiler retains semantic origins and authored uses. The builder supplies output placement and URL context. The central output system owns reads, writes, conflicts and manifests.

Use output and resource planning services to reserve the consuming artefact and its context before lowering any URL-dependent code. A page URL context is the document, while a standalone stylesheet uses its own location. A builder that cannot supply a valid context reports an unsupported use rather than guessing a root slash or treating a resource reference as ordinary text.

All output destinations are preflighted before ordinary resource bytes are read or hashed. Unused resources may remain tracked inputs without being read or emitted. The build system deduplicates compatible resource origins and rejects conflicting output owners. Runtime assets, source resources and builder artefacts use the same ownership rules.

BuildArtifacts records the result. The output writer validates relative paths and configured-root containment, retains manifest ownership and removes only stale files owned by the corresponding successful build. A builder cannot compose with another builder by silently overwriting its outputs.

Preserve failure categories

The SDK preserves the difference between a source diagnostic, an operational build failure and a compiler bug. Authored locations and typed reasons travel with diagnostics through the public reporting view. Builder code doesn't need the compiler's interner tables to produce a useful report.

Runtime moth::host::Error values and entry failures belong to execution, not to moth::builder::Error as an alternative compiler diagnostic. Rust adapter faults also don't acquire a typed Moth error channel that the binding never declared. The host's fault policy handles them at its owned execution boundary.

Test the boundary through the public API

Compile representative projects through build_project and inspect their artefacts and diagnostics. Exercise the same definition and assembly services used by the application rather than constructing HIR or fake compiler results. Use temporary output roots when testing writing and cleanup.

A builder's tests should cover successful registration and duplicate rejection, unsupported capabilities, required configuration, const/runtime fragment ordering, startup success and error, resource-context failures and output ownership conflicts.

Host-binding tests also cover Rust signatures rejected at compile time and actual calls through the selected runtime adapter. Verify malformed values, non-finite float results, stale or foreign resource handles, conflicting mutable access and missing host context. Descriptor inspection alone doesn't test ABI conversion or runtime lifetime safety.

Keep the host package interface and installed implementations consistent across build and runtime tests. A function that type-checks in Moth still needs a valid implementation in the execution environment that will call it.