# witforge Full Documentation Version: 0.12.0 Rust MSRV: 1.88 Site: https://witforge.org/ Index: https://witforge.org/llms.txt --- # Overview URL: https://witforge.org/docs/ witforge compiles one hand-written WIT package into runtime-independent contract artifacts: - plain Rust types and interface traits (with opt-in Serde, `no_std`, `Eq`/`Hash`, and `TryFrom`); - zero-dependency plain types, interfaces, and version adapters for TypeScript, Python, Go, Java 21, and C# 12; - protobuf messages with stable field and method numbers and opt-in Go/Java/C# file options; - JSON Schema (Draft 7 default, opt-in Draft 2020-12); - checked protobuf conversion glue for Rust, TypeScript, Python, Go, Java, and C#; - deterministic Markdown contract reference docs (`witforge doc`), versioned JSON contract IR (`witforge inspect --json`), and cross-language conformance fixtures (`witforge conformance`); - opt-in third-party emitter plugins (`witforge plugin`), compatibility reports (`diff`, `--git-base`, project policies), `deps sync`, and deterministic CI checks. It is a contract compiler, not a Wasm runtime, RPC framework, or replacement for wit-bindgen. 1. [Choose whether witforge fits](https://witforge.org/docs/choosing-witforge/). 2. Follow the [quickstart](https://witforge.org/docs/quickstart/). 3. Learn the [contract layout and supported WIT](https://witforge.org/docs/contract-authoring/). 4. Configure [generation](https://witforge.org/docs/generation/) and [wire a Rust crate](https://witforge.org/docs/wiring/). 5. Inspect [real generated output](https://witforge.org/docs/generated-output/). 6. Add [CI checks](https://witforge.org/docs/ci/). 7. Review [contract evolution](https://witforge.org/docs/evolution/) and [release migrations](https://witforge.org/docs/migration/). 8. Look up flags and keys in the [CLI and configuration reference](https://witforge.org/docs/reference/). ## Important boundaries - [JSON projections](https://witforge.org/docs/json-projections/) - [Non-Rust implementation rules](https://witforge.org/docs/non-rust/) - [wit-bindgen, Wasmtime, and witforge](https://witforge.org/docs/component-model/) - [Runnable examples](https://witforge.org/docs/examples/) ## Reference - [Design overview](https://github.com/zeropier/witforge/blob/main/docs/design/overview.md) - [Emitter specification](https://github.com/zeropier/witforge/blob/main/docs/design/emitters.md) - [Polyglot emitter specification](https://github.com/zeropier/witforge/blob/main/docs/design/polyglot-emitters.md) - [Plugin specification](https://github.com/zeropier/witforge/blob/main/docs/design/plugins.md) - [Ecosystem distribution](https://github.com/zeropier/witforge/blob/main/docs/design/ecosystem-distribution.md) - [Lockfile specification](https://github.com/zeropier/witforge/blob/main/docs/design/lockfile.md) - [Diagnostics](https://github.com/zeropier/witforge/blob/main/docs/design/diagnostics.md) - [GitHub Action](https://github.com/zeropier/witforge/blob/main/docs/design/action.md) - [Public API policy](https://github.com/zeropier/witforge/blob/main/docs/design/public-api.md) Current release: **0.12.0**. Rust MSRV: **1.88**. The 1.0 release remains gated on successful independent-consumer validation. --- # Choosing witforge URL: https://witforge.org/docs/choosing-witforge/ ## Good fit witforge fits when: - hand-written WIT is the contract source of truth; - the callable contract is pure, synchronous, and value-oriented; - native Rust and polyglot or out-of-process implementations share the same semantic values; - protobuf numbers must remain stable across versions; - generated output is committed and checked for drift; - contract changes need machine-readable compatibility review; - adjacent contract versions need generated conversion adapters. Typical examples are analyzers, validators, bounded policy calls, transformation requests, and plugin operations that take and return finite values. ## Use another tool directly Use [wit-bindgen](https://github.com/bytecodealliance/wit-bindgen) and a Component Model runtime when you only need guest/host bindings and Canonical ABI support. Use protobuf tooling directly when protobuf is already authoritative and WIT is only a generated view. Use an application runtime or protocol framework for: - component loading and linking; - process framing and multiplexing; - callbacks, cancellation, and asynchronous streams; - capability grants, resource limits, retries, and failure policy; - discovery, signing, packaging, and distribution. witforge does not own those concerns. ## Current subset Supported: records, variants, enums, flags, aliases, `char`, lists, fixed-length lists (`list`, `1 <= N <= 65536`), maps (`map` with `bool`, integer, `char`, or `string` keys), options, results, named interface functions, worlds, and standard `deps/` package references. Refused: resources and handles, tuples, futures, streams, async functions, accessors, world-defined functions/types, unsupported map key types, and out-of-range fixed-length lists. Run `witforge check` against the actual package for the authoritative answer. --- # Quickstart URL: https://witforge.org/docs/quickstart/ witforge turns one hand-written [WIT](https://component-model.bytecodealliance.org/design/wit.html) package into the artifacts the two sides of a contract need: - plain Rust types and interface traits (with opt-in Serde, `no_std`, `Eq`/`Hash`, and `TryFrom`); - zero-dependency plain types, interfaces, and version adapters for TypeScript, Python, Go, Java 21, and C# 12; - a protobuf schema with append-only field numbers and opt-in Go/Java/C# file options; - JSON Schema definitions (Draft 7 default, opt-in Draft 2020-12); - checked protobuf conversion glue across Rust, TypeScript, Python, Go, Java, and C#; - deterministic Markdown contract reference documentation (`witforge doc`), conformance fixtures (`witforge conformance`), and opt-in third-party plugins (`witforge plugin`). It is not a runtime, transport, or WASM guest-binding generator. Consumers in Rust, TypeScript, Python, Go, Java, and C# can use the generated plain types, adapters, and checked protobuf glue directly, while other languages use the emitted `.proto` with their normal protobuf toolchain. ## Install Install the current release: ```sh cargo install witforge-cli --version 0.12.0 --locked witforge --version ``` Non-Rust teams do not need a Rust toolchain to run `witforge`: | Ecosystem | Invocation / Package | Details | |---|---|---| | Python (`uvx`, `pipx`, `pip`) | `uvx witforge== generate --config witforge.toml --only proto,py,py-glue --check` *(workflow-packaged; published once PyPI OIDC is enabled)* | [PyPI install](https://witforge.org/docs/wiring/#from-pypi-uvx-pipx-pip) | | TypeScript / Node (`npx`, `npm`) | `npx --yes @witforge/cli@ generate --config witforge.toml --only proto,ts,ts-glue --check` *(workflow-packaged; published once npm OIDC is enabled)* | [npm install](https://witforge.org/docs/wiring/#from-npm-npx-npm-pnpm) | | macOS / Linux / Go (`brew`, `mise`) | `brew install zeropier/tap/witforge` or `mise use aqua:zeropier/witforge@` *(workflow-staged tap / local `aqua` registry)* | [Homebrew, `aqua`, and `mise`](https://witforge.org/docs/wiring/#from-homebrew-aqua-and-mise) | | .NET 8+ / JVM 21+ | `Witforge.Tools` (`PrivateAssets="all"`) and `witforge-native` `@exe` *(workflow artifact / local feed)* | [.NET and JVM wrappers](https://witforge.org/docs/wiring/#from-nuget-witforgetools-and-maven-witforge-native) | | GitHub Actions | `uses: zeropier/witforge@v0.12.0` | [CI guide](https://witforge.org/docs/ci/) | Prebuilt archives (with `.sha256` checksums, `LICENSE-APACHE`, `LICENSE-MIT`, `README.md`, and from 0.7.0 SLSA build provenance attestations) are published on GitHub Releases for Linux x86_64 and Linux arm64 (static `musl` from 0.8.0 alongside `gnu`), macOS Intel and Apple silicon, and Windows x86_64; `cargo binstall witforge-cli` is also configured. Windows arm64 builds are not provided; use `cargo install witforge-cli --locked` on that platform (or see the [wiring and installation guide](https://witforge.org/docs/wiring/) for manual download and verification commands). From this repository, before or after publication: ```sh cargo run -p witforge-cli -- --version ``` The examples below use `witforge`; replace it with `cargo run -p witforge-cli --` when working from a checkout. Every command on this page runs from one working directory, the one that contains `my-contract/`, and the test suite runs them in this order. ## One version To scaffold a starter project (`wit/v0.1/contract.wit`, initial `wire.lock`, and `witforge.toml`) in one step without overwriting existing files, run `witforge init my-contract --package example:hello` (add `--serde` to enable Serde derives). The manual steps below walk through each file explicitly. Create a root with a version directory: ```text my-contract/ wit/ v0.1/ contract.wit ``` ```sh mkdir -p my-contract/wit/v0.1 ``` Save a small contract as `my-contract/wit/v0.1/contract.wit`. The package version must match the directory name, and an interface and a world cannot share a name: ```wit package example:hello@0.1.0; interface greeter { record greeting { text: string, } greet: func(name: string) -> greeting; } world hello { export greeter; } ``` At this point, `contract.wit` is the only file in `v0.1`. Do not create `wire.lock` by hand. Create the lockfile, assign wire numbers, and validate the contract: ```sh witforge lock my-contract/wit/v0.1 --first witforge check my-contract/wit/v0.1 ``` `witforge lock --first` creates `my-contract/wit/v0.1/wire.lock`. Commit `contract.wit` and the generated `wire.lock` together. The lockfile is append-only: generated protobuf field numbers and method ids must never change. Generate each projection: ```sh witforge rust my-contract/wit --out my-contract/generated/rust witforge proto my-contract/wit --out my-contract/generated/proto witforge schema my-contract/wit --out my-contract/generated/schema witforge glue my-contract/wit --out my-contract/generated/glue \ --plain-root crate::generated::rust --proto-root crate::generated::proto ``` `--plain-root` and `--proto-root` are Rust module paths, not output directories. The glue emitter uses them to reference the plain types and the `prost` types generated from the `.proto` schema. Every generator supports `--check`, which writes nothing and fails if committed output differs: ```sh witforge rust my-contract/wit --out my-contract/generated/rust --check witforge proto my-contract/wit --out my-contract/generated/proto --check witforge schema my-contract/wit --out my-contract/generated/schema --check witforge glue my-contract/wit --out my-contract/generated/glue \ --plain-root crate::generated::rust --proto-root crate::generated::proto --check ``` ## Use `witforge.toml` Put the repeated paths in a project file, `my-contract/witforge.toml`: ```toml version = 1 [project.hello] root = "wit" [project.hello.rust] out = "generated/rust" # serde = true # opt in to Serialize/Deserialize derives [project.hello.proto] out = "generated/proto" [project.hello.schema] out = "generated/schema" [project.hello.glue] out = "generated/glue" plain-root = "crate::generated::rust" proto-root = "crate::generated::proto" ``` Then run every configured generator in one command (or invoke `rust`, `proto`, `schema`, and `glue` individually): ```sh witforge generate --config my-contract/witforge.toml witforge generate --config my-contract/witforge.toml --check ``` Inside `my-contract/` (or any subdirectory below it within the repository), `witforge.toml` is discovered automatically without passing `--config` (pass `--no-config` to disable discovery). If the file has more than one project, `generate` runs all of them unless `--project NAME` selects one. Paths inside the file are relative to the file itself. Explicit CLI paths override configured paths, and the command-line-only form continues to work. `--serde` or `--no-serde` overrides the Rust section's serde setting; the generated code then requires the consumer's `serde` crate with `derive`. ## Evolve a contract A contract change is a new version directory, never an edit to a released one. Keep every released version in the tree: ```text my-contract/wit/ released # lists v0.1 v0.1/ contract.wit wire.lock v0.2/ contract.wit wire.lock ``` When `v0.1` ships, validate and record it as released in `my-contract/wit/released`: ```sh witforge release my-contract/wit/v0.1 ``` Start the next minor from the latest version. `new-version` copies every `.wit` file, `deps/`, and `wire.lock`, and updates the `package` version header to `0.2.0` (add `--major` for a new major with no copied lockfile; the manual equivalent is `mkdir`, `cp` of the `.wit` files and `wire.lock`, and bumping the `package` header yourself): ```sh witforge new-version my-contract/wit ``` Edit `my-contract/wit/v0.2/contract.wit` to add the new members (using defaultable types when possible so generated adapters can convert old values): ```wit package example:hello@0.2.0; interface greeter { record greeting { text: string, language: option, // old values become None tags: list, // old values become an empty list } greet: func(name: string) -> greeting; } world hello { export greeter; } ``` Assign numbers to the new members, then validate the whole WIT root (which checks released directories in default mode and every draft against its predecessor): ```sh witforge lock my-contract/wit/v0.2 --against my-contract/wit/v0.1/wire.lock witforge check my-contract/wit ``` Regenerate everything. With two versions in the root, `rust` also writes `convert.rs`: ```sh witforge generate --config my-contract/witforge.toml witforge generate --config my-contract/witforge.toml --check ``` `convert.rs` holds old-to-new and new-to-old adapters. Old-to-new conversion fills an added `option` with `None`, an added `list` with an empty list, and an added `map` with an empty `BTreeMap`. New-to-old conversion drops members the older version does not have. Missing required older members are reported as `ConversionError::MissingMember`; added or removed cases are reported as `ConversionError::UnknownCase`. A required, non-defaultable addition is refused by conversion generation. Do not edit a released version's WIT, lockfile, or generated per-version modules. `witforge lock` refuses a released directory, `check` and the generators fail when a released WIT file no longer matches its lockfile, and `witforge freeze` verifies in Git history (with `fetch-depth: 0`) that no released directory was modified or dropped from `wit/released`. ## Review a change Compare a draft with the previous version before merging it: ```sh witforge diff my-contract/wit/v0.1 my-contract/wit/v0.2 witforge diff my-contract/wit/v0.1 my-contract/wit/v0.2 --json witforge diff my-contract/wit/v0.1 my-contract/wit/v0.2 --check # exits 1: see below ``` `--check` fails on wire-, source-, or generated-API-breaking changes (or the view set configured in `[project..policy].diff-check`). It exits 1 for the change above: the two added fields keep every wire number and convert from old values, but Rust code that constructs a `Greeting` has to be updated, so `diff` reports them as source- and API-breaking. To compare your working tree directly against a Git commit or branch without checking out a second tree, pass `--git-base `. `--json` is the complete diff report, and `witforge inspect --json` exports the versioned JSON contract IR for tooling. `diff` also reports a note when a shared record type's generated new-to-old converter is guaranteed to fail because the older version requires a member the newer version removed; the notes do not change the change counts or `--check` result. To make any command's diagnostics machine-readable, add `--format json` or `--format sarif`; the catalogue is in the [diagnostic codes guide](https://witforge.org/docs/diagnostics/). For Markdown contract reference pages (`index.md` and one `v_.md` per live version), run `witforge doc` (or configure `[project..doc]`). For CI, [`zeropier/witforge`](https://github.com/zeropier/witforge) publishes an Action that installs the matching release and can run the same checks; see the [CI guide](https://witforge.org/docs/ci/) and the [Action specification](https://github.com/zeropier/witforge/blob/main/docs/design/action.md). ## Non-Rust consumers witforge includes built-in plain-type, cross-version adapter, and checked protobuf glue emitters for five non-Rust ecosystems: - TypeScript (`witforge ts` and `witforge ts-glue` for `@bufbuild/protobuf`); - Python 3.11+ (`witforge py` and `witforge py-glue` for `google.protobuf`); - Go 1.22+ (`witforge go` and `witforge go-glue` for `google.golang.org/protobuf`); - Java 21+ (`witforge java` and `witforge java-glue` for `com.google.protobuf`); - C# 12+ / .NET 8+ (`witforge csharp` and `witforge csharp-glue` for `Google.Protobuf`). Built-in `*-glue` emitters enforce every WIT decode and encode rule automatically, and `witforge conformance` exports deterministic test vectors (`vectors.json`, `proto/`, `wit/`) that prove cross-language parity. Other ecosystems (such as C++, Kotlin, or Swift) can use the emitted `.proto` files with their standard protobuf generator alongside the documented decode profile, or generate custom projections with `witforge plugin `. The [Non-Rust implementation guide](https://witforge.org/docs/non-rust/) specifies the complete profile and lists every built-in emitter. witforge intentionally does not duplicate `wit-bindgen`'s runtime WIT bindings or own transport framing. The generated types, glue, stable protobuf numbers, and JSON Schema are cross-language contract artifacts, not a complete application protocol. ## Supported WIT subset The current subset is deliberately pure and synchronous: - package versions are `..0`; - types and functions live in named interfaces; - records, variants, enums, flags, aliases, `use` aliases, `char`, lists, fixed-length lists (`list`, `1 <= N <= 65536`), maps (`map` with `bool`, integer, `char`, or `string` keys), options, and results are supported; - resources, async, futures, streams, tuples, unsupported map key types, out-of-range fixed-length lists, multi-package workspaces, and world-defined types are currently refused. - named types and interfaces from packages under a version directory's standard `deps/` layout are supported as package-qualified references; worlds may import and export dependency interfaces, and glue covers dependency types and functions. See the [dependency specification](https://github.com/zeropier/witforge/blob/main/docs/design/dependencies.md). Run `witforge check` for the exact diagnostic. The [design overview](https://github.com/zeropier/witforge/blob/main/docs/design/overview.md) has the full contract model and the reasons for each refusal. ## Dependencies and Serde A version directory may use standard `deps/` packages. Put the dependency under `wit/v0.1/deps/`, declare its package, and import its types or interfaces normally: ```wit package example:app@0.1.0; interface api { use example:shared/types@0.1.0.{item}; get: func() -> item; } world plugin { import example:shared/types@0.1.0; } ``` `witforge rust`, `proto`, `schema`, `glue`, and all ten built-in polyglot emitters generate dependency bindings alongside the local output (`witforge doc` lists the pinned dependencies on each version page), and `witforge deps sync` keeps vendored `deps/` trees synchronized across unreleased versions within a major. See the [dependency specification](https://github.com/zeropier/witforge/blob/main/docs/design/dependencies.md) for the generated files and dependency glue layout. Serde and other Rust profile options (`no-std`, `eq-hash`, `try-from`) are opt-in per project: ```toml [project.demo.rust] out = "generated/rust" serde = true ``` The default generated output has no external crate dependencies; enabling Serde requires the consumer's `serde` crate with the `derive` feature. CLI flags (`--serde`/`--no-serde`, `--no-std`/`--std`, `--eq-hash`/`--no-eq-hash`, `--try-from`/`--no-try-from`) override the configuration. ## JSON projections Plain Rust Serde, JSON Schema (Draft 7 default, opt-in Draft 2020-12), and proto3-JSON project the same WIT values differently: - generated Rust Serde uses Rust identifiers, so `start-byte` becomes `start_byte`; - JSON Schema preserves the WIT name `start-byte`, requires every record property, and permits `null` for `option`; - proto3-JSON uses lowerCamelCase (`startByte`), decimal strings for 64-bit integers, and normally omits an absent optional value; - none of the projections supplies application defaults such as "missing severity means warning." Choose one authoritative JSON profile. Keep an explicit application adapter when an existing protocol differs, and do not validate one projection with another projection's schema. See [JSON projections](https://witforge.org/docs/json-projections/) for the full comparison. ## Examples - [`examples/single`](https://github.com/zeropier/witforge/tree/main/examples/single): one version, Rust, protobuf, JSON Schema, and glue generators, config-driven. - [`examples/evolved`](https://github.com/zeropier/witforge/tree/main/examples/evolved): released v0.1 plus draft v0.2, lock continuity, and generated conversions. - [`examples/polyglot`](https://github.com/zeropier/witforge/tree/main/examples/polyglot): released v0.1 plus draft v0.2 with Go/Java/C# protobuf options and all ten TypeScript, Python, Go, Java 21, and C# 12 plain, adapter, and checked-glue outputs. - [`examples/plugin-starters`](https://github.com/zeropier/witforge/tree/main/examples/plugin-starters): zero-dependency `protocol_version = 1` emitter plugin starter kits in Rust, TypeScript, and Python. ## Troubleshooting - **`wire.lock` missing**: for the first version use `witforge lock --first`; for a new minor copy the previous lockfile and use `--against`. - **stale lockfile**: run `witforge lock`, review the printed `added`, `reserved`, `updated`, and `dropped` entries, and commit the result. - **released version changed**: restore the released WIT and lockfile; create a new version directory for the change. - **glue root path errors**: for Rust `witforge glue`, pass absolute Rust module roots (`crate::...`), not filesystem paths; for polyglot glue emitters, pass the language-specific import, module, package, or namespace roots documented in the [CLI and configuration reference](https://witforge.org/docs/reference/). - **generated output drift**: run the generator without `--check`, review the diff, and commit the result. --- # Runnable examples URL: https://witforge.org/docs/examples/ The repository contains three runnable examples with committed generated output. ## Single version [`examples/single`](https://github.com/zeropier/witforge/tree/main/examples/single) exercises: - one contract version; - `witforge.toml`; - Rust, protobuf, JSON Schema, and glue generation; - committed output checked by every generator's `--check` mode. ```sh git clone https://github.com/zeropier/witforge.git cd witforge/examples/single witforge check wit/v0.1 witforge rust --config witforge.toml witforge proto --config witforge.toml witforge schema --config witforge.toml witforge glue --config witforge.toml ``` The exact generated files are under [`examples/single/generated`](https://github.com/zeropier/witforge/tree/main/examples/single/generated). The [generated-output guide](https://witforge.org/docs/generated-output/) walks through representative sections. ## Evolved contract [`examples/evolved`](https://github.com/zeropier/witforge/tree/main/examples/evolved) contains released `v0.1` and draft `v0.2`. It demonstrates lock continuity, `diff`, release freezing, and generated version adapters. ```sh cd witforge/examples/evolved witforge check wit/v0.2 --against wit/v0.1/wire.lock witforge diff wit/v0.1 wit/v0.2 witforge rust --config witforge.toml ``` The example adds defaultable fields. Version-adapter generation accepts them, but `diff --check` still reports a source/generated-API break. Use plain `diff` to review the example; add `--check` when project policy forbids those changes. ## Polyglot contract [`examples/polyglot`](https://github.com/zeropier/witforge/tree/main/examples/polyglot) contains released `v0.1` and draft `v0.2` (adding `priority: option` on `item`), configuring protobuf file options alongside all five built-in non-Rust ecosystems in one [`witforge.toml`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/witforge.toml): - protobuf with Go, Java, and C# placement options (`generated/proto`); - TypeScript strict ESM plain types, `convert.ts`, and `@bufbuild/protobuf` glue (`generated/ts`, `generated/ts-glue`); - Python 3.11+ stdlib plain types, `convert.py`, and `google.protobuf` glue (`generated/py`, `generated/py_glue`); - Go 1.22+ stdlib plain packages, `convert/`, and `google.golang.org/protobuf` glue (`generated/go`, `generated/go-glue`); - Java 21+ records and sealed interfaces, `Convert.java`, and `com.google.protobuf` glue (`generated/java`, `generated/java-glue`); - C# 12+ / .NET 8+ records, `Convert.cs`, and `Google.Protobuf` glue (`generated/csharp`, `generated/csharp-glue`). ```sh cd witforge/examples/polyglot witforge check wit witforge generate --config witforge.toml --check witforge generate --config witforge.toml --only proto,ts,ts-glue --check ``` The committed outputs live under [`examples/polyglot/generated`](https://github.com/zeropier/witforge/tree/main/examples/polyglot/generated), and the [generated-output guide](https://witforge.org/docs/generated-output/#polyglot-outputs) shows line-verified excerpts for every language. ## Plugin starter kits [`examples/plugin-starters`](https://github.com/zeropier/witforge/tree/main/examples/plugin-starters) contains zero-dependency `protocol_version = 1` emitter plugin starter kits in Rust, TypeScript (Node.js 20+), and Python 3.11+ that read Contract IR v1 from stdin and agree byte-for-byte on output and diagnostics under `witforge plugin starter`. Generated output is committed for review and checked for drift in CI (or run `witforge generate --config witforge.toml --check` to verify every configured emitter in one step). You can also run `witforge inspect wit --json` to inspect any example's versioned contract IR, or `witforge doc wit --out preview-doc` to preview generated Markdown contract reference pages. Run any generator without `--check` to update committed files, review the diff, then run the same command with `--check`. --- # Contract authoring URL: https://witforge.org/docs/contract-authoring/ ## Layout ```text wit/ released v0.1/ contract.wit wire.lock v0.2/ contract.wit wire.lock ``` A directory named `vX.Y` contains WIT package version `X.Y.0`. Released versions are immutable. ## First version To scaffold `wit/v0.1/contract.wit`, an initial `wire.lock`, and `witforge.toml` in one command, run `witforge init --package example:checker`. To lock and validate an existing directory by hand: ```sh witforge lock wit/v0.1 --first witforge check wit/v0.1 ``` Commit both WIT and `wire.lock`. ## WIT example ```wit package example:checker@0.1.0; interface api { record request { text: string, } record diagnostic { start: u32, end: u32, message: string, } check: func(input: request) -> list; } world plugin { export api; } ``` Use named records instead of tuples and explicit IDs/records instead of resources when the contract must cross Rust, polyglot emitters, protobuf, and JSON Schema. ## Supported types, stability annotations, and inspection The supported subset includes records, variants, enums, flags, aliases, `use` aliases, `char`, lists, fixed-length lists (`list`, `1 <= N <= 65536`), primitive-keyed maps (`map` with `bool`, integer, `char`, or `string` keys), options, results, named interface functions, and worlds. Standard WIT stability annotations (`@since`, `@unstable`, and `@deprecated`) propagate into generated Rust docs/attributes, polyglot doc comments and deprecation annotations (`@deprecated`, `// Deprecated:`, `@Deprecated`, `[Obsolete]`), protobuf comments/options, JSON Schema metadata, and generated Markdown docs. Set `[project..policy].forbid-unstable-in-release = true` (or pass `witforge release --forbid-unstable`) to block releasing `@unstable` items. Run `witforge inspect wit` for a concise contract summary, or `witforge inspect wit --json` to export the deterministic, versioned JSON contract IR (`version: 1`) for downstream tools. ## Dependencies Place standard WIT dependencies under each version's `deps/` directory. All versions within one major must resolve an identical dependency graph (use `witforge deps sync` / `witforge deps sync --check` to keep `deps/` in sync across unreleased versions of a major without touching released versions); across majors, dependencies may be upgraded or changed and are scoped per major. witforge emits referenced dependency bindings and glue with package-qualified identity. See the [dependency specification](https://github.com/zeropier/witforge/blob/main/docs/design/dependencies.md) for layout and generated modules. --- # Configuring generation URL: https://witforge.org/docs/generation/ ## Commands ```sh witforge rust wit --out generated/rust witforge proto wit --out generated/proto witforge schema wit --out generated/schema witforge glue wit --out generated/glue \ --plain-root crate::plain \ --proto-root crate::proto witforge doc wit --out generated/doc ``` `--plain-root` and `--proto-root` on `witforge glue` are absolute Rust module paths used by generated glue (not filesystem paths). Accepted forms are `crate`, `crate::...`, `::crate_name::...`, or an external crate name (`other::...`). Relative paths starting with `self` or `super` are refused because glue references the roots from nested modules at multiple depths; write `crate::...` for modules inside your own crate, and prefix an external crate with `::` if its name matches a generated module. The same rules apply to `plain-root` and `proto-root` in `[project..glue]`. Ten additional built-in commands target TypeScript (`ts`, `ts-glue`), Python (`py`, `py-glue`), Go (`go`, `go-glue`), Java (`java`, `java-glue`), and C# (`csharp`, `csharp-glue`), each following the same `--out`, `--check`, and `--diff` conventions. Use `witforge conformance --out ` to export the deterministic cross-language protobuf conformance bundle, and `witforge plugin ` to run a third-party emitter plugin. See [Non-Rust implementations](https://witforge.org/docs/non-rust/) and the [CLI and configuration reference](https://witforge.org/docs/reference/) for every language flag and root syntax. ## Configuration ```toml version = 1 [project.example] root = "wit" [project.example.rust] out = "generated/rust" serde = true # no-std = true # opt-in `#![no_std]` + `alloc` paths (CLI: `--no-std` / `--std`) # eq-hash = true # opt-in `Eq, Hash` on float-free types (CLI: `--eq-hash` / `--no-eq-hash`) # try-from = true # opt-in `TryFrom` impls in `convert.rs` (CLI: `--try-from` / `--no-try-from`) [project.example.proto] out = "generated/proto" # go-package = "github.com/acme/contracts/gen/go" # java-package = "com.acme.contracts" # java-multiple-files = true # java-outer-classname = "ContractProto" # csharp-namespace = "Acme.Contracts" # # [project.example.proto.packages."example.plugin.v0"] # go-package = "github.com/acme/contracts/custom/v0;customv0" [project.example.schema] out = "generated/schema" # draft = "2020-12" # Draft 7 default, opt-in Draft 2020-12 (CLI: `--draft 7|2020-12`) [project.example.glue] out = "generated/glue" plain-root = "crate::plain" proto-root = "crate::proto" # no-std = true # opt-in `#![no_std]` + `alloc` paths (CLI: `--no-std` / `--std`) # [project.example.doc] # out = "generated/doc" # Polyglot emitters (any subset may be configured alongside Rust; see examples/polyglot/witforge.toml): # [project.example.typescript] # out = "generated/ts" # [project.example.typescript-glue] # out = "generated/ts-glue" # plain-root = "../ts" # proto-root = "../proto" # [project.example.python] # out = "generated/py" # [project.example.python-glue] # out = "generated/py_glue" # plain-root = "..py" # proto-root = "..proto" # [project.example.go] # out = "generated/go" # go-module = "example.com/acme/contracts/gen/go" # [project.example.go-glue] # out = "generated/go-glue" # go-module = "example.com/acme/contracts/gen/go-glue" # plain-root = "example.com/acme/contracts/gen/go" # proto-root = "example.com/acme/contracts/gen/proto" # [project.example.java] # out = "generated/java" # java-package = "com.acme.contracts.plain" # [project.example.java-glue] # out = "generated/java-glue" # java-package = "com.acme.contracts.glue" # plain-root = "com.acme.contracts.plain" # proto-root = "com.acme.contracts.proto" # [project.example.csharp] # out = "generated/csharp" # csharp-namespace = "Acme.Contracts.Plain" # [project.example.csharp-glue] # out = "generated/csharp-glue" # csharp-namespace = "Acme.Contracts.Glue" # plain-root = "Acme.Contracts.Plain" # proto-root = "Acme.Contracts.Proto" # [project.example.policy] # diff-check = ["wire", "decode"] # forbid-unstable-in-release = true ``` Then run every configured built-in emitter at once, narrow to a subset with `--only`, or opt in to configured plugins with `--allow-plugins`: ```sh witforge generate --config witforge.toml witforge generate --config witforge.toml --only rust,proto --check witforge generate --config witforge.toml --allow-plugins --check witforge generate --config witforge.toml --check ``` Inside a project directory or any subdirectory below it within the Git repository, `witforge.toml` is discovered upwards automatically (`witforge generate`, `witforge rust`, etc.); pass `--no-config` to disable discovery. Individual commands (`witforge rust`, `proto`, `schema`, `glue`, `doc`, `ts`, `ts-glue`, `py`, `py-glue`, `go`, `go-glue`, `java`, `java-glue`, `csharp`, `csharp-glue`, and `plugin`) also continue to accept `--config witforge.toml` or explicit CLI flags. Paths inside `witforge.toml` (`root`, `released`, and every `out`) are resolved relative to the configuration file (or used as given when absolute, including `..` components) and are never shell-expanded: a path starting with `~` or containing `$` or `%VAR%` is refused with exit `2`. Save `witforge.toml` as UTF-8 without a byte-order mark (BOM); `wit/released` is accepted with or without a leading UTF-8 BOM. Under a WIT root, every entry whose name starts with `v` or `V` followed by a digit must be a valid `v.` directory (for example `v0.1`, `v1.0`). Near-miss directories or files such as `v0.2.0`, `V0.2`, `v0.2-rc1`, `v00.2`, `v1`, or overflowing version numbers are refused rather than silently skipped; unrelated entries such as `vendor`, `versions.md`, `released`, and hidden files are ignored. ## Output ownership Each emitter and project needs its own non-overlapping output directory. Every generated file starts with an ownership header naming both the generator and the contract (`// @generated by witforge (, :); do not edit.`, `// Code generated by witforge (, :); DO NOT EDIT.` for Go, `# @generated by witforge (, :); do not edit.` for Python, `` for Markdown, or the matching JSON Schema `$comment` prefix), except allowlisted headerless marker files such as PEP 561 `py.typed`. A generator only overwrites or removes files that carry its own header (or the legacy pre-0.6.0 shared header, which is adopted and rewritten when you regenerate). - An output directory that already holds files from another generator or another contract is refused with exit `2` before anything is written. - A `witforge.toml` configuration whose `out` paths coincide or nest (including across projects or through symlinks) is refused as a usage error (exit `2`). - Symlinks, directories, and unowned files at expected output paths are refused; unowned files at other paths are left untouched. - Every generator supports `--check`, which writes nothing and fails on missing, changed, or extra generated files (and exits `2` if a foreign generator's or contract's file is present). ## Inspect the result The [generated-output guide](https://witforge.org/docs/generated-output/) shows current Rust, protobuf, JSON Schema, glue, version-adapter, and polyglot (TypeScript, Python, Go, Java, and C#) output from the committed runnable examples. Run `witforge doc` (or configure `[project..doc]`) to generate deterministic Markdown contract reference pages and per-version changelogs, or run `witforge inspect --json` to export the versioned JSON contract IR. The full example files are checked with `--check` in this repository's CI. ## Third-party emitter plugins External tools can target additional languages or frameworks without forking `witforge` by implementing the versioned JSON-over-stdio plugin protocol (`protocol_version = 1`, specified in [`docs/design/plugins.md`](https://github.com/zeropier/witforge/blob/main/docs/design/plugins.md)). ### Invoking a plugin Invoke a plugin explicitly by name (matching `^[a-z0-9][a-z0-9-]*$`, up to 64 ASCII characters): ```sh witforge plugin kotlin wit --out generated/kotlin --option package=com.acme.api witforge plugin kotlin wit --out generated/kotlin --option package=com.acme.api --check ``` `witforge` resolves `witforge-gen-` strictly by scanning absolute directories in `PATH` (using `PATHEXT` on Windows). Empty and relative `PATH` entries (including `.`) are skipped, and the current working directory is never searched implicitly. To run a local or pinned binary during development, pass `--plugin-bin ` on the CLI: ```sh witforge plugin kotlin wit --out generated/kotlin --plugin-bin ./bin/witforge-gen-kotlin ``` Plugin output directories, default key-value options, and timeout limits may also be stored in `witforge.toml`: ```toml [project.example.plugins.kotlin] out = "generated/kotlin" timeout-secs = 30 [project.example.plugins.kotlin.options] package = "com.acme.api" ``` ### Authoring a plugin 1. Read a single UTF-8 JSON request object from `stdin` containing `protocol_version` (`1`), `ir_version` (`1`), `plugin`, `contract_id`, `package`, `ownership` (with `generator_id` `"plugin:"` and pre-formatted line-1 ownership headers for `line_comment`, `go_generated`, `hash_comment`, `json_comment`, and `html_comment`), normalized `options`, and the validated root `ir` from `witforge inspect --json`. Host-specific filesystem paths such as `--out` and `WIT_ROOT` are never sent to the plugin so output remains machine-independent. 2. Emit a single UTF-8 JSON response object on `stdout` with `protocol_version: 1`, optional `header_style` (default `"line_comment"`), an ordered `files` list (`{ "path", "content", "marker?" }`), and optional `diagnostics` (`{ "severity", "message", "path?", "code?" }`), then exit `0`. 3. Begin every non-marker file on line 1 with `request.ownership.headers[header_style]`. Use `"marker": true` only for small allowlisted marker files (up to 4 KiB, such as an empty `py.typed`). ### Security boundaries and limits - **Explicit opt-in only:** `witforge generate` validates plugin config keys, output-root guards, and output-root distinctness, and never executes configured plugins unless `--allow-plugins` is passed explicitly on the CLI (passing `--only plugins` without `--allow-plugins` exits `2` with `WF9001`; plugin-only projects without `--allow-plugins` exit `2` with instructions to pass `--allow-plugins` or invoke `witforge plugin `, while mixed multi-project configs run their built-in generators and skip plugin-only projects). - **No executable paths in config:** `[project..plugins.]` rejects unknown keys such as `plugin-bin`, `bin`, `command`, or `path` with exit `2` (`WF9003`). Only the CLI flag `--plugin-bin` may specify an explicit executable path. - **Pre-flight contract and path safety:** `witforge` validates the WIT contract, lockfiles, and output-root guards before spawning the plugin. Before writing any file, `witforge` enforces POSIX relative path rules, refuses traversal (`..`), absolute paths, backslashes, control characters, duplicates, case-insensitive and prefix collisions, Windows reserved device names, missing or foreign ownership headers, and symlinks, and normalizes line endings to LF. - **Bounded execution:** `stdin`, `stdout`, and `stderr` are piped concurrently with hard caps (default timeout `30s` up to `3600s`, `64 MiB` stdout, `1 MiB` stderr, `4096` files, `16 MiB` per file, `64 MiB` total emitted content, `1024` diagnostics); runaway or timed-out processes are terminated and reported with exit `2` (`WF9004`). Plugin `severity: "error"` diagnostics prevent any writes and exit `1`. --- # Wiring and installation URL: https://witforge.org/docs/wiring/ This guide takes an empty Rust crate to a compiling plain-Rust and protobuf round trip, explains how to install and verify prebuilt binaries, and covers the `--lock`, `--released`, and `released` configuration options. ## Install and verify Choose the channel that matches your team's toolchain; every channel runs the same single native `witforge` Rust binary with zero runtime dependencies added to generated plain types: | Channel | Best for | Section | |---|---|---| | `crates.io` (`cargo install` / `cargo binstall`) | Rust crates and custom platforms | [From crates.io](#from-cratesio) | | PyPI (`uvx`, `pipx`, `pip`) | Python 3.11+ repositories | [From PyPI](#from-pypi-uvx-pipx-pip) | | npm (`npx`, `npm`, `pnpm`) | TypeScript / Node.js repositories | [From npm](#from-npm-npx-npm-pnpm) | | Homebrew, `aqua`, and `mise` | macOS, Linux, and Go `//go:generate` teams | [From Homebrew, `aqua`, and `mise`](#from-homebrew-aqua-and-mise) | | NuGet (`Witforge.Tools`) and Maven (`witforge-native`) | .NET 8+ MSBuild and Java 21+ Gradle / Maven builds | [From NuGet and Maven](#from-nuget-witforgetools-and-maven-witforge-native) | | Prebuilt GitHub Release archives | Air-gapped CI and manual SLSA verification | [Prebuilt archives](#prebuilt-archives) | ### From crates.io ```sh cargo install witforge-cli --version 0.12.0 --locked witforge --version ``` ### From PyPI (`uvx`, `pipx`, `pip`) Python teams can run or pin the native `witforge` CLI wheel without installing Rust or Cargo (packaged and smoked on every release tag via `release.yml`, and published on PyPI once PyPI Trusted Publishing is enabled; Linux wheels bundle the static `musl` binary for both `manylinux_2_17` and `musllinux_1_1`, alongside native macOS Intel/Apple silicon and Windows x86_64 wheels): ```sh VERSION=0.12.0 # Ephemeral pinned invocation with uvx: uvx "witforge==${VERSION}" --version uvx "witforge==${VERSION}" generate --config witforge.toml --only proto,py,py-glue --check # Persistent CLI install with uv or pipx: uv tool install "witforge==${VERSION}" pipx install "witforge==${VERSION}" # Project virtualenv pin with pip: pip install "witforge==${VERSION}" ``` The PyPI wheel contains zero Python runtime dependencies and executes no postinstall network downloads. Plain Python code generated by `witforge py` also has zero runtime dependencies. ### From npm (`npx`, `npm`, `pnpm`) TypeScript and Node.js teams can run or pin `@witforge/cli` without installing Rust or Cargo (packaged and smoked on every release tag via `release.yml`, and published on npm once npm Trusted Publishing is enabled; uses exact-pinned per-platform `optionalDependencies` with static Linux `musl` binaries, zero `postinstall` scripts, and `WITFORGE_BINARY_PATH` offline override): ```sh VERSION=0.12.0 # Ephemeral pinned invocation with npx: npx --yes "@witforge/cli@${VERSION}" --version npx --yes "@witforge/cli@${VERSION}" generate --config witforge.toml --only proto,ts,ts-glue --check # Pinned devDependency in package.json: npm install --save-dev --save-exact "@witforge/cli@${VERSION}" npm exec witforge -- generate --config witforge.toml --only proto,ts,ts-glue --check ``` `@witforge/cli` works cleanly under `npm ci --ignore-scripts`, `pnpm`, and behind corporate proxies. Plain TypeScript code generated by `witforge ts` has zero runtime dependencies. ### From Homebrew, `aqua`, and `mise` macOS, Linux, and Go teams can install the verified static GitHub Release archives through Homebrew (using the deterministic `Formula/witforge.rb` rendered by `ci/render-homebrew-formula.sh` for `zeropier/homebrew-tap`) or through `aqua` and `mise` (`packaging/aqua/registry.yaml`, verifying both `.sha256` checksums and GitHub SLSA build provenance attestations): ```sh VERSION=0.12.0 # Homebrew tap (once zeropier/homebrew-tap is populated from a release's Formula/witforge.rb): brew install zeropier/tap/witforge witforge --version # mise (using the aqua registry backend once merged upstream, or a local aqua registry): mise use "aqua:zeropier/witforge@${VERSION}" ``` On Linux, both the Homebrew formula and `packaging/aqua/registry.yaml` select the static `musl` archive (`x86_64-unknown-linux-musl` / `aarch64-unknown-linux-musl`), so Ubuntu LTS, Debian, RHEL, and Alpine containers work without a glibc 2.39 floor (for `mise` on Linux distributions with `glibc < 2.39`, set `libc = "musl"` or `MISE_LIBC=musl` so `mise` does not swap to the sibling Ubuntu 24.04 `-gnu` archive). See [Go `//go:generate` with `mise` and `aqua`](https://witforge.org/docs/non-rust/#go-gogenerate-workflow) for a pinned Go code-generation setup. ### From NuGet (`Witforge.Tools`) and Maven (`witforge-native`) .NET 8+ and Java 21+ repositories can integrate `witforge` directly into `dotnet build`, Gradle, or Maven using thin build-tool wrappers staged in each tag release's `dotnet-jvm-packages` workflow artifact (ready for local or private enterprise NuGet/Maven feeds, with zero runtime dependencies): - **.NET / MSBuild (`packaging/dotnet/`):** `Witforge.Tools` is a `developmentDependency` NuGet package (`PrivateAssets="all"`, zero `lib/` assemblies, zero `buildTransitive/` targets) bundling the five native release binaries under `tools//` (static `musl` on Linux). Its MSBuild targets run with `BeforeTargets="Protobuf_BeforeCompile;Protobuf_Compile;BeforeCompile"` so `witforge` executes strictly ahead of `Grpc.Tools` and C# compilation. See [MSBuild integration for .NET](https://witforge.org/docs/non-rust/#msbuild-integration-for-net). - **JVM / Gradle and Maven (`packaging/jvm/`):** classifier-addressed `org.witforge:witforge-native::@exe` artifacts follow the standard `osdetector` / `os-maven-plugin` scheme (`linux-x86_64`, `linux-aarch_64`, `osx-x86_64`, `osx-aarch_64`, `windows-x86_64`) with SHA-256 verification before execution and explicit ordering ahead of `protoc` and Java compilation. See [Gradle and Maven integration for JVM](https://witforge.org/docs/non-rust/#gradle-and-maven-integration-for-jvm). ### Prebuilt archives Prebuilt archives are published on [GitHub Releases](https://github.com/zeropier/witforge/releases) for native targets (each archive contains the executable beside `LICENSE-APACHE`, `LICENSE-MIT`, and `README.md`, plus a sibling `.sha256` file and, from 0.7.0, a SLSA build provenance attestation): | Platform | Target | Notes | |---|---|---| | Linux x86_64 (static) | `x86_64-unknown-linux-musl` | Portable across glibc/Alpine (from 0.8.0) | | Linux x86_64 (gnu) | `x86_64-unknown-linux-gnu` | glibc >= 2.39 (Ubuntu 24.04 runner) | | Linux arm64 (static) | `aarch64-unknown-linux-musl` | Portable across glibc/Alpine (from 0.8.0) | | Linux arm64 (gnu) | `aarch64-unknown-linux-gnu` | glibc >= 2.39, published from 0.7.0 | | macOS Intel | `x86_64-apple-darwin` | Native binary | | macOS Apple silicon | `aarch64-apple-darwin` | Native binary | | Windows x86_64 | `x86_64-pc-windows-msvc` | Native binary | Windows `arm64` builds are **not** provided; install from crates.io with `cargo install witforge-cli --locked` on that target. `cargo binstall witforge-cli` is also configured via `[package.metadata.binstall]`. Download and verify a prebuilt archive before extracting it: ```sh VERSION=0.12.0 TARGET=x86_64-unknown-linux-musl BASE="https://github.com/zeropier/witforge/releases/download/v${VERSION}" curl -sSfLO "${BASE}/witforge-${VERSION}-${TARGET}.tar.gz" curl -sSfLO "${BASE}/witforge-${VERSION}-${TARGET}.tar.gz.sha256" sha256sum -c "witforge-${VERSION}-${TARGET}.tar.gz.sha256" # Releases 0.12.0 and later carry a GitHub build provenance attestation under zeropier/witforge: gh attestation verify "witforge-${VERSION}-${TARGET}.tar.gz" \ --repo zeropier/witforge \ --signer-workflow zeropier/witforge/.github/workflows/release.yml tar -xzf "witforge-${VERSION}-${TARGET}.tar.gz" ./witforge --version ``` For pre-transfer releases `0.7.0` through `0.11.0`, pass `--owner asamarts --signer-workflow asamarts/witforge/.github/workflows/release.yml` to `gh attestation verify` because GitHub keeps pre-transfer attestations indexed under the original owner. On macOS, use `shasum -a 256 -c` if `sha256sum` is unavailable. ## Layout: committed output vs. `build.rs` Two layouts are possible: 1. **Commit witforge output under `src/generated/` (recommended):** `witforge generate` writes plain Rust, `.proto`, JSON Schema, and glue into committed directories, and `build.rs` only compiles the committed `.proto` files with `prost-build` (`0.14`) and `protox` (`0.10`, so no system `protoc` binary is required). CI runs `witforge generate --check` to catch drift, code review shows exact API changes in pull requests, and downstream crates build with plain `cargo` without installing `witforge`. 2. **Generate during `build.rs`:** invokes `witforge` into `OUT_DIR`. This avoids committing generated files, but `witforge --check` cannot guard committed per-version modules in CI and every contributor needs the matching `witforge` binary during `cargo build`. The walkthrough below uses the committed layout. Generated glue targets **`prost` / `prost-build` 0.14** (and optionally `pbjson` / `pbjson-build` 0.9 for proto3 JSON). ## Empty crate to compiling round trip Create the crate layout: ```text my-contract-crate/ Cargo.toml build.rs witforge.toml wit/ v0.1/ contract.wit wire.lock src/ lib.rs main.rs generated/ rust/ proto/ schema/ glue/ ``` ```sh mkdir -p my-contract-crate/wit/v0.1 my-contract-crate/src ``` Save `my-contract-crate/Cargo.toml`: ```toml [package] name = "my-contract-crate" version = "0.1.0" edition = "2024" [dependencies] prost = "0.14" [build-dependencies] prost-build = "0.14" protox = "0.10" ``` Save `my-contract-crate/wit/v0.1/contract.wit`: ```wit package example:greeter@0.1.0; interface api { record greeting { text: string, repeat: option, } greet: func(name: string) -> greeting; } world hello { export api; } ``` Save `my-contract-crate/witforge.toml`: ```toml version = 1 [project.greeter] root = "wit" [project.greeter.rust] out = "src/generated/rust" [project.greeter.proto] out = "src/generated/proto" [project.greeter.schema] out = "src/generated/schema" [project.greeter.glue] out = "src/generated/glue" plain-root = "crate::plain" proto-root = "crate::proto" ``` Lock the contract, validate it, and generate all four outputs: ```sh witforge lock my-contract-crate/wit/v0.1 --first witforge check my-contract-crate/wit witforge generate --config my-contract-crate/witforge.toml witforge generate --config my-contract-crate/witforge.toml --check ``` Save `my-contract-crate/build.rs`, which compiles the committed `.proto` schema using `protox` (pure Rust, no external `protoc`) and `prost-build`: ```rust use std::path::PathBuf; fn main() -> Result<(), Box> { let proto_dir = PathBuf::from("src/generated/proto"); println!("cargo:rerun-if-changed={}", proto_dir.display()); let fds = protox::compile([proto_dir.join("v0.proto")], [&proto_dir])?; prost_build::Config::new().compile_fds(fds)?; Ok(()) } ``` Save `my-contract-crate/src/lib.rs`, exposing `plain`, `proto`, and `glue` at the exact module paths configured by `plain-root = "crate::plain"` and `proto-root = "crate::proto"`: ```rust #![deny(missing_docs)] //! Contract crate wiring witforge's generated plain Rust, prost protobuf types, and glue. /// Generated plain Rust contract types, traits, and worlds. #[path = "generated/rust/mod.rs"] pub mod plain; /// Prost-generated protobuf messages compiled by `build.rs`. pub mod proto { /// Wire schema for major version 0. #[allow(clippy::all, missing_docs)] pub mod v0 { include!(concat!(env!("OUT_DIR"), "/example.greeter.v0.rs")); } } /// Generated plain-Rust <-> prost protobuf glue. #[path = "generated/glue/mod.rs"] pub mod glue; ``` Save `my-contract-crate/src/main.rs` to round-trip a plain Rust value through generated glue and protobuf binary encoding: ```rust use my_contract_crate::{glue, plain, proto}; use prost::Message as _; fn main() { let original = plain::v0_1::api::Greeting { text: "hello".to_string(), repeat: Some(3), }; let wire = glue::v0::api::greeting::to_proto(&original); let encoded = wire.encode_to_vec(); let decoded_wire = proto::v0::ApiGreeting::decode(encoded.as_slice()).expect("decode proto"); let roundtripped = glue::v0::api::greeting::from_proto(decoded_wire).expect("glue from_proto"); assert_eq!(roundtripped, original); } ``` Run `cargo run` inside `my-contract-crate/` (the repository test suite builds and runs these exact files verbatim): ```sh cargo run --manifest-path my-contract-crate/Cargo.toml ``` ## Module roots, dependencies, `rustfmt`, and lints - **Module path forms:** `--plain-root` / `plain-root` and `--proto-root` / `proto-root` must be absolute Rust module paths: `crate`, `crate::...`, `::crate_name::...`, or an external crate name (`other::...`). Relative paths (`self::...`, `super::...`) and unprefixed generated module names (`v0`, `witforge_deps`, etc.) are refused with exit `2`. - **Contracts with `deps/`:** When a contract uses standard `deps/` packages, `witforge proto` emits `..v.proto` files alongside `v.proto`. Pass all `.proto` files in `src/generated/proto/` to `protox::compile(...)`, set `prost_build::Config::new().include_file("prost_include.rs")`, and include `concat!(env!("OUT_DIR"), "/prost_include.rs")` inside `pub mod proto { ... }` so prost emits the package-nested module tree (`crate::proto::::::v`) that glue expects. - **Formatting and lints:** Generated plain Rust and glue already match default `rustfmt` (Editions 2021 and 2024), pass default Clippy (`-D warnings`), and document every public item (`-D missing_docs`) without needing attributes. If your crate uses a non-default `rustfmt.toml`, add `#[rustfmt::skip]` on the `pub mod plain;` and `pub mod glue;` declarations. - **`#![no_std]` + `alloc` crates:** Set `no-std = true` under `[project..rust]` and `[project..glue]` (or pass `--no-std` on `rust`, `glue`, or `generate`). Generated Rust, `convert.rs`, and glue emit `::alloc::string::String`, `::alloc::vec::Vec`, `::alloc::collections::BTreeMap`, `::core::option::Option`, `::core::result::Result`, and `::core::error::Error` with no `::std::` references. In your crate, declare `#![no_std]` and `extern crate alloc;`, and depend on `prost` with `default-features = false, features = ["derive"]` (and `serde` with `default-features = false, features = ["alloc", "derive"]` if `serde = true`). When a `#![no_std]` contract uses `map`, configure `prost_build::Config::btree_map(["."])` in `build.rs` (or via `witforge_build::Config::with_prost_config`) so prost emits `BTreeMap` instead of `std::collections::HashMap`. - **Additional opt-in Rust derives and adapters:** Set `eq-hash = true` (`--eq-hash`) to derive `Eq` and `Hash` on float-free generated types, and `try-from = true` (`--try-from`) to emit `TryFrom` implementations in `convert.rs` for converted nominal types. See [Generation](https://witforge.org/docs/generation/) for the full `witforge.toml` layout. ## Simplifying `build.rs` with `witforge-build` Instead of wiring `protox`, `prost-build`, and manual `cargo:rerun-if-changed` directives by hand, you can use the optional `witforge-build` helper crate (first published on crates.io starting in `0.8.0`) in `[build-dependencies]`: ```toml [build-dependencies] witforge-build = "0.12.0" ``` ```rust // build.rs fn main() -> Result<(), Box> { witforge_build::compile_protos("src/generated/proto")?; Ok(()) } ``` Then include the generated `prost_include.rs` in `src/lib.rs`: ```rust #[allow(clippy::all, missing_docs)] pub mod proto { include!(concat!(env!("OUT_DIR"), "/prost_include.rs")); } ``` `witforge-build` discovers every `.proto` file in deterministic order, emits per-file `cargo:rerun-if-changed` directives, compiles with pure-Rust `protox` (no external `protoc` needed), and generates a `prost_include.rs` layout matching `witforge glue` for both standalone contracts (`crate::proto::v0::*`) and contracts with `deps/` (`crate::proto::::::v::*`). Enable `features = ["pbjson"]` and call `witforge_build::Config::new().pbjson(true).compile_protos("src/generated/proto")?` to also emit and include proto3-JSON `serde` implementations via `pbjson-build`. ## Released-directory options (`--lock`, `--released`, and `released`) - **`--lock `** (on `check` and `lock` for a single version directory): overrides the lockfile path instead of the default `/wire.lock`. `witforge lock` still refuses any `--lock` path located inside a released directory. - **`--released `** (on `check`, `lock`, `rust`, `proto`, `schema`, `glue`, `doc`, `ts`, `ts-glue`, `py`, `py-glue`, `go`, `go-glue`, `java`, `java-glue`, `csharp`, `csharp-glue`, `plugin`, `generate`, `new-version`, `deps sync`, `release`, `retire`, `inspect`, and `freeze`): overrides the released-version manifest path. The defaults are: - `/../released` for single-version commands (`check `, `lock `, `release `, `retire `); - `/released` for whole-root `check`, `new-version`, `deps sync`, `inspect` (refused on single version directories), generators, and `freeze`. A missing default manifest means no versions are released; an explicitly passed missing manifest exits `2`. For `lock`, an explicit `--released` manifest is checked **in addition to** the default manifests (never instead of them), so an explicit manifest cannot unlock a released directory. - **`released = "..."` in `witforge.toml`:** sets the project's released-version manifest path relative to `witforge.toml` (overridden by CLI `--released`). - **Version retirement (` retired`):** marking a contiguous oldest prefix of released versions as `retired` in the manifest keeps their directories frozen on disk while removing them from generated outputs on the next run. See [Contract evolution](https://witforge.org/docs/evolution/) for major-version and retirement rules, and [CLI and configuration reference](https://witforge.org/docs/reference/) for every flag and key. --- # Real generated output URL: https://witforge.org/docs/generated-output/ This page shows representative output produced by the current repository build from the committed [`examples/single`](https://github.com/zeropier/witforge/tree/main/examples/single) contract. The repository commits these files and CI runs every generator with `--check`, so the linked files are executable examples rather than illustrative pseudocode. ```sh witforge rust --config examples/single/witforge.toml witforge proto --config examples/single/witforge.toml witforge schema --config examples/single/witforge.toml witforge glue --config examples/single/witforge.toml ``` The source WIT defines an `item` record, an enum, flags, a variant, and one interface function. Its [`wire.lock`](https://github.com/zeropier/witforge/blob/main/examples/single/wit/v0.1/wire.lock) assigns the field, case, parameter, and method numbers shown below. Every fenced generated-output excerpt is checked line-for-line against the linked committed file; generated comments, unrelated definitions, and surrounding module context may be omitted. ## Plain Rust The Rust emitter writes owned values and one trait per WIT interface that declares functions. WIT names become Rust identifiers; no Wasm runtime types appear in this output. ```rust pub mod types { #[derive(Debug, Clone, PartialEq)] pub struct Item { pub id: u64, pub name: ::std::string::String, pub tags: ::std::vec::Vec<::std::string::String>, pub note: ::std::option::Option<::std::string::String>, } #[derive(Debug, Clone, PartialEq)] pub enum Status { Accepted, Rejected, } #[derive(Debug, Clone, PartialEq)] pub enum Event { Started, Item(Item), Finished(Status), } } pub mod ingest { pub type Item = super::types::Item; pub type Event = super::types::Event; pub trait Ingest { fn submit(&self, item: Item) -> Event; } } ``` Full files: [`v0_1.rs`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/rust/v0_1.rs), [`worlds.rs`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/rust/worlds.rs), and [`mod.rs`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/rust/mod.rs). Opt-in Rust flags enable additional profiles per project: `--serde` (`serde = true`) adds plain, format-independent `::serde::Serialize` and `::serde::Deserialize` derives using these Rust identifiers; `--no-std` (`no-std = true`) emits `#![no_std]`-compatible `::alloc::*` and `::core::*` paths; `--eq-hash` (`eq-hash = true`) derives `Eq` and `Hash` on float-free types; and `--try-from` (`try-from = true`) emits `TryFrom` impls in `convert.rs`. See [JSON projections](https://witforge.org/docs/json-projections/) for the exact Serde JSON keys, reading rules, and `serde_json` edge cases. ## Protobuf The protobuf emitter uses the numbers in `wire.lock`. Required scalar and string values use proto3 `optional` so generated glue can distinguish absence from a default value. WIT interfaces produce request and response messages plus a stable method-ID enum, not protobuf services. ```proto message TypesItem { optional uint64 id = 1; optional string name = 2; repeated string tags = 3; optional string note = 4; } message TypesEvent { oneof witforge_value { Empty started = 1; TypesItem item = 2; TypesStatus finished = 3; } } message IngestSubmitRequest { TypesItem item = 1; } message IngestSubmitResponse { TypesEvent result = 1; } enum IngestMethod { INGEST_METHOD_UNSPECIFIED = 0; INGEST_METHOD_SUBMIT = 1; } ``` Full file: [`v0.proto`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/proto/v0.proto). Generate language-specific protobuf types from this file with the normal toolchain for that language. ## JSON Schema The schema emitter writes one JSON Schema document per contract version (Draft 7 by default, or Draft 2020-12 via `--draft 2020-12` / `draft = "2020-12"`). Named WIT types live under `definitions` (or `$defs` in Draft 2020-12); records are closed objects whose properties are all required. An `option` value accepts `null`, but the containing property is still required. ```json "types/item": {"description":"One item submitted to the ingester.","type":"object","properties":{"id":{"description":"Stable item id.","type":"integer","minimum":0,"maximum":18446744073709551615},"name":{"description":"Human-readable name.","type":"string"},"tags":{"description":"Free-form tags.","type":"array","items":{"type":"string"}},"note":{"description":"Optional note.","anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","tags","note"],"additionalProperties":false}, "types/status": {"description":"The result state of an item.","type":"string","enum":["accepted","rejected"]}, ``` Full file: [`v0_1.schema.json`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/schema/v0_1.schema.json). Read [JSON Schema and Rust Serde](https://witforge.org/docs/json-projections/) before treating both projections as one JSON wire format. ## Rust/protobuf glue The glue emitter converts borrowed plain Rust values into owned prost values and validates the reverse conversion. Copy values are copied directly, owned values are cloned only when the target must own them, and already-owned identity collections move out of the protobuf value without an extra allocation. ```rust type Plain = crate::generated::rust::v0_1::types::Item; type Proto = crate::generated::proto::v0::TypesItem; /// Convert `types/item` to its protobuf representation. pub fn to_proto(value: &Plain) -> Proto { Proto { id: ::core::option::Option::Some(value.id), name: ::core::option::Option::Some(::core::clone::Clone::clone(&value.name)), tags: ::core::clone::Clone::clone(&value.tags), note: ::core::clone::Clone::clone(&value.note), } } /// Convert `types/item` from its protobuf representation. pub fn from_proto(value: Proto) -> ::core::result::Result { let ::core::option::Option::Some(v0) = value.id else { return ::core::result::Result::Err(GlueError::MissingField { field: "types/item.id", }); }; let ::core::option::Option::Some(v1) = value.name else { return ::core::result::Result::Err(GlueError::MissingField { field: "types/item.name", }); }; ::core::result::Result::Ok(Plain { id: v0, name: v1, tags: value.tags, note: value.note, }) } ``` Every line in this excerpt is copied from the generated file. Emitted Rust is produced directly by witforge (without shelling out to `rustfmt`) in `rustfmt`'s default style for both Edition 2021 and Edition 2024, and passes default Clippy lints and `#![deny(missing_docs)]`. If your crate sets non-default `rustfmt.toml` options, put `#[rustfmt::skip]` on the module declaration that includes the generated tree. Full files: [`v0.rs`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/glue/v0.rs) and [`mod.rs`](https://github.com/zeropier/witforge/blob/main/examples/single/generated/glue/mod.rs). Function helpers in the same module map WIT calls to protobuf request and response messages and expose the locked method ID: ```rust type Method = crate::generated::proto::v0::IngestMethod; type Request = crate::generated::proto::v0::IngestSubmitRequest; type Response = crate::generated::proto::v0::IngestSubmitResponse; type Params = crate::generated::rust::v0_1::ingest::Item; type Output = crate::generated::rust::v0_1::ingest::Event; /// Protobuf method identifier for `ingest#submit`. pub const METHOD: Method = Method::Submit; /// Encode request parameters for `ingest#submit`. pub fn to_request(item: &crate::generated::rust::v0_1::ingest::Item) -> Request { let v0 = super::super::super::types::item::to_proto(item); Request { item: ::core::option::Option::Some(v0), } } /// Decode request parameters for `ingest#submit`. pub fn from_request(value: Request) -> ::core::result::Result { let ::core::option::Option::Some(v0) = value.item else { return ::core::result::Result::Err(GlueError::MissingField { field: "ingest#submit.item", }); }; super::super::super::types::item::from_proto(v0) } ``` These are conversion helpers, not a transport or RPC service implementation. ## Version adapters With adjacent contract versions, `witforge rust` also writes `convert.rs`. The evolved example adds an optional priority and a list of tags; old values receive their WIT-safe defaults. ```rust /// Convert `types/task` from 0.1.0 to 0.2.0. /// /// # Errors /// /// Returns an error when the source value cannot be represented by the target version. pub fn task( value: &super::__witforge_from::types::Task, ) -> ::core::result::Result { ::core::result::Result::Ok(super::__witforge_to::types::Task { id: value.id, title: ::core::clone::Clone::clone(&value.title), done: value.done, priority: ::core::option::Option::None, tags: ::std::vec::Vec::new(), }) } ``` Full file: [`convert.rs`](https://github.com/zeropier/witforge/blob/main/examples/evolved/generated/rust/convert.rs). ## Polyglot outputs The committed [`examples/polyglot`](https://github.com/zeropier/witforge/tree/main/examples/polyglot) project compiles the same `example:ingest` contract (`v0.1` and `v0.2`, where `v0.2` adds `priority: option` to `item`) into TypeScript, Python, Go, Java 21, and C# 12 plain types, bidirectional version adapters, and checked protobuf glue in one command: ```sh witforge generate --config examples/polyglot/witforge.toml --check ``` Every excerpt below is checked line-for-line against the committed `v0.1` output under [`examples/polyglot/generated`](https://github.com/zeropier/witforge/tree/main/examples/polyglot/generated). ### TypeScript (`ts` and `ts-glue`) Strict ESM `readonly` interfaces, string literal unions, discriminated variant unions, and zero runtime dependencies: ```ts export interface Item { readonly id: bigint; readonly name: string; readonly tags: readonly string[]; readonly note: Option; } export const Status = { Accepted: "accepted", Rejected: "rejected", } as const; export type Status = (typeof Status)[keyof typeof Status]; export type Event = | { readonly tag: "started" } | { readonly tag: "item"; readonly value: Item } | { readonly tag: "finished"; readonly value: Status }; ``` Full files: [`v0_1/types.ts`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/ts/v0_1/types.ts), [`convert.ts`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/ts/convert.ts), and `@bufbuild/protobuf` glue [`v0/types.ts`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/ts-glue/v0/types.ts). ### Python 3.11+ (`py` and `py-glue`) Immutable `@dataclass(frozen=True, slots=True)` records, `StrEnum` enums, union variant types, `Protocol` interfaces, and a PEP 561 `py.typed` marker using only the Python standard library: ```python @dataclass(frozen=True, slots=True) class Item: id: int name: str tags: tuple[str, ...] note: str | None class Status(StrEnum): ACCEPTED = "accepted" REJECTED = "rejected" @dataclass(frozen=True, slots=True) class EventStarted: pass @dataclass(frozen=True, slots=True) class EventItem: value: Item @dataclass(frozen=True, slots=True) class EventFinished: value: Status Event: TypeAlias = EventStarted | EventItem | EventFinished ``` Full files: [`v0_1/types.py`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/py/v0_1/types.py), [`convert.py`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/py/convert.py), and `google.protobuf` glue [`v0/types.py`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/py_glue/v0/types.py). ### Go 1.22+ (`go` and `go-glue`) `gofmt`-formatted Go structs, closed enum constants with `Valid()` and `String()` helpers, sealed variant interfaces, and stdlib-only packages: ```go type Item struct { Id uint64 Name string Tags []string Note *string } type Status uint32 const ( StatusAccepted Status = 1 StatusRejected Status = 2 ) func (v Status) Valid() bool { switch v { case StatusAccepted, StatusRejected: return true default: return false } } func (v Status) String() string { switch v { case StatusAccepted: return "accepted" case StatusRejected: return "rejected" default: return "" } } type Event interface { isEvent() } type EventStarted struct{} func (EventStarted) isEvent() {} type EventItem struct { Value Item } func (EventItem) isEvent() {} type EventFinished struct { Value Status } func (EventFinished) isEvent() {} ``` Full files: [`v0_1/types/types.go`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/go/v0_1/types/types.go), [`convert/v0_1_to_v0_2/types/convert.go`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/go/convert/v0_1_to_v0_2/types/convert.go), and `google.golang.org/protobuf` glue [`v0/types/glue.go`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/go-glue/v0/types/glue.go). ### Java 21+ (`java` and `java-glue`) Java 21 `record` classes with defensive list/optional copies and `sealed interface` variants with exhaustive pattern-matching `permits` clauses: ```java public record Item( long id, String name, List tags, Optional note ) { public Item { Objects.requireNonNull(name, "name"); tags = WitforgeValues.copyList(tags, "tags"); note = WitforgeValues.copyOptional(note, "note"); } } ``` ```java public sealed interface Event permits Event.Started, Event.Item, Event.Finished { record Started() implements Event {} record Item(com.example.ingest.plain.v0_1.types.Item value) implements Event { public Item { Objects.requireNonNull(value, "value"); } } record Finished(Status value) implements Event { public Finished { Objects.requireNonNull(value, "value"); } } } ``` Full files: [`Item.java`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/java/com/example/ingest/plain/v0_1/types/Item.java), [`Event.java`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/java/com/example/ingest/plain/v0_1/types/Event.java), [`Convert.java`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/java/com/example/ingest/plain/Convert.java), and `com.google.protobuf` glue [`TypesGlue.java`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/java-glue/com/example/ingest/glue/v0/types/TypesGlue.java). ### C# 12+ / .NET 8+ (`csharp` and `csharp-glue`) Nullable-enabled (`#nullable enable`) immutable records with defensive copies and structural list equality, enum wire-name helpers, and closed `abstract record` variant hierarchies: ```csharp public sealed record Item { private readonly ulong _id; private readonly string _name; private readonly global::System.Collections.Generic.IReadOnlyList _tags; private readonly string? _note; public Item(ulong id, string name, global::System.Collections.Generic.IReadOnlyList tags, string? note) { _id = id; _name = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(name, "name"); _tags = global::Example.Ingest.Plain.WitforgeValues.CopyNonNullList(tags, "tags"); _note = note; } public ulong Id { get => _id; init => _id = value; } public string Name { get => _name; init => _name = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "Name"); } public global::System.Collections.Generic.IReadOnlyList Tags { get => _tags; init => _tags = global::Example.Ingest.Plain.WitforgeValues.CopyNonNullList(value, "Tags"); } public string? Note { get => _note; init => _note = value; } public void Deconstruct(out ulong id, out string name, out global::System.Collections.Generic.IReadOnlyList tags, out string? note) { id = Id; name = Name; tags = Tags; note = Note; } public bool Equals(Item? other) { if (object.ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } return global::System.Collections.Generic.EqualityComparer.Default.Equals(_id, other._id) && global::System.Collections.Generic.EqualityComparer.Default.Equals(_name, other._name) && global::Example.Ingest.Plain.WitforgeValues.ListEquals(_tags, other._tags) && global::System.Collections.Generic.EqualityComparer.Default.Equals(_note, other._note); } public override int GetHashCode() { var hash = new global::System.HashCode(); hash.Add(_id); hash.Add(_name); hash.Add(global::Example.Ingest.Plain.WitforgeValues.ListHashCode(_tags)); hash.Add(_note); return hash.ToHashCode(); } public override string ToString() { return "Item { Id = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_id) + ", Name = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_name) + ", Tags = " + global::Example.Ingest.Plain.WitforgeValues.ListToString(_tags) + ", Note = " + global::Example.Ingest.Plain.WitforgeValues.DeepToString(_note) + " }"; } } ``` ```csharp public enum Status { Accepted = 0, Rejected = 1, } public static class StatusExtensions { public static string ToWitName(this global::Example.Ingest.Plain.V0_1.Types.Status value) { return value switch { global::Example.Ingest.Plain.V0_1.Types.Status.Accepted => "accepted", global::Example.Ingest.Plain.V0_1.Types.Status.Rejected => "rejected", _ => throw new global::System.ArgumentOutOfRangeException("value", value, "Unknown Status value."), }; } public static bool TryParseWitName(string? name, out global::Example.Ingest.Plain.V0_1.Types.Status value) { switch (name) { case "accepted": value = global::Example.Ingest.Plain.V0_1.Types.Status.Accepted; return true; case "rejected": value = global::Example.Ingest.Plain.V0_1.Types.Status.Rejected; return true; default: value = default; return false; } } } public abstract record Event { private Event() { } public sealed record Started : Event { public Started() { } } public sealed record Item : Event { private readonly global::Example.Ingest.Plain.V0_1.Types.Item _value; public Item(global::Example.Ingest.Plain.V0_1.Types.Item value) { _value = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "value"); } public global::Example.Ingest.Plain.V0_1.Types.Item Value { get => _value; init => _value = global::Example.Ingest.Plain.WitforgeValues.RequireNonNull(value, "Value"); } public void Deconstruct(out global::Example.Ingest.Plain.V0_1.Types.Item value) { value = Value; } } public sealed record Finished : Event { private readonly global::Example.Ingest.Plain.V0_1.Types.Status _value; public Finished(global::Example.Ingest.Plain.V0_1.Types.Status value) { _value = value; } public global::Example.Ingest.Plain.V0_1.Types.Status Value { get => _value; init => _value = value; } public void Deconstruct(out global::Example.Ingest.Plain.V0_1.Types.Status value) { value = Value; } } } ``` Full files: [`V0_1/Types.cs`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/csharp/V0_1/Types.cs), [`Convert.cs`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/csharp/Convert.cs), and `Google.Protobuf` glue [`V0/TypesGlue.cs`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/generated/csharp-glue/V0/TypesGlue.cs). To emit deterministic Markdown contract reference pages (`index.md` and per-version `v_.md`) for your own contract, run `witforge doc`; to export the deterministic JSON contract IR for tooling, run `witforge inspect --json`. --- # Evolving contracts URL: https://witforge.org/docs/evolution/ ## Add a minor version A new minor is a new directory that starts as a copy of the previous version, lockfile included (`witforge new-version wit` automates this from the latest version, and `witforge new-version wit --from v0.2` creates a maintenance minor `v0.3` on an earlier major line even after `v1.0` exists): ```sh mkdir wit/v0.2 cp wit/v0.1/contract.wit wit/v0.1/wire.lock wit/v0.2/ # Edit wit/v0.2/contract.wit: set the package version to 0.2.0, then change the contract. witforge lock wit/v0.2 --against wit/v0.1/wire.lock witforge check wit/v0.2 --against wit/v0.1/wire.lock witforge diff wit/v0.1 wit/v0.2 witforge diff wit/v0.1 wit/v0.2 --check # exits 1 if the change is breaking ``` To compare your current working tree directly against a Git base revision without checking out a second tree (for example in a pull request), run `witforge diff --git-base origin/main wit --check=wire,decode`. The package version in `contract.wit` must match the directory name; with the copied `@0.1.0` still in place, every command refuses `wit/v0.2`. Copy every `.wit` file and the `deps/` directory when the version has more than one file or uses dependencies (or run `witforge deps sync wit` / `witforge deps sync wit --check` to keep `deps/` synchronized across unreleased versions within the same major). Never create a minor version with a fresh lockfile (`lock --first`). Copying preserves protobuf field numbers, method IDs, removed-member reservations, and declaration-order history. `diff --check` exits 1 on a wire-, source-, or generated-API-breaking change. Adding a record field is source-breaking even when its type is defaultable, because Rust code that constructs the record must be updated. ## Wire identity vs. decode compatibility `witforge diff` separates **wire identity** (`wire`) from **protobuf binary decode compatibility** (`decode`): - **Wire identity (`wire`)** checks whether lockfile numbers, kinds, and canonical types changed meaning. Adding a new field or enum case gets a fresh wire number, so it is `wire:compatible`. - **Decode compatibility (`decode`)** checks whether two separate processes running different minors of the same major can actually decode each other's protobuf binary messages under the decode profile ([`non-rust.md`](https://witforge.org/docs/non-rust/) / built-in checked glue emitters): - `new<-old` (`new_reads_old`): whether a newer reader accepts messages sent by an older writer. Adding a required record field or parameter (including required `list` (`optional bytes`), `list`, or `char`) breaks `new<-old` (`MissingField` or `InvalidLength`), as does removing an enum case, variant case, or function. Adding an `option` field, a non-byte `list` field, a `map` field, or a flag stays compatible. - `old<-new` (`old_reads_new`): whether an older reader accepts messages sent by a newer writer. Adding an enum case, variant case, or function breaks `old<-new` (`UnknownEnumValue` / `UnknownCase`), as does removing a required field (`MissingField`). Adding any field or flag stays compatible in protobuf **binary** encoding because unknown fields are ignored (note that strict proto3-JSON parsers such as `pbjson` reject unknown JSON field names by default). `decode` applies within one major (two majors have two distinct protobuf packages negotiated separately) and is distinct from in-process version adapters. Bare `witforge diff --check` gates on `[project..policy].diff-check` when configured in `witforge.toml`, or on `wire,source,api` by default without `decode`; pass `--check=decode` or `--check=wire,decode` when rolling upgrades require two services at different minors to talk on the wire. ## Version adapters `witforge rust` emits `convert.rs` for adjacent live versions in both directions, and the polyglot plain emitters apply the exact same shared convertibility rules (`convert.ts` for `witforge ts`, `convert.py` for `witforge py`, `convert/` packages for `witforge go`, `Convert.java` with `ConversionErrorKind.java` and `WitforgeConversionException.java` for `witforge java`, and `Convert.cs` for `witforge csharp`). Pass `--try-from` (or set `try-from = true` under `[project..rust]`) to also generate Rust `TryFrom<&From>` and owned `TryFrom` implementations for converted nominal types. Old-to-new conversion defaults an added record field only when its type is `option` (to `None` / empty option), `list` (to an empty list, including `list` in-process), or `map` (to an empty map), and sets a flag added to an existing flags type to `false`. A required addition of any other type, including a field whose type is a fixed-length list, flags, record, or scalar type, is refused within a major (`WF2002`) when the adapters are generated. New-to-old conversion drops fields and flags that the older version does not have; it does not report them. It returns `MissingMember` when the older version requires a field the newer version removed (except `option`, `list`, or `map`, which default to empty). In either direction, a value whose enum or variant case the target version does not have returns `UnknownCase`. Retypes and kind changes are refused within a major. ## Starting a new major A breaking change (such as retyping a field, changing a type's kind, adding a required field without a default, renaming a type, or upgrading a dependency) belongs in a new major version (`v1.0` after `v0.x`, or `v2.0` after `v1.x`). A new major starts with a fresh lockfile (`--first`) and gets its own protobuf package (`v1.proto`) and per-major glue (`v1.rs`, `v1/`, or `V1/`). ### In the same WIT root (recommended) Keeping the new major in the same WIT root gives you all versions under one generated module tree and generates adapters automatically for every type that still converts: ```sh witforge new-version wit --major # Edit wit/v1.0/contract.wit to make breaking changes (and wit/v1.0/deps/ if upgrading dependencies). witforge lock wit/v1.0 --first witforge check wit witforge diff wit/v0.2 wit/v1.0 witforge rust wit --out generated/rust ``` Across a major boundary: - **Plain types always generate.** Plain emitters never refuse a major boundary, so `v1_0` and every earlier live version's types are always written. - **Partial adapters generate per direction.** Types that still convert under the normal rules get adapters in the generated adapter files (`convert.rs`, `convert.ts`, `convert.py`, `convert/`, `Convert.java`, `Convert.cs`). Types that do not (retypes, kind changes, required additions in the old-to-new direction, payload-presence changes, types with no namesake, types using an upgraded dependency, and any containing type transitively) are omitted in that direction. Required additions still generate new-to-old adapters because the new field is dropped. - **Every omission is listed twice.** The top of each generated conversion file carries a sorted, deterministic comment block listing every omitted `(from -> to, type, reason)` pair (`--check` covers it), and `witforge diff wit/v0.2 wit/v1.0` reports the exact same list. Write manual adapters for those types in your own package beside the generated ones. - **Dependencies may change or upgrade.** Within one major, every minor still shares an identical pinned dependency graph. Across majors, unchanged dependencies stay in `witforge_deps::` and still convert across the major; dependencies that changed or were upgraded move into per-major modules (`witforge_deps::v0::`, `witforge_deps::v1::`), and proto/schema files disambiguate only if two live majors pin conflicting definitions with the same dependency major version. - **`diff --check` still reports breaking changes.** Because a new major is expected to break, run `witforge diff wit/v0.2 wit/v1.0` without `--check` when reviewing a major boundary. ### Retiring old versions Once consumers no longer need the oldest versions in a WIT root, retire them with `witforge retire wit/v0.1` (which validates release status, contiguous oldest-prefix ordering, and at least one remaining live version before atomically marking ` retired` in `wit/released`, first supported in 0.7.0; earlier releases reject the syntax): ```text v0.1 retired v0.2 retired v1.0 ``` - Only a contiguous oldest prefix of versions may be retired, and at least one live version must remain. Retiring `v0.2` while `v0.1` is still live (or retiring every version) is refused. - Never delete an entry or directory from `wit/released`. Retired directories remain in Git and stay frozen; `witforge freeze` accepts the one-way transition from live to `retired` and refuses un-retiring (`retired` back to live) or editing a retired directory. - Retired versions stop being generated: running the generators removes their per-version plain modules and packages, JSON Schema files, Markdown reference pages (`v_.md`), and adapters through normal stale-file cleanup (while `index.md` lists them under retired versions). Retiring an older minor of a live major leaves `v.proto` unchanged (the highest minor carries every reservation); retiring every version of a major removes that major's `.proto` file and glue output as well. ### Separate WIT root per major (alternative) If you prefer completely isolated generated packages or output trees with no shared conversion adapters or `witforge_deps` modules, place each major in its own WIT root (`wit-v1/`, `wit-v2/`) with separate output directories (or separate `[project.]` entries in `witforge.toml`) and write any cross-major bridge in your own code. ## Released versions List immutable version directories in `wit/released` using `witforge release wit/v0.1` (which validates the directory and predecessor before appending to `wit/released`; pass `--forbid-unstable` or set `[project..policy].forbid-unstable-in-release = true` to reject releasing any `@unstable` declaration). Do not edit a released version's WIT, lockfile, dependency packages, or generated per-version modules. Create a new version directory instead (`witforge new-version wit` for a minor, or `witforge new-version wit --major` for a new major). Use `witforge freeze` (with `fetch-depth: 0`) in CI to verify released history (including one-way live-to-retired transitions). --- # CI and release freeze URL: https://witforge.org/docs/ci/ ## GitHub Action Check out with full Git history (`fetch-depth: 0`) so `witforge freeze` can inspect the history of `wit/released`, pin the Action to a release tag or commit SHA, and let the Action run `check`, `diff`, `freeze`, and every configured generator with `--check`. ### Passing workflow on `examples/evolved` `examples/evolved` adds defaultable fields in `v0.2` (wire-compatible, source-breaking for Rust struct literals). Setting `diff-check: "wire"` verifies wire compatibility while allowing the additive minor evolution; this exact combination passes on `examples/evolved`: ```yaml - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: zeropier/witforge@v0.12.0 with: check: examples/evolved/wit/v0.2 against: examples/evolved/wit/v0.1/wire.lock diff-old: examples/evolved/wit/v0.1 diff-new: examples/evolved/wit/v0.2 diff-check: wire config: examples/evolved/witforge.toml generators: rust,proto,schema,glue freeze: "true" # Optional from v0.8.0 (defaults to github.token); pass explicitly on <= v0.7.x. github-token: ${{ github.token }} ``` The Action validates every input before downloading anything, downloads a checksum-verified (and from 0.7.0, build-provenance-verified) release archive, removes the downloaded archive/checksum scratch files, leaves `witforge` on `PATH` (`WITFORGE_BIN`), and emits GitHub workflow annotations (`::error file=...,line=...,col=...::...`) whenever a check fails. ### Failing compatibility gate and SARIF upload To fail a pull request on any source-, generated-API-, wire-, or protobuf binary decode break, set `diff-check: "true"` (default: `wire,source,api`) or `diff-check: "wire,decode"`. Set `format: sarif` to write a combined SARIF 2.1.0 report and upload it in a separate step: ```yaml permissions: contents: read security-events: write steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - id: witforge uses: zeropier/witforge@v0.12.0 with: check: wit/v0.2 against: wit/v0.1/wire.lock diff-old: wit/v0.1 diff-new: wit/v0.2 diff-check: wire,decode config: witforge.toml generators: rust,proto,schema,glue freeze: "true" format: sarif sarif-file: witforge.sarif # Optional from v0.8.0 (defaults to github.token); pass explicitly on <= v0.7.x. github-token: ${{ github.token }} - if: always() && steps.witforge.outputs.sarif-file != '' uses: github/codeql-action/upload-sarif@v3 with: sarif_file: ${{ steps.witforge.outputs.sarif-file }} ``` Uploading SARIF requires `security-events: write` and is unavailable to pull requests from forks with read-only tokens. Workflow annotations require no extra permissions and always appear on pull request diffs regardless of `format`. ### Version pinning and SHA pins - When `version` is empty and the Action ref is a release tag (`@v0.12.0`), the Action installs that exact release. - When `version` is empty and the Action ref is a commit SHA, branch, floating tag, or local `./`, the Action installs the workspace version recorded in `Cargo.toml` at that exact ref; it never silently falls back to `latest`. If that version has no published release assets yet, the step fails and names the `version` input. - Pass `version: latest` explicitly only if you intentionally want floating latest releases. - Pass `binary: path/to/witforge` to skip download and run a locally built executable (cannot be combined with `version`). ### Action inputs | Input | Default | Description | |---|---|---| | `version` | empty | `X.Y.Z`, `vX.Y.Z`, or `latest`. Empty installs the release tag or the workspace version at the Action's commit SHA/branch. Cannot be combined with `binary`. | | `binary` | empty | Path to an existing local `witforge` binary to run instead of downloading a release. Cannot be combined with `version`. | | `check` | empty | WIT version directories or WIT roots to pass to `witforge check`, one per line, or `true` (from `v0.8.0`) to check every project in `config`. | | `against` | empty | Baseline `wire.lock` path(s) for `witforge check --against`: a single lockfile path when `check` lists one directory, or `=` lines when `check` lists multiple directories. Cannot be combined with `check: true`. | | `diff-old` | empty | Old version directory or WIT root for `witforge diff` (must be paired with `diff-new`). | | `diff-new` | empty | New version directory or WIT root for `witforge diff` (must be paired with `diff-old`). | | `diff-check` | `true` | `true` (`--check`, defaults to `[project..policy].diff-check` when configured, otherwise `wire,source,api`), `false` (report only), or comma-separated views from `wire`, `source`, `api`, `decode` (`--check=`). | | `config` | empty | Path to `witforge.toml` for `check: true`, `freeze: true`, and configured generators. | | `project` | empty | Optional project name in `witforge.toml`. | | `generators` | `rust` | Comma- or whitespace-separated subset of built-in generators (`rust`, `proto`, `schema`, `glue`, `doc` (from `v0.9.0`), plus polyglot `ts`, `ts-glue`, `py`, `py-glue`, `go`, `go-glue`, `java`, `java-glue`, `csharp`, `csharp-glue` (from `v0.10.0`)) run with `--config` and `--check` (individual names, including default `rust`, require `project` when `config` defines multiple projects), or `all` (from `v0.8.0`) to run `witforge generate --config ... --check` across every configured built-in generator and project. Third-party plugins stay strictly opt-in (`generators: plugins` is refused, and `generators: all` never passes `--allow-plugins`). Empty skips generation (pass `generators: ""` when using `config` only for `check: true` or `freeze: true`). | | `freeze` | empty | WIT roots to verify with `witforge freeze` (one per line), or `true` to verify every project in `config`. Requires `fetch-depth: 0`. | | `format` | `human` | Output format: `human`, `json`, or `sarif`. Failing checks emit GitHub workflow annotations in all formats. | | `sarif-file` | empty | Output file path for the combined SARIF 2.1.0 report when `format: sarif` is set (defaults to `witforge.sarif`). | | `github-token` | `${{ github.token }}` (from `v0.8.0`) | Token sent only to GitHub API calls (`version: latest` lookup and `gh attestation verify`), defaulting to the workflow token from `v0.8.0` (pass explicitly on `<= v0.7.x`) and never sent with asset downloads. | ### Action outputs | Output | Description | |---|---| | `failed-command` | Empty on success; names the failing stage (`validate`, `install`, `sarif`, or `witforge `, such as `witforge diff`) on failure. | | `sarif-file` | Path to the combined SARIF 2.1.0 file when `format: sarif` was requested. | ### Release freeze and `diff` upgrade notes `witforge freeze` refuses shallow clones with exit code `2` and names `fetch-depth: 0`; never skip it with a shallow checkout. It protects committed WIT contract sources and `wire.lock` files under every released directory. Generated per-version modules (such as `v0_1.rs`) are frozen by committing the generated copies and verifying them with `--check`, not by `witforge freeze`. **Action releases up to and including v0.5.0 ignored `diff-old`, `diff-new`, `diff-check`, and `github-token`** because they read them under underscore environment names. Fixed in `v0.6.0`: workflows already passing `diff-old` and `diff-new` begin running `witforge diff --check` when moving to `v0.6.0` or later; set `diff-check: "false"` or `diff-check: "wire"` if source-breaking additions should not fail the job. ## Direct commands ```sh witforge freeze --config witforge.toml witforge check wit witforge diff wit/v0.1 wit/v0.2 --check witforge generate --config witforge.toml --check ``` Recommended direct CI gates: - `witforge freeze --config witforge.toml` (with `fetch-depth: 0`) to verify released history and one-way retirement transitions; - `witforge check ` to check every version directory, predecessor lockfile continuity, and the pinned dependency graph; - `witforge diff --git-base origin/main --check` (or `witforge diff old new --check`), which uses `[project..policy].diff-check` when configured in `witforge.toml` (set `forbid-unstable-in-release = true` in the same policy table to block releasing `@unstable` items); - `witforge deps sync --check` when vendored `deps/` are shared across unreleased minors; - `witforge generate --config witforge.toml --check` to verify every configured built-in generator (Rust, protobuf, JSON Schema, glue, Markdown docs, TypeScript, Python, Go, Java, and C#) has not drifted. Pass `--only ` to gate a subset of generators, and pass `--allow-plugins` explicitly (or invoke `witforge plugin --check`) only in workflows that intentionally opt in to running third-party plugins. ## Consumer tests Generated-file checks prove reproducibility, not application behavior. Also compile generated Rust and polyglot types/glue, compile the emitted protobuf with the consumer's normal toolchain, round-trip representative values (including `witforge conformance` vectors for cross-language boundaries), and exercise application adapters and defaults. For a JSON protocol, commit full and minimal fixtures and run them through every language implementation. --- # Release migration URL: https://witforge.org/docs/migration/ ## General upgrade steps 1. Check the release row below and read its full changelog section before moving your pin. 2. Update your installed CLI (`cargo install witforge-cli --version X.Y.Z --locked`) and CI Action pin (`zeropier/witforge@vX.Y.Z`) together. 3. Run `witforge check` across every version directory to surface any newly refused invalid or ambiguous contracts. 4. Run `witforge generate --diff` (or each generator with `--diff`) to inspect generated-output changes, regenerate committed outputs, compile and test your consumer crate, and verify `witforge generate --check` passes before committing. ## Per-release output and compatibility summary Each row links directly to the authoritative release notes in [`CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md) rather than copying its details here. | Release | Generated output changes for existing contracts? | Summary & changelog link | |---|---|---| | **Unreleased** | No announced changes | See [Unreleased in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#unreleased). | | **0.12.0** (2026-12-03) | **No output changes for existing 0.11.0 contracts** (pre-1.0 diagnostic metadata update: `witforge::diagnostic::HELP_BASE_URL` moves to `https://witforge.org/docs/diagnostics/` and SARIF `informationUri` moves to `https://github.com/zeropier/witforge`) | ZeroPier organization and `witforge.org` cutover release (`W10-137`, `W10-138`, `W10-139`); migrates repository, Cloudflare Workers docs site at `https://witforge.org/`, Action (`zeropier/witforge@v0.12.0`, retaining `--owner asamarts` SLSA verification for `0.7.0` through `0.11.0`), and polyglot packaging coordinates (`org.witforge`, `zeropier/tap/witforge`, `aqua:zeropier/witforge` `>= 0.12.0`, `ZeroPier` NuGet), plus staggered macOS release smokes and SLSA verification in all `package-*` jobs. See [0.12.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#0120---2026-12-03). | | **0.11.0** (2026-12-02) | **No output changes for existing 0.10.0 contracts** | Strictly additive release over 0.10.0 with zero Rust library API or generated-output changes; adds PyPI platform wheel packaging (`packaging/pypi/`), npm `@witforge/cli` + 7 exact-pinned `optionalDependencies` (`packaging/npm/`), Homebrew formula renderer and `aqua`/`mise` registry metadata (`packaging/homebrew/`, `packaging/aqua/`), thin .NET `Witforge.Tools` MSBuild and JVM Gradle/Maven `witforge-native` `@exe` wrappers (`packaging/dotnet/`, `packaging/jvm/`), zero-dependency Rust/TypeScript/Python `protocol_version = 1` plugin starter kits (`examples/plugin-starters/`), multi-ecosystem install tabs, and Windows `--plugin-bin` separator normalization. See [0.11.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#0110---2026-12-02). | | **0.10.0** (2026-12-02) | **No output changes for existing 0.9.0 contracts** (narrow new `WF1003` refusal on `protoc-gen-go` digit-boundary collisions such as `foo2bar` vs `foo2-bar`) | Strictly additive Rust library release over 0.9.0; adds built-in zero-dependency plain types, cross-version adapters, and checked protobuf glue for TypeScript, Python 3.11+, Go 1.22+, Java 21+, and C# 12+ / .NET 8+, opt-in protobuf language file options, `witforge conformance` fixture bundle, `witforge plugin` (`protocol_version = 1`), `witforge generate --only` and `--allow-plugins`, polyglot Action generators, `examples/polyglot`, and the Astro + Starlight site. See [0.10.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#0100---2026-12-02). | | **0.9.0** (2026-11-26) | **Minor (`glue/mod.rs` adds two `#[non_exhaustive]` `GlueError` variants)** | Strictly additive Rust library release over 0.8.0; adds WIT subset expansion (`char`, fixed-length `list`, primitive-keyed `map`), deterministic Markdown docs (`witforge doc` / `emit::doc` / Action `generators: doc`), opt-in `--eq-hash` and `--try-from` Rust/convert options, `witforge diff --git-base ` (`diff::compare_git_base`), `[project..policy]` (`diff-check` and `forbid-unstable-in-release`), `witforge deps sync`, and Protobuf Editions 2023 evaluation. See [0.9.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#090---2026-11-26). | | **0.8.0** (2026-11-24) | **Minor (JSON Schema docs, proto wrappers/unused imports, long-line Rust/glue formatting)** | Strictly additive Rust library release over 0.7.0; adds lifecycle CLI (`init`, `retire`, `new-version --from`/`--released`), versioned JSON contract IR (`inspect`), opt-in `no_std` + `alloc` Rust/convert/glue output, optional `witforge-build` crate, JSON Schema Draft 2020-12 and member descriptions, static `musl` Linux archives, and Action `check: true` / `generators: all` / default `github-token`. See [0.8.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#080---2026-11-24). | | **0.7.0** (2026-11-23) | **Yes for contracts using `@since`, `@unstable`, or `@deprecated`** | Final pre-1.0 Rust-library source break (`#[non_exhaustive]` data types, private former internals, structured workflow/generated findings, typed diff elements and `stability-changed`); stability docs and deprecation markers in Rust/protobuf/JSON Schema; cross-major partial `convert.rs`, per-major `deps/` scoping, retirement, decode diffing, workflow commands, diagnostics, and Action hardening. Regenerate every annotated contract and apply the [0.7.0 migration notes](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#070---2026-11-23). | | **0.6.0** (2026-11-21) | **Yes (all consumers)** | Per-generator/contract ownership headers, `rustfmt`/Clippy/`missing_docs`-clean Rust, upper-case Rust identifier folding, dropped empty traits for type-only interfaces, `ConversionError` `from`/`to` fields, lossless JSON Schema `result` + `f32` bounds, byte-list aliases -> `bytes`/`Vec`, leading-dot cross-package `.proto` refs, deterministic multi-file order, absolute glue module roots, Action `diff-*` activation, and stricter `check`/lockfile rules. Read [0.6.0 Migration in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#060---2026-11-21). | | **0.5.0** (2026-11-17) | Minor (`convert.rs` trailing newline only) | Removed extra blank line at EOF of `convert.rs`; additive `diff` conversion-impact notes; no wire, proto, schema, or Rust API changes. See [0.5.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#050---2026-11-17). | | **0.4.4** (2026-11-12) | Minor (glue & `convert.rs` docs) | Reduced clones/allocations in generated glue and added `# Errors` docs to `convert.rs`; regenerate committed glue and `convert.rs`. See [0.4.4 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#044---2026-11-12). | | **0.4.3** (2026-11-11) | No | Tightened transitive dependency validation for exposed unsupported dependency types. See [0.4.3 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#043---2026-11-11). | | **0.4.2** (2026-11-10) | No | Node 24 Action runtime and stricter world/dependency validation. See [0.4.2 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#042---2026-11-10). | | **0.4.1** (2026-11-06) | Only nested dependency wrappers | Fixed PascalCase synthesized wrapper names for nested `deps/` lists/options. See [0.4.1 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#041---2026-11-06). | | **0.4.0** (2026-11-06) | Only when using `deps/` or `serde = true` | Added standard `deps/` dependency support and opt-in Serde derives. See [0.4.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#040---2026-11-06). | | **0.3.0** (2026-11-06) | No | Added `witforge diff`, `--format json` / `--format sarif`, prebuilt archives, and GitHub Action. See [0.3.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#030---2026-11-06). | | **0.2.0** (2026-11-04) | **Yes (multi-version, worlds, schema)** | Added `convert.rs`, `worlds.rs`, `witforge schema`, `witforge.toml`, and `# witforge order v1` lockfile fingerprints. See [0.2.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#020---2026-11-04). | | **0.1.2** (2026-11-01) | No | Validation and CRLF/lockfile/freeze hardening only. See [0.1.2 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#012---2026-11-01). | | **0.1.1** (2026-11-01) | No | Output ownership, symlink refusal, and release-freeze hardening. See [0.1.1 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#011---2026-11-01). | | **0.1.0** (2026-10-31) | Initial release | Initial public compiler release (`check`, `lock`, `rust`, `proto`, `glue`). See [0.1.0 in `CHANGELOG.md`](https://github.com/zeropier/witforge/blob/main/CHANGELOG.md#010---2026-10-31). | --- # Non-Rust implementations URL: https://witforge.org/docs/non-rust/ witforge compiles one hand-written WIT contract into idiomatic, zero-dependency plain types, interface definitions, cross-version adapters, and checked protobuf glue for five non-Rust ecosystems alongside Rust: **TypeScript**, **Python**, **Go**, **Java**, and **C#**. For any other language (such as C++, Kotlin, or Swift), consumers can use the emitted `.proto` schema with that language's protobuf generator and enforce the decode profile below, or target the language with a third-party emitter plugin. witforge does not generate RPC services or own transport framing. ## Built-in polyglot emitters Each built-in polyglot language ships as a plain-types emitter (zero third-party runtime dependencies, plus bidirectional cross-version adapters whenever a contract has adjacent versions) paired with a checked protobuf glue emitter that enforces every decode and encode rule in the profile below: | Language | Target baseline | Plain emitter (`witforge `) | Version adapters | Checked glue (`witforge `) | Protobuf runtime | |---|---|---|---|---|---| | TypeScript | Strict ESM (`NodeNext`) | `ts` (`readonly` interfaces, unions, `worlds.ts`) | `convert.ts` | `ts-glue` | `@bufbuild/protobuf` | | Python | Python 3.11+ stdlib | `py` (`frozen` dataclasses, `StrEnum`, `Protocol`, `py.typed`) | `convert.py` | `py-glue` | `google.protobuf` (`protoc --python_out`) | | Go | Go 1.22+ stdlib | `go` (typed structs, sealed interfaces, `worlds/`) | `convert/` | `go-glue` | `google.golang.org/protobuf` (`protoc-gen-go`) | | Java | Java 21+ stdlib | `java` (records, sealed interfaces, `Optional`, `Worlds.java`) | `Convert.java` | `java-glue` | `com.google.protobuf` (`protoc --java_out`) | | C# | C# 12+ / .NET 8+ stdlib | `csharp` (`#nullable enable` records, `Worlds.cs`) | `Convert.cs` | `csharp-glue` | `Google.Protobuf` (`protoc --csharp_out`) | Configure any subset of these emitters in `witforge.toml` and run them together with `witforge generate` (or narrow a run with `--only`): ```sh witforge generate --config examples/polyglot/witforge.toml witforge generate --config examples/polyglot/witforge.toml --only proto,ts,ts-glue --check ``` See [`examples/polyglot/witforge.toml`](https://github.com/zeropier/witforge/blob/main/examples/polyglot/witforge.toml) for a complete working configuration covering all five languages, and the [generated-output guide](https://witforge.org/docs/generated-output/#polyglot-outputs) for verified excerpts from the committed outputs. All flags and configuration keys are listed in the [CLI and configuration reference](https://witforge.org/docs/reference/). ## Protobuf file options By default, emitted `.proto` files carry no language-specific file options so output remains neutral across every target language. If you want generated `.proto` files to embed idiomatic Go, Java, or C# placement options directly, opt in via `[project..proto]` in `witforge.toml` or the matching flags on `witforge proto`: ```toml [project.example.proto] out = "generated/proto" go-package = "github.com/acme/contracts/gen/go" java-package = "com.acme.contracts" java-multiple-files = true csharp-namespace = "Acme.Contracts" # Optional exact overrides keyed by emitted proto package name (including # disambiguated dependency packages such as `shared.types.v0_m1`): [project.example.proto.packages."example.plugin.v0"] java-outer-classname = "PluginV0Proto" ``` Or on the command line: ```sh witforge proto wit --out generated/proto \ --go-package github.com/acme/contracts/gen/go \ --java-package com.acme.contracts \ --java-multiple-files \ --csharp-namespace Acme.Contracts ``` How each option is derived across multiple majors (`v0`, `v1`) and `deps/` dependency files: - `go-package`: a base import path prefix without `;` derives `///;__` for every emitted file (for example `github.com/acme/contracts/gen/go/example/plugin/v0;example_plugin_v0`). An explicit `;` value (which must include `/`) is accepted verbatim when at most one emitted file inherits it and refused when multiple emitted files would share it. - `java-package`: derives `.`, escaping Java reserved keywords with a trailing underscore (for example `default` becomes `default_`). Two emitted files in the same effective Java package cannot emit colliding top-level Java class names (including `Empty.java` under `java-multiple-files = true` or implicit default outer classnames). - `java-multiple-files`: emits `option java_multiple_files = true;` (or `false;` in config). Pass `--no-java-multiple-files` on the CLI to omit the option when overriding config. - `java-outer-classname`: validated as a Java type identifier (rejecting keywords and restricted type identifiers such as `record` and `var`) and refused if it collides with any generated message, enum, wrapper, `OrBuilder`, enclosed `Builder`/`*Case` class, or another emitted file's Java class in the same effective Java package. - `csharp-namespace`: derives `.` (for example `example.my_pkg.v0` becomes `Acme.Contracts.Example.MyPkg.V0`, and a disambiguated dependency `shared.types.v0_m1` becomes `Acme.Contracts.Shared.Types.V0M1`). Two emitted files resolving to the same C# namespace are refused because every generated `.proto` file defines `message Empty`. File options are strictly non-wire metadata: they never alter `wire.lock`, protobuf binary wire encoding, `witforge diff --check=wire,decode`, Rust module paths generated by `witforge-build` / `prost-build`, or `witforge glue`. If you prefer to keep zero language options in checked-in `.proto` files, both `protoc` (`--go_opt=Mv0.proto=github.com/acme/contracts/gen/go/v0`) and `buf` managed mode (`buf.gen.yaml` `managed.override`) can inject Go, Java, and C# placement outside the schema. Note that `buf breaking` with its default `FILE` rules flags changed file options once if you enable file options on an already-published contract; either opt in before your first release or temporarily exclude `FILE_SAME_*` option checks for that transition commit. ## Decode profile The generated protobuf type alone is not the complete WIT value contract. Some WIT rules cannot be expressed by proto3 syntax and are enforced by witforge's built-in checked glue emitters (`glue`, `ts-glue`, `py-glue`, `go-glue`, `java-glue`, and `csharp-glue`). If you consume the `.proto` files directly in another language without generated glue, your adapter must enforce the same rules explicitly. | WIT value | Protobuf projection | Required implementation behavior | |---|---|---| | `u8`, `u16` | `uint32` | Reject values above the WIT type's maximum. | | `s8`, `s16` | `sint32` | Reject values outside the WIT type's signed range. | | `char` | `uint32` | Reject code points that are not valid Unicode scalar values (surrogates `0xD800..=0xDFFF` and values `> 0x10FFFF`). | | required scalar, string, enum, `list`, or `list` | proto3 `optional` scalar/string/enum/bytes | Reject absence. A scalar's protobuf default is not a substitute for presence. | | `option` | the same optional or wrapper shape used for `T` | Permit absence as `None`; validate a present payload normally. | | required record, variant, flags, result, parameter, or message result | message field | Reject absence. | | `list` | `repeated T`, or a wrapper when nested | Empty is valid. Validate every element recursively. | | `list` | `optional bytes` (when `T` is `u8`) or `repeated singular(T)` (or list wrapper when nested) | Require exact length `N` (`1 <= N <= 65536`), rejecting shorter or longer payloads (`InvalidLength`). Validate every element recursively. | | `map` | `map`, or a `WitforgeMapOf...` wrapper when nested | Empty is valid. Validate narrow integer keys (`u8`/`u16`/`s8`/`s16`), `char` keys, and every value recursively. | | enum | protobuf enum with `UNSPECIFIED = 0` | Reject zero and unknown numeric values; WIT enums are closed. | | variant or result | message with a `oneof` | Require one known case. Reject an unset or unknown case. | | flags | message with one `bool` per flag | Treat missing/default `false` as an unset flag. | | nested option/list/result wrapper | synthesized message | Require the wrapper's `oneof` (`none`/`some` or `ok`/`err`) to be set; reject an unset or unknown wrapper state. | These rules apply to record fields, function parameters, and function results. They also apply after protobuf binary or proto3-JSON parsing. Language protobuf libraries commonly preserve an unknown enum number or expose a `uint32` without the narrower WIT range; successful protobuf parsing therefore does not establish a valid WIT value. Built-in checked glue returns a structured error (`GlueError` in Rust, `WitforgeGlueError` in TypeScript and Python, `*glueerr.GlueError` in Go, `WitforgeGlueException` in Java and C#) covering these cases plus encode-side narrow/unsigned integer, UTF-8/scalar-value, and fixed-length checks. Custom implementations in other languages should expose idiomatic errors while preserving the exact same accept/reject boundary. ## Conformance fixture bundle Use `witforge conformance` to export witforge's built-in, deterministic cross-language conformance bundle (`conformance_version = 1`) and verify built-in or custom protobuf glue against the exact same decode and encode rules proved across Rust, TypeScript, Python, Go, Java, and C# in CI: ```sh witforge conformance --out conformance-bundle --polyglot-proto-options witforge conformance --out conformance-bundle --polyglot-proto-options --check ``` The command writes two directories and a top-level manifest under `--out`: - `wit/v0.1/`: the canonical WIT conformance contract (`contract.wit`, `deps/conformance-dep/dep.wit`, and `wire.lock`) exercising all 13 decode-profile rows, foreign `deps/` types, and interface functions. - `proto/`: the emitted `.proto` files (`v0.proto` and `witforge.conformance_dep.v0.proto`). Files are neutral by default; pass `--polyglot-proto-options` (or explicit `--go-package`, `--java-package`, `--java-multiple-files`, `--java-outer-classname`, `--csharp-namespace`) to embed Go, Java, and C# placement options. - `vectors.json`: deterministic test vectors carrying RFC 4648 base64 binary protobuf payloads, canonical proto3-JSON payloads, expected `accept`/`reject` outcomes, canonical error kinds (`IntegerOutOfRange`, `MissingField`, `UnknownEnumValue`, `UnknownCase`, `InvalidState`, `InvalidChar`, `InvalidLength`), and `encode`-direction boundary rejection vectors for languages without native narrow/unsigned/scalar-char/fixed-array types. The built-in vectors cover: - every narrow integer's minimum, maximum, and out-of-range values plus 64-bit integers beyond `2^53 - 1` (`u64::MAX`, `i64::MIN`, `i64::MAX`, `9007199254740993`, `-9007199254740993`); - `char` boundary scalars (`U+0000`, `U+D7FF`, `U+E000`, `U+1F680`, `U+10FFFF`), multi-byte UTF-8 strings with embedded NUL, UTF-16 surrogates (`0xD800..=0xDFFF`), and values above `0x10FFFF`; - `f32`/`f64` finite boundaries, `-0.0`, `NaN`, `Infinity`, and `-Infinity`; - required optional/message fields present (including explicit zero/empty defaults) and absent; - `option` absent and present, including `option>`, `option>`, and `option>`; - closed enums (`0`, known cases, and unknown numbers) in both root and `deps/` packages; - every variant case, all four `result` forms (`result`, `result`, `result<_, E>`, `result`), unset variant/result oneofs (`UnknownCase`), and unset `WitforgeOptionOf*` wrappers (`InvalidState`); - empty and populated lists, fixed-length `list` and `list` with exact length `N`, `N - 1`, and `N + 1`, and nested list/option/result wrappers; - `map` across string, narrow integer, `char`, `bool`, and 64-bit keys plus nested maps; - interface function request and response wrappers (including foreign `deps/` parameters and no-result functions), in both protobuf binary and proto3-JSON forms; - encode-side (`toProto`) boundary rejection vectors for TypeScript, Python, Go, Java, and C#. Run the vectors through your target language's protobuf implementation and keep `--check` in CI to detect drift. Generated-file `--check` proves schema reproducibility; running `vectors.json` proves runtime wire-contract parity across every language. ## Extending to other languages with plugins If you need generated plain types, glue, or framework-specific code for an ecosystem outside the built-in emitters (such as Kotlin, Swift, C++, or a custom runtime), implement the versioned JSON-over-stdio plugin protocol (`protocol_version = 1`) and run it with `witforge plugin ` or opt in via `witforge generate --allow-plugins`. See [Third-party emitter plugins](https://witforge.org/docs/generation/#third-party-emitter-plugins), the normative [plugin specification](https://github.com/zeropier/witforge/blob/main/docs/design/plugins.md), and the zero-dependency starter kits in Rust, TypeScript (Node 20+), and Python 3.11+ under [`examples/plugin-starters/`](https://github.com/zeropier/witforge/tree/main/examples/plugin-starters): ```sh # Try the TypeScript (or Rust / Python) starter kit against examples/polyglot/wit: witforge plugin starter examples/polyglot/wit \ --plugin-bin examples/plugin-starters/typescript/witforge-gen-starter.mjs \ --out ./starter-out witforge plugin starter examples/polyglot/wit \ --plugin-bin examples/plugin-starters/typescript/witforge-gen-starter.mjs \ --out ./starter-out \ --check ``` ## Go `//go:generate` workflow Go repositories can pin `witforge` (alongside `protoc` and `protoc-gen-go`) via `mise.toml` or `aqua.yaml` using [`packaging/aqua/registry.yaml`](https://github.com/zeropier/witforge/blob/main/packaging/aqua/registry.yaml), which downloads the attested static `musl` Linux (or native macOS/Windows) archive and verifies both its `.sha256` checksum and GitHub SLSA build provenance (until `zeropier/witforge` is merged into upstream `aquaproj/aqua-registry`, configure `packaging/aqua/registry.yaml` as a local `aqua` registry as shown in [`packaging/aqua/README.md`](https://github.com/zeropier/witforge/blob/main/packaging/aqua/README.md)). Setting `libc = "musl"` in `mise.toml` ensures `mise` selects the static `musl` archive on Linux distributions with `glibc < 2.39` rather than swapping to the sibling Ubuntu 24.04 `-gnu` archive: ```toml # mise.toml (once zeropier/witforge is merged into upstream aquaproj/aqua-registry) [tools] "aqua:zeropier/witforge" = { version = "0.12.0", libc = "musl" } ``` Then drive deterministic generation directly from `go generate ./...`: ```go //go:generate witforge generate --config witforge.toml --only proto,go,go-glue //go:generate protoc -I generated/proto --go_out=generated/pb --go_opt=paths=source_relative generated/proto/v0.proto package contracts ``` In CI, run `witforge generate --config witforge.toml --only proto,go,go-glue --check` to verify committed Go outputs without introducing any compiler dependency into `go.mod`. Generated Go plain types remain zero-dependency Go 1.22+ stdlib packages. ## MSBuild integration for .NET .NET 8+ projects can integrate `witforge` into `dotnet build` with the thin `Witforge.Tools` `developmentDependency` NuGet package ([`packaging/dotnet/`](https://github.com/zeropier/witforge/tree/main/packaging/dotnet), staged in each tag release's `dotnet-jvm-packages` workflow artifact for local or private NuGet feeds), modeled on `Grpc.Tools`: ```xml net8.0 enable witforge.toml proto,csharp,csharp-glue check generated/csharp all runtime; build; native; contentfiles; analyzers ``` `Witforge.Tools` carries zero runtime assemblies under `lib/` and zero `buildTransitive/` targets, so downstream projects referencing a compiled contract assembly never inherit codegen targets or bundle native binaries in `bin/`. `WitforgeRun` executes with `BeforeTargets="Protobuf_BeforeCompile;Protobuf_Compile;BeforeCompile"`, restores user execute permission (`u+x`) on the bundled NuGet tool on Unix if NuGet extraction cleared it before verifying execute permission, supports offline binary overrides via `` or `WITFORGE_BINARY_PATH`, and in `generate` mode dynamically appends newly emitted `.cs` and `.proto` files to `@(Compile)` and `@(Protobuf)` (deduplicated by `%(FullPath)`). ## Gradle and Maven integration for JVM Java 21+ projects can invoke `witforge` ahead of `protoc` and Java compilation using the classifier-addressed `org.witforge:witforge-native::@exe` artifacts (staged in each tag release's `dotnet-jvm-packages` workflow artifact for local or private Maven repositories) and thin wrappers under [`packaging/jvm/`](https://github.com/zeropier/witforge/tree/main/packaging/jvm), matching the standard `osdetector` / `os-maven-plugin` convention (`linux-x86_64`, `linux-aarch_64`, `osx-x86_64`, `osx-aarch_64`, `windows-x86_64`, with static `musl` binaries on Linux): - **Gradle (`packaging/jvm/witforge.gradle.kts`):** registers `witforgeGenerate` (ordered strictly ahead of `extractProto`, `extractIncludeProto`, `generateProto`, `generateTestProto`, `compileJava`, and `compileTestJava`, with `wit/`, `witforge.toml`, version, generators, and manifest inputs declared for Gradle build-cache correctness, plus opt-in `-PwitforgeAutoGenerate=true`) and `witforgeCheck` (wired into `check` with `mustRunAfter(witforgeGenerate)`). Verifies the resolved `@exe` artifact against a committed SHA-256 manifest, ensures owner execute permissions (`u+x`) on Unix when needed, and honors `-PwitforgeBinary=...` and `WITFORGE_BINARY_PATH`. - **Maven (`packaging/jvm/pom-example.xml` + `packaging/jvm/WitforgeWrapper.java`):** resolves `witforge-native` via `os-maven-plugin` (`${os.detected.classifier}`) + `maven-dependency-plugin`, runs the forked Java 21 `exec:exec` launcher (`witforge-generate`) in `generate-sources` strictly ahead of `protobuf-maven-plugin` inside `` so Maven runs `witforge` before `protoc`, binds `witforge-check` to `verify`, verifies SHA-256 digests before execution, and honors `-Dwitforge.binary=...` and `WITFORGE_BINARY_PATH`. Plain Java 21 outputs emitted by `witforge java` remain zero-dependency `java.base` code. ## JSON is a separate choice Proto3-JSON follows protobuf naming and presence rules. It is not the JSON shape described by witforge's JSON Schema (Draft 7 default, opt-in Draft 2020-12) and it is not necessarily the shape produced by Serde on generated plain Rust types. See [JSON projections](https://witforge.org/docs/json-projections/) before choosing a JSON boundary. Protovalidate annotations are not emitted today; they would expand the generated `.proto` schema and consumer runtime/tooling requirements and remain deferred behind an explicit future option if an adopter demonstrates a need beyond checked glue and conformance fixtures. --- # JSON projections URL: https://witforge.org/docs/json-projections/ witforge can participate in three different JSON shapes. They project the same WIT values but do not define one interchangeable JSON wire format. For this WIT: ```wit record diagnostic { start-byte: u32, id: u64, note: option, } ``` the default shapes are: | Projection | Representative value | |---|---| | generated Rust with `--serde` | `{"start_byte":4,"id":9,"note":null}` | | generated JSON Schema (Draft 7 / 2020-12) | `{"start-byte":4,"id":9,"note":null}` | | emitted protobuf through proto3-JSON | `{"startByte":4,"id":"9"}` | ## Plain Rust Serde `--serde` adds plain, format-independent `#[derive(::serde::Serialize, ::serde::Deserialize)]` attributes to generated records, enums, variants, and flags. Derived Serde uses the generated Rust spelling rather than the WIT spelling: - **Fields and flags:** `start-byte` becomes `"start_byte"`, upper-case words fold to Rust casing (`URL` becomes `"url"`), non-raw escaped keywords keep their trailing underscore (`%self` is keyed `"self_"`), and raw Rust identifiers drop `r#` (`%type` becomes `r#type` and is keyed `"type"`). - **Enums and variants:** enum cases serialize as PascalCase strings (`done-now` -> `"DoneNow"`), payload-less variant cases serialize as unit strings (`"Started"`), and payload variant cases use externally tagged single-key objects (`{"Item": {...}}`). - **Bytes, characters, fixed-length lists, maps, and integers:** `list` (including byte aliases) and `list` serialize as JSON arrays of integers (`[0, 127, 255]`), not base64; arrays with length `N > 32` (including inside `Option`, `Vec`, `BTreeMap`, or `Result`) use a private generated `#[serde(with = "...")]` helper module with no extra crate dependencies. `char` serializes as a single-character JSON string, and `map` (`BTreeMap`) serializes as a JSON object with stringified keys in deterministic key order. Rust integer types serialize as exact JSON numbers, including `u64` and `s64` (JavaScript `JSON.parse` loses precision above `±2^53`). - **Reading and evolution:** derived Serde treats an omitted `option` field as `None` (writing `None` as `null`) and silently ignores unknown fields. Reading a `v0.1` JSON document directly as `v0.2` therefore yields `None` for an added `option` field, but fails with a missing-field error for an added `list` or `map` field (unlike generated `convert.rs`, which defaults `option`, `list`, and `map`). - **`serde_json` losses:** because JSON has no distinct representation for nested nulls or non-finite floats, `serde_json` serializes `Some(None)` on nested options (`option>`, through aliases, or in lists) as `null` and deserializes it as `None`, and serializes `NaN` / `±Infinity` as `null` (which fails to deserialize for required fields/lists and deserializes as `None` inside `option`/`option`). Formats that tag `Option` or encode binary IEEE-754 floats round-trip both. See [the emitter specification](https://github.com/zeropier/witforge/blob/main/docs/design/emitters.md) section 3.3 for the full mapping table. ## JSON Schema (Draft 7 / Draft 2020-12) The schema preserves the WIT member spelling, including `start-byte` (Draft 7 is the default with `definitions`; opt-in Draft 2020-12 uses `$defs` and standardizes `deprecated: true`, which witforge also emits as an annotation in Draft 7 with the same JSON value shape). Every record property is required and records set `additionalProperties: false`. `option` permits `null` as the property's value; it does not make the property omittable (`option>` shares `null` for `None` and `Some(None)`, as in Serde). Integer schemas use the WIT type's exact numeric `minimum` and `maximum` (JSON parsers using IEEE 754 doubles are exact only up to `±2^53`, and Draft 7 `integer` accepts `1.0`). `f32` carries its finite bounds (`-3.4028235e38` to `3.4028235e38`) while accepting in-range decimals that round to `f32`; `NaN` and `±Infinity` have no JSON form. `char` is a JSON string with `minLength: 1` and `maxLength: 1` (Unicode scalar values); fixed-length `list` is an array with `minItems: N` and `maxItems: N` (for `list`, an array of `0..=255` integers, matching `list`); and `map` is an object with `additionalProperties` set to the value schema and `propertyNames` constraining non-`string` keys (`bool`, integer patterns, or single-character `char` keys). Every WIT `result` (including `result`, `result<_, E>`, and bare `result`) is a closed single-key object with `"ok"` or `"err"`, using `null` for a side without a payload (matching payload-less variant cases): | WIT value | Generated Rust `--serde` | JSON Schema | |---|---|---| | `result` (`Ok(7)` / `Err("e")`) | `{"Ok":7}` / `{"Err":"e"}` | `{"ok":7}` / `{"err":"e"}` | | `result` (`Ok(7)` / `Err(())`) | `{"Ok":7}` / `{"Err":null}` | `{"ok":7}` / `{"err":null}` | | `result<_, string>` (`Ok(())` / `Err("e")`) | `{"Ok":null}` / `{"Err":"e"}` | `{"ok":null}` / `{"err":"e"}` | | bare `result` (`Ok(())` / `Err(())`) | `{"Ok":null}` / `{"Err":null}` | `{"ok":null}` / `{"err":null}` | The schema describes a WIT-shaped JSON value. It does not describe Serde's Rust-identifier shape or protobuf's JSON mapping. ## Proto3-JSON The emitted `.proto` determines this projection. Its standard JSON mapping uses: - lowerCamelCase output names, so protobuf `start_byte` becomes `startByte`; parsers also accept the original protobuf spelling `start_byte`; - decimal strings for `u64` and `s64`; - base64 strings for `list` and fixed-length `list` bytes, unsigned integer code points (`uint32`) for `char`, JSON arrays for other `list` / `list` (wrapped as `{"values": [...]}` when nested), JSON objects with stringified protobuf keys for `map` (decimal `uint32` strings for `char` keys, wrapper objects when values are lists/maps/options/results, and `{"entries": {...}}` when the map itself is nested), and strings for non-finite floats; - enum names rather than integer values in normal output; - omitted fields for absent optional values. A WIT `option` containing `None` is therefore normally absent rather than the explicit `null` emitted by Rust Serde. Parsing valid proto3-JSON does not enforce all WIT semantics. Required presence, narrow integer ranges, closed enums, and selected variant/result cases still need the checks described in [Non-Rust implementations](https://witforge.org/docs/non-rust/) or the built-in checked glue emitters. ## Application defaults WIT does not define defaults such as "missing severity means warning." Keep application defaults in an explicit adapter and test them with fixtures. ## Choosing a JSON boundary Before adopting generated output for an existing protocol: 1. choose exactly one authoritative JSON profile; 2. test full and minimal payloads, naming, `null`, omission, 64-bit integers, enums, and bytes; 3. keep a custom wire schema or adapter when the existing protocol differs; 4. do not validate one projection with another projection's schema; 5. do not describe a custom application profile as generated unless its actual names and presence rules match. An opt-in naming mode could align future Serde output with WIT names, or a future schema mode could describe Serde names. Either changes the JSON behavior of generated per-version types and must not be applied retroactively to a frozen version. --- # Component Model boundary URL: https://witforge.org/docs/component-model/ These tools consume WIT for different purposes. | Tool | Owns | |---|---| | wit-bindgen | Guest bindings, imports/exports, Canonical ABI lift/lower | | Wasmtime `component::bindgen!` | Typed host bindings, linking, stores, calls, traps, async execution | | witforge | Runtime-independent plain types, interfaces, version adapters, and checked protobuf glue across Rust, TypeScript, Python, Go, Java, and C#, plus protobuf identity, JSON Schema, conformance, plugins, and compatibility diffs | witforge does not generate guest export shims or load components. ## Guest type reuse Rust `wit_bindgen::generate!` can remap selected WIT types with `with`, but a Rust path match is not enough: the remapped type must provide every API wit-bindgen's generated Canonical ABI code uses. Verified with wit-bindgen 0.63.0: - owned records and payload variants can reuse witforge types when their complete reachable type graph contains compatible primitives, strings, lists, options, records, and variants; - witforge enums cannot be remapped because wit-bindgen calls a generated hidden `_lift` constructor; - witforge flags cannot be remapped because wit-bindgen expects the `bitflags` API: `empty`, `from_bits_retain`, and `bits`; - a remapped record or variant containing one of those incompatible enum or flags types also fails, even if the nested type itself is left generated. Keep enums, flags, and aggregates that contain them wit-bindgen-generated, then convert at the application boundary. Do not add wit-bindgen-specific hidden helpers or a `bitflags`-shaped API to witforge's runtime-independent types. If an adopter needs direct reuse, the cleaner change belongs upstream in wit-bindgen. Re-run a compile check when upgrading wit-bindgen because `with` is tied to its generated API. Type reuse avoids an application-level conversion for compatible values. It does not avoid the Canonical ABI's required lift/lower memory work. ## Host adapters Wasmtime host bindings include runtime traits and linker machinery. A plain witforge module is not a replacement. Keep an application adapter between host-generated values and domain contract values, and measure nested-list allocations before proposing generated bridge code. Use witforge when the same WIT values also need native Rust, polyglot (TypeScript, Python, Go, Java, C#), protobuf/process, schema, or version-evolution surfaces. Otherwise use wit-bindgen/Wasmtime directly. --- # CLI and config reference URL: https://witforge.org/docs/reference/ This page lists every `witforge` subcommand, flag, `witforge.toml` configuration key, and exit code. The test suite verifies this page against the CLI parser so no option can go undocumented. ## Exit codes | Exit code | Meaning | |---|---| | `0` | Success (valid contract, up-to-date generated files, passing gate) | | `1` | Contract, lockfile, compatibility, release-freeze, plugin contract diagnostic, or generated-output drift violation | | `2` | Operational, CLI usage, parse, I/O, or safety-guard error | ## Global options Every subcommand accepts these global options: | Option | Description | |---|---| | `--format ` | Diagnostic output format: `human` (default), `json` (versioned diagnostic envelope on stdout), or `sarif` (SARIF 2.1.0 on stdout). | | `-q`, `--quiet` | Suppress human notes and summaries (never hides errors, exit codes, or JSON/SARIF output). | | `-h`, `--help` | Print help for `witforge` or a subcommand. | | `-V`, `--version` | Print version (bare `X.Y.Z` on exact clean release tags/tarballs; appends short Git commit and `-dirty` on development builds). | ## Commands ### `witforge check` Validate one version directory, an entire WIT root, or configured project(s) without writing. | Option / Argument | Description | |---|---| | `[PATH]` | Version directory or WIT root; omit to check configured project root(s) via `witforge.toml`. | | `--lock ` | Lockfile path (single version directory only; defaults to `/wire.lock`). | | `--first` | Treat every existing lockfile entry as a draft (single version directory only; conflicts with `--against`). | | `--against ` | Treat entries from this baseline lockfile as released (single version directory only; conflicts with `--first`). | | `--released ` | Released-version manifest path (defaults to `/../released` or `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge lock` Reconcile `wire.lock` for one version directory, assigning wire numbers to new members and reserving removed ones. Refuses released directories. | Option / Argument | Description | |---|---| | `` | WIT version directory to lock. | | `--lock ` | Lockfile path (defaults to `/wire.lock`). | | `--first` | Create or reconcile a fresh draft lockfile with no baseline (conflicts with `--against`). | | `--against ` | Reconcile against a predecessor version's `wire.lock` (conflicts with `--first`). | | `--released ` | Additional released-version manifest to check alongside defaults. | ### `witforge rust` Generate or check plain Rust types, interface traits, `worlds.rs`, `witforge_deps.rs`, and `convert.rs`. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Rust files. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--serde` | Enable `serde::Serialize` and `serde::Deserialize` derives (conflicts with `--no-serde`). | | `--no-serde` | Disable Serde derives, overriding `witforge.toml` (conflicts with `--serde`). | | `--no-std` | Emit `#![no_std]` + `alloc` compatible paths (`::alloc::*`, `::core::*`), overriding `witforge.toml` (conflicts with `--std`). | | `--std` | Emit default `std` paths, overriding `no-std = true` in `witforge.toml` (conflicts with `--no-std`). | | `--eq-hash` | Derive `Eq` and `Hash` on generated float-free records, variants, enums, and flags, overriding `witforge.toml` (conflicts with `--no-eq-hash`). | | `--no-eq-hash` | Disable `Eq`/`Hash` derives, overriding `eq-hash = true` in `witforge.toml` (conflicts with `--eq-hash`). | | `--try-from` | Emit `TryFrom` impls in `convert.rs` for converted nominal types, overriding `witforge.toml` (conflicts with `--no-try-from`). | | `--no-try-from` | Disable `TryFrom` impls in `convert.rs`, overriding `try-from = true` in `witforge.toml` (conflicts with `--try-from`). | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge proto` Generate or check per-major protobuf schemas (`v.proto` and dependency `.proto` files). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated `.proto` files. | | `--go-package ` | Base `go_package` import path prefix (or explicit `path;alias` for single-file output), overriding `project..proto.go-package`. | | `--java-package ` | Base `java_package` prefix for emitted `.proto` files, overriding `project..proto.java-package`. | | `--java-multiple-files` | Emit `option java_multiple_files = true;`, overriding config (conflicts with `--no-java-multiple-files`). | | `--no-java-multiple-files` | Omit `option java_multiple_files`, overriding `project..proto.java-multiple-files` (conflicts with `--java-multiple-files`). | | `--java-outer-classname ` | Emit `option java_outer_classname = "";`, overriding `project..proto.java-outer-classname`. | | `--csharp-namespace ` | Base `csharp_namespace` prefix for emitted `.proto` files, overriding `project..proto.csharp-namespace`. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge schema` Generate or check JSON Schema files (`v_.schema.json` and dependency schemas; Draft 7 by default, or Draft 2020-12 with `--draft 2020-12`). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated JSON Schema files. | | `--draft ` | JSON Schema dialect: `7` (default) or `2020-12` (overrides `project..schema.draft`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge glue` Generate or check Rust/prost conversion glue (`v.rs`, `mod.rs`, `witforge_deps.rs`). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated glue files. | | `--plain-root ` | Absolute Rust module path to generated plain modules (for example `crate::plain`). | | `--proto-root ` | Absolute Rust module path to prost modules (for example `crate::proto`). | | `--no-std` | Emit `#![no_std]` + `alloc` compatible paths (`::alloc::*`, `::core::*`), overriding `witforge.toml` (conflicts with `--std`). | | `--std` | Emit default `std` paths, overriding `no-std = true` in `witforge.toml` (conflicts with `--no-std`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge doc` Generate or check deterministic Markdown contract reference pages (`index.md` and one `v_.md` per live version). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Markdown reference files. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge ts` Generate or check zero-dependency strict ESM TypeScript types, shared `Option` helpers (`witforge_types.ts`), interfaces, dependency modules (`witforge_deps/`), world metadata (`worlds.ts`), and bidirectional cross-version conversion adapters (`convert.ts` when two or more live versions exist). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated TypeScript files. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge ts-glue` Generate or check TypeScript checked protobuf glue targeting `@bufbuild/protobuf` (`protobuf-es` v2): `toProto` / `fromProto` conversions, per-function `toRequest` / `fromRequest` / `toResponse` / `fromResponse` helpers, `METHOD` constants, message schema references, and structured `WitforgeGlueError` diagnostics enforcing all 13 rows of the WIT decode profile plus encode-side range, scalar `char`, closed-enum, and exact fixed-length list bounds. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated TypeScript protobuf glue files. | | `--plain-root ` | ESM import root containing generated plain TypeScript files (relative path such as `../plain` or bare npm package specifier such as `@acme/plain`). | | `--proto-root ` | ESM import root containing generated `@bufbuild/protobuf` `*_pb.js` files (relative path such as `../proto` or bare npm package specifier such as `@acme/proto`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge py` Generate or check zero-dependency Python 3.11+ stdlib packages (`@dataclass(frozen=True, slots=True)`, `StrEnum`, `Protocol` interfaces, union variants, shared `Option`/`Ok`/`Err` helpers in `witforge_types.py`, dependency packages under `witforge_deps/`, `worlds.py`, bidirectional cross-version conversion adapters in `convert.py` when two or more live versions exist, and the empty PEP 561 `py.typed` marker). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Python package files. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge py-glue` Generate or check Python checked protobuf glue targeting official `google.protobuf` (`protoc --python_out` and `google.protobuf.json_format`): `to_proto` / `from_proto` conversions, per-function `to_request` / `from_request` / `to_response` / `from_response` helpers, `METHOD` constants, message class references (`proto_type`, `request_type`, `response_type`), and structured `WitforgeGlueError` (`ValueError` subclass) diagnostics enforcing all 13 rows of the WIT decode profile plus encode-side integer (rejecting `bool`), Unicode scalar `char`, closed-enum, exact fixed-length list, and map-key checks. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Python protobuf glue files. | | `--plain-root ` | Python package root containing generated plain Python modules (dotted absolute path such as `my_app.plain` or relative path such as `..plain`). | | `--proto-root ` | Python package root containing generated `protoc --python_out` `*_pb2.py` modules (dotted absolute path such as `my_app.proto` or relative path such as `..proto`). When a contract uses `deps/`, add the `--proto-root` directory itself to `PYTHONPATH` / `sys.path` because `protoc --python_out` emits root-relative cross-file `*_pb2` imports. | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge go` Generate or check zero-dependency, `gofmt`-formatted Go 1.22+ stdlib packages: root `doc.go`, structs for records and flags, typed `uint32` enums with `Valid()` and `String()`, sealed variant interfaces with case structs, Go `interface` declarations for function-bearing WIT interfaces, native fixed-length arrays (`[N]T`), exact signed/unsigned integer widths (`uint8..uint64`, `int8..int64`), Unicode `rune`, shared generic `Option[T]` / `Result[T, E]` helpers in `witforge_types`, `witforge_deps/` packages with cross-major canonical-owner aliases, `worlds` metadata, and bidirectional cross-version conversion packages under `convert/` when two or more live versions exist. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Go package files. | | `--go-module ` | Go module import path prefix for emitted packages (for example `example.com/acme/contracts/gen/plain`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge go-glue` Generate or check Go checked protobuf glue targeting `google.golang.org/protobuf` (`protoc-gen-go` and `protojson`, paired with `witforge proto --go-package`): root `doc.go`, structured `*glueerr.GlueError` implementing `error`, narrow-width and Unicode scalar helpers in `helpers`, per-major `ToProto` / `FromProto` conversions, per-function `ToRequest` / `FromRequest` / `ToResponse` / `FromResponse` helpers, typed `Method` constants, and `witforge_deps/` cross-major glue enforcing all 13 rows of the WIT decode profile plus encode-side Unicode scalar `rune`, valid UTF-8 `string`, closed-enum, non-nil `[]byte`, and deterministic sorted-key `map` checks. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Go protobuf glue files. | | `--go-module ` | Go module import path prefix for emitted glue packages (for example `example.com/acme/contracts/gen/glue`). | | `--plain-root ` | Go import path prefix for generated plain Go packages (matching `witforge go --go-module`). | | `--proto-root ` | Go import path prefix for generated `*.pb.go` packages (matching `witforge proto --go-package`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge java` Generate or check zero-dependency Java 21 LTS+ stdlib package trees under `--java-package`: root `package-info.java`, shared `WitforgeUnit`, `WitforgeResult`, and `WitforgeValues` defensive-copy/deep-equality helpers, per-version interface packages (`.v_.`), immutable `record` declarations for records and flags, `enum` declarations with `witName()`, `sealed interface ... permits ...` variants with nested case records, service `interface` declarations for function-bearing WIT interfaces, `witforge_deps/` packages (with canonical-owner sharing across majors), `Worlds.java` metadata when any live version declares worlds, and bidirectional cross-version conversion adapters (`ConversionErrorKind.java`, `WitforgeConversionException.java`, `Convert.java`) when two or more live versions exist. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Java source files. | | `--java-package ` | Base Java package prefix for emitted packages (for example `com.acme.contracts.plain`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge java-glue` Emit or check Java 21+ checked protobuf glue targeting official `com.google.protobuf` (`protobuf-java` + `protobuf-java-util` `JsonFormat`), converting between plain Java types from `witforge java` and `protoc --java_out` messages from `witforge proto` (supporting both `java_multiple_files = true` and `java_multiple_files = false`). Emits root `GlueErrorKind`, checked `WitforgeGlueException`, and `WitforgeGlueHelpers`, per-major `Glue` classes, and `witforge_deps/` glue with canonical-owner forwarding. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated Java protobuf glue files. | | `--java-package ` | Base Java package prefix for emitted glue packages (for example `com.acme.contracts.glue`). | | `--plain-root ` | Base Java package prefix for generated plain Java types (matching `witforge java --java-package`). | | `--proto-root ` | Base Java package prefix for generated protobuf classes (matching `witforge proto --java-package`). | | `--java-multiple-files` | Match paired `.proto` files compiled with `option java_multiple_files = true;` (default; conflicts with `--no-java-multiple-files`). | | `--no-java-multiple-files` | Match paired `.proto` files compiled without `java_multiple_files = true` (nested under each file's outer class; conflicts with `--java-multiple-files`). | | `--java-outer-classname ` | Explicit `option java_outer_classname` matching paired `.proto` generation (used when `--no-java-multiple-files` is set). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge csharp` Generate or check zero-dependency C# 12+ / .NET 8 LTS+ stdlib namespaces under `--csharp-namespace`: `#nullable enable` on every file, root `WitforgeTypes.cs` (`WitforgeUnit`, `WitforgeOption` for nested `option>`, `WitforgeResult`, and `WitforgeValues` defensive-copy and deep-equality helpers), per-version interface files (`V_/.cs`), `sealed record` types for records and flags, `enum` declarations with `ToWitName`/`TryParseWitName` extensions, `abstract record` + nested `sealed record` variants, `I` service interfaces, `WitforgeDeps/` namespaces with canonical-owner sharing across majors, `Worlds.cs` metadata when any live version declares worlds, and bidirectional cross-version conversion adapters (`Convert.cs`) when two or more live versions exist. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated C# source files. | | `--csharp-namespace ` | Base C# root namespace for emitted types (for example `Acme.Contracts.Plain`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge csharp-glue` Emit or check C# 12+ / .NET 8 LTS+ checked protobuf glue targeting official `Google.Protobuf` (`JsonFormatter` and `JsonParser`), converting between plain C# types from `witforge csharp` and `protoc --csharp_out` messages from `witforge proto --csharp-namespace`. Emits `#nullable enable` on every file, root `GlueErrorKind.cs`, `WitforgeGlueException.cs`, and `WitforgeGlueHelpers.cs`, per-major `V/Glue.cs` classes (`ToProto`/`FromProto`, `ToBytes`/`FromBytes`, `ToJson`/`FromJson`, `Method` constants, per-function request/response helpers, and `Params` records), and `WitforgeDeps/` glue with canonical-owner forwarding across majors. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for generated C# protobuf glue files. | | `--csharp-namespace ` | Base C# root namespace for emitted glue types (for example `Acme.Contracts.Glue`). | | `--plain-root ` | Base C# root namespace for generated plain C# types (matching `witforge csharp --csharp-namespace`). | | `--proto-root ` | Base C# root namespace for generated protobuf messages (matching `witforge proto --csharp-namespace`). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge plugin` Run a third-party process-based emitter plugin implementing the `protocol_version = 1` JSON-over-stdio protocol, reusing `witforge`'s contract validation, lockfile enforcement, ownership headers, cross-platform path guards, atomic nested-tree writes, `--check`, and `--diff`. | Option / Argument | Description | |---|---| | `` | Plugin name matching `^[a-z0-9][a-z0-9-]*$` (1 to 64 ASCII characters; resolves `witforge-gen-` strictly along absolute `PATH` directories). | | `[WIT_ROOT]` | WIT root containing `v.` version directories. | | `--out ` | Output directory for plugin-generated files. | | `--plugin-bin ` | Explicit path to the plugin executable (CLI-only; never allowed in `witforge.toml`). | | `--option ` | Pass a `KEY=VALUE` option to the plugin (repeatable; overrides `witforge.toml` plugin options). | | `--timeout-secs ` | Wall-clock timeout in seconds before terminating the plugin process (`1..=3600`, default `30`, overrides config). | | `--check` | Verify existing files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of output changes without changing the exit status. | | `--released ` | Released-version manifest path (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Project name in `witforge.toml`. | ### `witforge conformance` Generate or check the versioned cross-language protobuf conformance fixture bundle (`conformance_version = 1`: `vectors.json`, `proto/`, and `wit/`). | Option | Description | |---|---| | `--out ` | Output directory for the conformance bundle (`vectors.json`, `proto/`, `wit/`). | | `--polyglot-proto-options` | Populate canonical Go, Java, and C# protobuf file options on emitted `.proto` files. | | `--go-package ` | Base `go_package` import path prefix for emitted `.proto` files. | | `--java-package ` | Base `java_package` prefix for emitted `.proto` files. | | `--java-multiple-files` | Emit `option java_multiple_files = true;` on emitted `.proto` files (conflicts with `--no-java-multiple-files`). | | `--no-java-multiple-files` | Omit `option java_multiple_files`, overriding `--polyglot-proto-options` (conflicts with `--java-multiple-files`). | | `--java-outer-classname ` | Emit `option java_outer_classname = "";` on emitted `.proto` files. | | `--csharp-namespace ` | Base `csharp_namespace` prefix for emitted `.proto` files. | | `--check` | Verify existing bundle files match without writing; exits `1` on drift. | | `--diff` | Print a unified diff of bundle changes without changing the exit status. | ### `witforge generate` Run built-in generators configured in `witforge.toml` across all projects or `--project`. Use `--only ` to run a selected subset of generators. Configured `[project..plugins.]` sections are validated for schema and output-root guards and are never executed unless `--allow-plugins` is explicitly passed on the CLI (or invoke a single plugin directly with `witforge plugin `). | Option | Description | |---|---| | `--only ` | Limit generation to a comma-separated (or repeatable) subset of `rust`, `proto`, `schema`, `glue`, `doc`, `ts`, `ts-glue`, `py`, `py-glue`, `go`, `go-glue`, `java`, `java-glue`, `csharp`, `csharp-glue`, and `plugins`. Fails with `WF9001` if any name is unknown, empty, or not configured in any selected project (and requires `--allow-plugins` when `plugins` is listed). | | `--allow-plugins` | Explicitly opt in to executing configured `[project..plugins.]` entries (off by default). | | `--check` | Verify all configured outputs without writing; exits `1` on drift. | | `--diff` | Print unified diffs of output changes without changing the exit status. | | `--serde` | Enable Serde derives across configured Rust outputs (conflicts with `--no-serde`). | | `--no-serde` | Disable Serde derives across configured Rust outputs (conflicts with `--serde`). | | `--no-std` | Emit `#![no_std]` + `alloc` compatible paths across configured Rust and glue outputs (conflicts with `--std`). | | `--std` | Emit default `std` paths across configured Rust and glue outputs, overriding config (conflicts with `--no-std`). | | `--eq-hash` | Derive `Eq` and `Hash` on float-free generated Rust types, overriding config (conflicts with `--no-eq-hash`). | | `--no-eq-hash` | Disable `Eq`/`Hash` derives on generated Rust types, overriding config (conflicts with `--eq-hash`). | | `--try-from` | Emit `TryFrom` impls in `convert.rs` for converted nominal types, overriding config (conflicts with `--no-try-from`). | | `--no-try-from` | Disable `TryFrom` impls in `convert.rs`, overriding config (conflicts with `--try-from`). | | `--draft ` | Override the JSON Schema dialect for configured schema outputs (`7` or `2020-12`). | | `--released ` | Override the released-version manifest path for the run. | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge init` Scaffold a new witforge contract project (`wit/v0.1/contract.wit`, initial `wit/v0.1/wire.lock`, and `witforge.toml`), refusing to overwrite any existing file. | Option / Argument | Description | |---|---| | `[DIR]` | Target directory to initialize (defaults to `.`). | | `--package ` | WIT package identity (`:`, for example `example:hello`; defaults to `example:`). | | `--serde` | Enable `serde = true` in the generated `witforge.toml` Rust section. | ### `witforge new-version` Scaffold the next minor (or major) version directory from the latest existing version or an explicit `--from` version. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing version directories; omit to use the configured project root. | | `--major` | Create `v.0` without copying `wire.lock` instead of `v.`. | | `--from ` | Source version directory to clone (for example `v0.2`), allowing maintenance minors on an earlier major line. | | `--released ` | Path to the released-version manifest (defaults to `/released` or `project..released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge deps` Manage vendored `deps/` trees across unreleased version directories. Subcommands: - `witforge deps sync`: synchronize `deps/` trees within each major without modifying released or retired directories. ### `witforge deps sync` Synchronize vendored `deps/` trees from the canonical source version of each major into unreleased version directories of the same major, refusing symlinks and never modifying released or retired directories. | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing version directories; omit to use the configured project root. | | `--from ` | Canonical source version directory (for example `v0.1`); defaults to the highest released (or lowest live) version per major. | | `--check` | Report `deps/` drift without writing; exits `1` (`WF1033`) if any unreleased version differs. | | `--released ` | Path to the released-version manifest (defaults to `/released` or `project..released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge release` Validate a version directory and append it to the `released` manifest. | Option / Argument | Description | |---|---| | `` | WIT version directory to validate and record as released. | | `--released ` | Released-version manifest path (defaults to `/../released`). | | `--forbid-unstable` | Refuse releasing a version containing any `@unstable` declaration, overriding config (conflicts with `--allow-unstable`). | | `--allow-unstable` | Allow releasing a version containing `@unstable` declarations, overriding `policy.forbid-unstable-in-release = true` (conflicts with `--forbid-unstable`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge retire` Mark a released version directory as `retired` in the `released` manifest, enforcing contiguous oldest-prefix retirement order and requiring at least one remaining live version. | Option / Argument | Description | |---|---| | `` | Released WIT version directory to mark as `retired`. | | `--released ` | Released-version manifest path (defaults to `/../released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge diff` Compare two version directories or WIT roots (or compare a working-tree target against its Git revision via `--git-base`) and classify wire, source, API, and protobuf binary decode compatibility. | Option / Argument | Description | |---|---| | `[OLD]` | Older version directory or WIT root (or target directory when `--git-base` is given; omit with `--git-base` to use the configured project root). | | `[NEW]` | Newer version directory or WIT root (omit when `--git-base` is given). | | `--git-base ` | Compare the target version directory or WIT root against its committed Git tree at ``. | | `--json` | Emit the full diff report as JSON on stdout (takes precedence over `--format`). | | `--check[=VIEWS]` | Exit `1` when any breaking change hits the selected views: comma-separated subset of `wire`, `source`, `api`, `decode` (bare `--check` defaults to `[project..policy].diff-check` when configured, otherwise `wire,source,api` without `decode`). | | `--config ` | Explicit `witforge.toml` path supplying `[project..policy].diff-check` and `root` for `--git-base` (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge inspect` Inspect a single version directory or WIT root, printing a concise human summary or exporting the deterministic, schema-versioned (`version: 1`) JSON contract IR with `--json`. | Option / Argument | Description | |---|---| | `[PATH]` | Version directory or WIT root; omit to inspect the configured project root via `witforge.toml`. | | `--json` | Emit the versioned JSON contract IR (`version: 1`) on stdout (takes precedence over `--format`). | | `--released ` | Released-version manifest path when inspecting a WIT root (defaults to `/released`). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge freeze` Verify that every directory listed in `wit/released` has remained immutable in Git history (allowing only one-way `live -> retired` transitions). | Option / Argument | Description | |---|---| | `[WIT_ROOT]` | WIT root containing `released` and version directories; omit to check all configured projects. | | `--released ` | Released-version manifest path (defaults to `/released` or project `released` in `witforge.toml`). | | `--base ` | Lower-bound Git revision to bound the manifest history scan (defaults to full history). | | `--config ` | Explicit `witforge.toml` path (conflicts with `--no-config`). | | `--no-config` | Disable upward `witforge.toml` discovery (conflicts with `--config`). | | `--project ` | Select a single project from `witforge.toml`. | ### `witforge completions` Print shell completion scripts generated from the CLI command definition. | Argument | Description | |---|---| | `` | Target shell: `bash`, `zsh`, or `fish`. | ### `witforge explain` Print the catalogue explanation and public documentation URL for a diagnostic code. | Argument | Description | |---|---| | `` | Diagnostic code such as `WF1015` (case-insensitive). | ## `witforge.toml` configuration keys `witforge.toml` is discovered upwards from the working directory (stopping at `.git` or the filesystem root) unless `--config` or `--no-config` is passed. Unknown keys are refused (`exit 2`), files must be UTF-8 without a BOM, and paths are resolved relative to `witforge.toml` without shell expansion. | Key | Required | Type | Description | |---|---|---|---| | `version` | yes | integer | Configuration schema version; must be `1`. | | `[project.]` | yes (at least one) | table | Named contract project table. | | `project..root` | yes | path | WIT root directory containing `v.` version directories. | | `project..released` | no | path | Released-version manifest path (defaults to `/released`). | | `[project..rust]` | no | table | Plain Rust generator configuration. | | `project..rust.out` | yes (if section set) | path | Output directory for generated Rust files. | | `project..rust.serde` | no | boolean | Enable `serde::Serialize`/`Deserialize` derives (default `false`). | | `project..rust.no-std` | no | boolean | Emit `#![no_std]` + `alloc` compatible paths (`::alloc::*`, `::core::*`) (default `false`). | | `project..rust.eq-hash` | no | boolean | Derive `Eq` and `Hash` on generated float-free records, variants, enums, and flags (default `false`). | | `project..rust.try-from` | no | boolean | Emit `TryFrom` impls in `convert.rs` for converted nominal types (default `false`). | | `[project..proto]` | no | table | Protobuf generator configuration. | | `project..proto.out` | yes (if section set) | path | Output directory for generated `.proto` files. | | `project..proto.go-package` | no | string | Base `go_package` import path prefix (or explicit `path;alias` for single-file output). | | `project..proto.java-package` | no | string | Base `java_package` prefix derived per emitted proto package. | | `project..proto.java-multiple-files` | no | boolean | Emit `option java_multiple_files = true;` (or `false;`) on emitted `.proto` files. | | `project..proto.java-outer-classname` | no | string | Emit `option java_outer_classname = "";` (collision-checked per Java package and file). | | `project..proto.csharp-namespace` | no | string | Base `csharp_namespace` prefix derived as PascalCase segments per emitted proto package. | | `[project..proto.packages.]` | no | table | Exact per-package overrides (`go-package`, `java-package`, `java-multiple-files`, `java-outer-classname`, `csharp-namespace`) keyed by emitted proto package name. | | `[project..schema]` | no | table | JSON Schema generator configuration. | | `project..schema.out` | yes (if section set) | path | Output directory for generated JSON Schema files. | | `project..schema.draft` | no | string | JSON Schema dialect: `"7"` (default) or `"2020-12"`. | | `[project..glue]` | no | table | Rust/prost glue generator configuration. | | `project..glue.out` | yes (if section set) | path | Output directory for generated glue files. | | `project..glue.plain-root` | yes (if section set) | string | Absolute Rust module path to generated plain modules (`crate::...` or `::ext::...`). | | `project..glue.proto-root` | yes (if section set) | string | Absolute Rust module path to prost modules (`crate::...` or `::ext::...`). | | `project..glue.no-std` | no | boolean | Emit `#![no_std]` + `alloc` compatible paths (`::alloc::*`, `::core::*`) (default `false`). | | `[project..doc]` | no | table | Markdown contract reference documentation generator configuration. | | `project..doc.out` | yes (if section set) | path | Output directory for generated Markdown reference files. | | `[project..typescript]` | no | table | Strict ESM TypeScript plain types and interfaces generator configuration. | | `project..typescript.out` | yes (if section set) | path | Output directory for generated TypeScript files. | | `[project..typescript-glue]` | no | table | Checked TypeScript protobuf glue (`@bufbuild/protobuf`) generator configuration. | | `project..typescript-glue.out` | yes (if section set) | path | Output directory for generated TypeScript protobuf glue files. | | `project..typescript-glue.plain-root` | yes (if section set) | string | ESM import root for generated plain TypeScript files (relative path or bare npm package specifier). | | `project..typescript-glue.proto-root` | yes (if section set) | string | ESM import root for generated `@bufbuild/protobuf` `*_pb.js` files (relative path or bare npm package specifier). | | `[project..python]` | no | table | Python 3.11+ stdlib plain types and `Protocol` interfaces generator configuration. | | `project..python.out` | yes (if section set) | path | Output directory for generated Python package files. | | `[project..python-glue]` | no | table | Checked Python protobuf glue (`google.protobuf`) generator configuration. | | `project..python-glue.out` | yes (if section set) | path | Output directory for generated Python protobuf glue files. | | `project..python-glue.plain-root` | yes (if section set) | string | Python package root for generated plain Python modules (dotted absolute path or relative package path). | | `project..python-glue.proto-root` | yes (if section set) | string | Python package root for generated `protoc --python_out` `*_pb2.py` modules (dotted absolute path or relative package path). | | `[project..go]` | no | table | Go 1.22+ stdlib plain types and interfaces generator configuration. | | `project..go.out` | yes (if section set) | path | Output directory for generated Go package files. | | `project..go.go-module` | yes (if section set) | string | Go module import path prefix for emitted packages (for example `example.com/acme/contracts/gen/plain`). | | `[project..go-glue]` | no | table | Checked Go protobuf glue (`google.golang.org/protobuf`) generator configuration. | | `project..go-glue.out` | yes (if section set) | path | Output directory for generated Go protobuf glue files. | | `project..go-glue.go-module` | yes (if section set) | string | Go module import path prefix for emitted glue packages (for example `example.com/acme/contracts/gen/glue`). | | `project..go-glue.plain-root` | yes (if section set) | string | Go import path prefix for generated plain Go packages (matching `witforge go --go-module`). | | `project..go-glue.proto-root` | yes (if section set) | string | Go import path prefix for generated `*.pb.go` packages (matching `witforge proto --go-package`). | | `[project..java]` | no | table | Java 21+ stdlib plain types and interfaces generator configuration. | | `project..java.out` | yes (if section set) | path | Output directory for generated Java source files. | | `project..java.java-package` | yes (if section set) | string | Base Java package prefix for emitted packages (for example `com.acme.contracts.plain`). | | `[project..java-glue]` | no | table | Checked Java 21+ protobuf glue (`com.google.protobuf`) generator configuration. | | `project..java-glue.out` | yes (if section set) | path | Output directory for generated Java protobuf glue files. | | `project..java-glue.java-package` | yes (if section set) | string | Base Java package prefix for emitted glue packages (for example `com.acme.contracts.glue`). | | `project..java-glue.plain-root` | yes (if section set) | string | Base Java package prefix for generated plain Java types (matching `witforge java --java-package`). | | `project..java-glue.proto-root` | yes (if section set) | string | Base Java package prefix for generated protobuf classes (matching `witforge proto --java-package`). | | `project..java-glue.java-multiple-files` | no | boolean | Match paired `.proto` `java_multiple_files = true\|false` (default `true`). | | `project..java-glue.java-outer-classname` | no | string | Explicit `option java_outer_classname` matching paired `.proto` files when `java-multiple-files = false`. | | `[project..csharp]` | no | table | C# 12+ / .NET 8+ stdlib plain types and interfaces generator configuration. | | `project..csharp.out` | yes (if section set) | path | Output directory for generated C# source files. | | `project..csharp.csharp-namespace` | yes (if section set) | string | Base C# root namespace for emitted types (for example `Acme.Contracts.Plain`). | | `[project..csharp-glue]` | no | table | Checked C# 12+ / .NET 8+ protobuf glue (`Google.Protobuf`) generator configuration. | | `project..csharp-glue.out` | yes (if section set) | path | Output directory for generated C# protobuf glue files. | | `project..csharp-glue.csharp-namespace` | yes (if section set) | string | Base C# root namespace for emitted glue types (for example `Acme.Contracts.Glue`). | | `project..csharp-glue.plain-root` | yes (if section set) | string | Base C# root namespace for generated plain C# types (matching `witforge csharp --csharp-namespace`). | | `project..csharp-glue.proto-root` | yes (if section set) | string | Base C# root namespace for generated protobuf messages (matching `witforge proto --csharp-namespace`). | | `[project..plugins.]` | no | table | Third-party emitter plugin configuration for plugin `` (`^[a-z0-9][a-z0-9-]*$`; executable paths are forbidden in config and `witforge generate` only executes plugins when `--allow-plugins` is passed). | | `project..plugins..out` | yes (if section set) | path | Output directory for files emitted by plugin `` (checked for overlap against every other configured output root). | | `project..plugins..options` | no | table of strings | Optional string key-value options passed to the plugin in stdin JSON (overridden per key by CLI `--option`). | | `project..plugins..timeout-secs` | no | integer | Optional wall-clock execution timeout in seconds (`1..=3600`, default `30`, overridden by `--timeout-secs`). | | `[project..policy]` | no | table | Project governance policy table. | | `project..policy.diff-check` | no | array of strings | Default compatibility views for bare `witforge diff --check` (non-empty subset of `"wire"`, `"source"`, `"api"`, `"decode"`). | | `project..policy.forbid-unstable-in-release` | no | boolean | Refuse `witforge release` when any `@unstable` declaration is present (default `false`). | --- # Diagnostic codes URL: https://witforge.org/docs/diagnostics/ Every `witforge` command emits structured diagnostics with `--format json` or `--format sarif`. SARIF rules link directly to the per-code anchors on this page, and `witforge explain ` prints any code's catalogue entry offline from the CLI. Positions use **1-based lines and 1-based UTF-16 code-unit columns** (the SARIF 2.1.0 default). Physical paths in JSON `file` fields and SARIF `artifactLocation.uri` are repository-relative with forward slashes when inside the working directory; SARIF uses an absolute `file:///` URI for files outside the working directory. Logical WIT paths (such as `example:pkg/types/record.field`) appear in `logical` (JSON) and `logicalLocations` (SARIF). ## Subset and contract codes (`WF1001`-`WF1033`) ### WF1001 **Severity:** `error` Unrecognised WIT construct outside the supported subset. Legacy umbrella code; individual subset rules now emit `WF1010`-`WF1030`. ### WF1002 **Severity:** `error` A lockfile belongs to another package (`namespace:name`). Check the `wire.lock` or `--against` baseline path named by the diagnostic. ### WF1003 **Severity:** `error` Two names in one scope collide: either they differ only in ASCII letter case (including against a reserved lockfile member), or they map to the same generated Rust, polyglot (TypeScript, Python, Go, Java, or C#), protobuf, `prost`, or glue identifier, filename, accessor, or reserved name. Rename one of the colliding items. ### WF1010 **Severity:** `error` · **Prior:** `WF1001` Root contract package version is missing or not `..0`. Declare `package ns:name@..0;` with patch `0` and no pre-release or build metadata. ### WF1011 **Severity:** `error` · **Prior:** `WF1001` A nested `package` block was found inside a version directory. Place dependency packages under the standard `deps/` directory instead. ### WF1012 **Severity:** `error` · **Prior:** `WF1001` A dependency package under `deps/` is missing a version or uses a version other than `..0`. ### WF1013 **Severity:** `error` · **Prior:** `WF1001` Duplicate dependency package identity under `deps/`, or a dependency declaring the same `namespace:name` as the root contract package. Pin one version per dependency package. ### WF1014 **Severity:** `error` · **Prior:** `WF1001` Unsupported or invalid WIT stability annotation. Only `@since`, `@unstable`, and `@deprecated` are accepted, and `@deprecated` must accompany `@since` or `@unstable`. Annotation versions must use `..0`, cannot be later than the containing package version, cannot have `@deprecated` predate `@since`, and must keep `@since` aligned across multi-version contracts. Also emitted when `witforge release --forbid-unstable` (or `[project..policy].forbid-unstable-in-release`) refuses a version containing `@unstable` items. ### WF1015 **Severity:** `error` · **Prior:** `WF1001` Resources and handles (`resource`, `borrow`, `own`) are not supported. Model state as pure values passed to freestanding functions. ### WF1016 **Severity:** `error` · **Prior:** `WF1001` `future` and `stream` types are not supported; witforge contracts are synchronous. ### WF1017 **Severity:** `error` · **Prior:** `WF1001` Legacy code: `char` is now supported (retained for diagnostic code stability). ### WF1018 **Severity:** `error` · **Prior:** `WF1001` `error-context` is not supported; model errors as explicit records, enums, or variants in `result`. ### WF1019 **Severity:** `error` · **Prior:** `WF1001` Tuples are not supported; define a named `record` so every field has a stable wire number. ### WF1020 **Severity:** `error` · **Prior:** `WF1001` Unsupported `map` key type. WIT `map` keys must be `bool`, an integer (`u8`-`u64`, `s8`-`s64`), `char`, or `string`. ### WF1021 **Severity:** `error` · **Prior:** `WF1001` Invalid fixed-length list length (`list`). Fixed-length lists must have length `1 <= N <= 65536`; use unbounded `list` for zero-length or larger lists. ### WF1022 **Severity:** `error` · **Prior:** `WF1001` Empty records are not supported; add a field or use a payload-less variant case. ### WF1023 **Severity:** `error` · **Prior:** `WF1001` `async` functions are not supported; witforge contracts are synchronous. ### WF1024 **Severity:** `error` · **Prior:** `WF1001` `get` and `set` accessors are not supported; use ordinary functions. ### WF1025 **Severity:** `error` · **Prior:** `WF1001` Inline interfaces in a `world` are not supported; declare a named `interface` and import or export it from the world. ### WF1026 **Severity:** `error` · **Prior:** `WF1001` Named (renamed) interface imports or exports in a `world` are not supported; import or export the interface directly without a local alias. ### WF1027 **Severity:** `error` · **Prior:** `WF1001` Functions defined directly in a `world` are not supported; place functions inside a named interface and export that interface from the world. ### WF1028 **Severity:** `error` · **Prior:** `WF1001` Types defined directly in a `world` are not supported; define types inside a named interface. ### WF1029 **Severity:** `error` · **Prior:** `WF1001` A `world` imports or exports an interface with no package or from a package outside `deps/`. ### WF1030 **Severity:** `error` · **Prior:** `WF1001` Type nesting depth, alias chain depth, canonical type byte length, synthesized protobuf wrapper name length, or canonical type cycle limit was exceeded. ### WF1031 **Severity:** `error` Version directory name (`v.`) disagrees with its declared WIT package version (`..0`). ### WF1032 **Severity:** `error` Versions in a WIT root or the two endpoints of `diff` declare different package identities (`namespace:name`). ### WF1033 **Severity:** `error` Pinned dependency graphs differ across versions under a WIT root, across `diff` endpoints, against a version-directory `--against` baseline, or between `deps/` trees checked by `witforge deps sync --check`. ## Lockfile codes (`WF1100`-`WF1205`) ### WF1100 **Severity:** `error` Lockfile continuity, drift evaluation, order-section, or baseline-policy violation. When a live member disagrees with its locked entry, the related location points at the conflicting line in `wire.lock`. ### WF1101 **Severity:** `error` A live contract member has no wire number in `wire.lock`. Run the suggested `witforge lock` command to assign one. ### WF1102 **Severity:** `error` A removed contract member is still unreserved in `wire.lock`. Run `witforge lock` to mark it `reserved`. ### WF1103 **Severity:** `error` A removed member was reintroduced under its reserved name and wire number. Give the member a new name (or use `--against` with the released baseline if the removal was only a draft). ### WF1104 **Severity:** `error` A stale draft entry remains in `wire.lock`. Run `witforge lock` to drop it. ### WF1105 **Severity:** `error` A draft member changed kind or canonical type since `wire.lock` was written. Run `witforge lock` to update the draft entry. ### WF1106 **Severity:** `error` `wire.lock` is not in the canonical formatting produced by `witforge lock`. Run `witforge lock` to rewrite it canonically. ### WF1107 **Severity:** `note` The pinned dependency graph could not be compared because `--against` does not point to a version-directory `wire.lock`. ### WF1108 **Severity:** `error` A draft removal can be restored; running `witforge lock --against` will un-reserve the member. ### WF1109 **Severity:** `error` A released version directory listed in `wit/released` changed after release, had an entry removed from `wit/released`, contains a symlink or untracked file, or lacks a git-tracked `wire.lock` under its exact spelling. Restore the released directory and manifest rather than editing a released version in place. ### WF1201 **Severity:** `note` `witforge lock` assigned a wire number to a newly added member. ### WF1202 **Severity:** `note` `witforge lock` marked a removed member as `reserved`. ### WF1203 **Severity:** `note` `witforge lock` dropped a stale draft entry. ### WF1204 **Severity:** `note` `witforge lock` updated a draft member's kind or canonical type. ### WF1205 **Severity:** `note` `witforge lock` restored a draft removal. ## Generation codes (`WF2001`-`WF2002`) ### WF2001 **Severity:** `error` Generated output is missing, changed, extra, or otherwise out of sync with `--check`. Re-run the suggested generator command. ### WF2002 **Severity:** `error` Version-to-version conversion adapter generation (`convert.rs`, `convert.ts`, `convert.py`, `convert/`, `Convert.java`, `Convert.cs`) refused an incompatible evolution between adjacent versions (such as adding a non-defaulted record field or retyping a member). ## Diff codes (`WF3001`-`WF3004`) ### WF3001 **Severity:** `error` (breaking a gated view under `--check[=]`) or `warning` (un-gated) `witforge diff` found a wire-, source-, generated-API-, or decode-breaking change. Without `--check`, `diff` exits `0` and emits `WF3001` at level `warning`; with `--check` or `--check=`, `diff` exits `1` and emits `WF3001` at level `error` for changes breaking a gated view (and `warning` for breaking changes outside the gated views). ### WF3002 **Severity:** `note` `witforge diff` found a compatible change. ### WF3003 **Severity:** `note` `witforge diff` found a record whose generated new-to-old conversion is guaranteed to fail because the older version requires a member removed in the newer version. ### WF3004 **Severity:** `note` `witforge diff` found a non-defaulted record field addition, retyped member, or cross-major conversion omission that will cause conversion adapter generation (`convert.rs`, `convert.ts`, `convert.py`, `convert/`, `Convert.java`, `Convert.cs`) to refuse or omit that item. ## Operational and internal codes (`WF9000`-`WF9004`) ### WF9000 **Severity:** `error` Internal compiler error (unexpected invariant failure only; never emitted for usage, I/O, parse, or safety-guard errors). ### WF9001 **Severity:** `error` Command-line usage or argument error (invalid flags, missing required arguments, reversed `diff` endpoints, invalid module root). Exits `2`. ### WF9002 **Severity:** `error` Filesystem or I/O error (missing file, directory, or lockfile; permission denied; unreadable path; write failure). Exits `2`. ### WF9003 **Severity:** `error` Parse or format error (invalid WIT syntax or name resolution error, malformed `wire.lock`, malformed `released` manifest, or invalid `witforge.toml` / BOM). Exits `2`. ### WF9004 **Severity:** `error` Safety guard or freeze-policy refusal (locking or writing into a released directory, symlinked version directory or symlink/submodule/special file inside a released directory, `deps/` tree, or `diff --git-base` target, shallow clone on `freeze` or `diff --git-base`, overlapping or unowned output path, non-canonical `v...` directory name, unexpanded shell path in `witforge.toml`, or a third-party plugin timeout, oversized output, path/collision violation, or missing/foreign ownership header). Exits `2`.