Skip to navigation

Cargo Build Scripts: Define Generated-Artifact Contracts for Claude Code

In short: Find what a Cargo build script generates, declares, and reruns before asking Claude Code to change it.

Published 20 min read
On this page

Direct answer

A Cargo build script is a Rust program Cargo compiles and runs before building your package, and it owns three things worth writing down: the inputs it reads, the outputs it emits, and the conditions under which Cargo reruns it. It declares generated files, emits metadata and compiler settings, and tells Cargo when a rebuild is needed through rerun directives. The useful way to treat a build script is as a small build-time interface rather than an opaque pre-build step, because that is what makes a change to it reviewable. The concrete win is a documented contract that says which files are generated, what triggers a rerun, and what environment or metadata the build depends on. The concrete loss is that a generated artifact being present proves nothing about whether it is correct, so a build that succeeds has not validated the generation logic.

Ask Claude Code to inventory the inputs, outputs, and rerun conditions before changing a build script, and keep generated files out of the edit by default. The official best-practices guidance warns against editing generated clients; the same ownership discipline applies to files a build script produces.

Why an undocumented build script costs a build

Three situations turn a build script into a time sink. A generated file is edited by hand to fix a symptom, the next rebuild overwrites it, and the fix disappears. A rerun condition is missing, so a change to a real input does not trigger a rebuild and the build uses stale output. An environment or metadata dependency is hidden inside the script, so the build works on one machine and fails on another with no visible cause.

None of these are Cargo defects. They are the predictable result of treating a build script as a black box that “just runs first”. The cost lands as wasted debugging time and as flaky-looking builds that differ between machines for reasons nobody wrote down.

There is a revert advantage here. A build script is a single Rust file plus manifest declarations, so documenting its contract and reviewing a change is a small, revertible diff. That makes it a reasonable Claude Code task as long as the inventory happens before the edit and generated outputs stay out of scope.

Evidence and its limits

Official, F019: The Cargo Book documents build scripts as declared in the package manifest, with documented mechanisms for rerun conditions, printed metadata, and compiler environment output. The manifest format reference documents the build key that names the script. The build-script page was not full-page fetched during research, so exact directive names and their precedence should be verified against the current reference before relying on a fine detail.

Official, features: The features reference documents how a build script can emit feature-related information. A build script that enables or reports features adds a resolver-visible effect, which is a boundary worth recording.

Official, F020 support: Claude Code best practices warns against editing generated clients and recommends checks that return pass or fail. This post applies that ownership caution to generated build artifacts. Claude Code common workflows covers iterating an edit against a command.

Derived, F020: Writing down a build script’s artifacts and rerun conditions as an interface before changing the script is an editorial review practice built on the official generated-client caution. It is not a Cargo requirement, and it does not claim any generated artifact is correct.

No build-time result, compile-time number, or generation benchmark is reported here, because none was measured. A successful build is not presented as evidence of correctness.

What a build script owns

A build script is a Rust file, conventionally build.rs, named in the manifest under a build key. Cargo compiles it as its own crate, runs it before building the package, and gives it a way to communicate back through printed instructions and through files it writes.

Responsibility Where it lives What to record
Read build inputs Source tree, files, env vars the script reads Every file and variable the script depends on
Emit generated files An output directory Cargo provides Which files are generated and their names
Print metadata and settings Instructions the script prints Which settings reach the compiler
Declare rerun conditions Rerun directives the script prints What makes Cargo rerun the script

Read the table as the contract. Each row is something a reviewer needs to know to judge a change, and each is a place where an undocumented dependency causes a surprise later. A script that reads a file without declaring a rerun condition on it is the classic source of stale builds.

The script does not own the generated files in the sense of them being source. They are build outputs. That distinction is what the ownership discipline in the next section is about.

Read the manifest declaration

The manifest names the script with a build key. When that key is present, Cargo builds and runs the script before the package. The manifest reference documents this declaration and the fact that the script is compiled as its own crate.

bash
[package]
build = "build.rs"

[build-dependencies]
some-codegen-tool = "1"

The [build-dependencies] table is where dependencies used only by the build script live. They are compiled for the host and are not part of the package’s normal dependency graph. Recording them separately matters because a build dependency that changes can change what the script generates without any change to the package source.

Two things to confirm from the manifest during review. That the build key points at the file you think it does, since a nonstandard path is easy to miss. And that build dependencies are genuinely build-only, because a codegen tool that also leaks into the runtime dependency graph is a different problem.

Inventory inputs and outputs

The inventory is the artifact that makes a build script reviewable. One row per input and output, with the source of truth for each.

Kind Example Where it comes from Rerun implication
Input file a schema or IDL in the repo Versioned source Script should rerun when it changes
Input env var a path or feature flag Build environment Undeclared means stale or machine-dependent builds
Generated source emitted Rust file Written by the script Regenerated on rerun; not hand-editable
Generated metadata emitted compiler setting Printed by the script Affects how the crate compiles

The pass condition for the inventory is that every input the script reads has a corresponding rerun condition, and every generated file has a named owner in the script. Anything the script reads from the environment without declaring it is a finding: either declare the dependency or remove the hidden read.

The generated files belong in a Cargo-provided output directory, not in the source tree. A script that writes into the source tree creates the hand-edit hazard described earlier, because the generated file looks like source and gets edited like source until a rebuild erases the edit.

Interpret rerun-if directives

Rerun directives are how the script tells Cargo when a rebuild is needed. The official build-script documentation describes these mechanisms; the exact directive names and precedence should be confirmed against the current reference because the page was not full-page fetched during research.

Rerun signal Meaning Failure mode if missing or wrong
Rerun on a tracked file changing Rebuild when an input changes Stale output when the input changes
Rerun on a tracked directory Rebuild when contents change Stale output for files added to the tree
Rerun when an env var changes Rebuild when the variable differs Machine-dependent builds with no visible cause
Rerun always Rebuild every time Correct but slow; a trade worth naming

Read the table as the rerun contract. The default behavior when a script prints no rerun directive is conservative, and the precise default should be confirmed from the reference rather than assumed. What this post asserts is the review rule: every real input needs a declared rerun condition, and a script that reruns always is paying a build-time cost that should be a conscious choice.

The dangerous case is the quiet one. A script that reads a config file but declares no rerun-on that file will produce correct output the first time and stale output after the config changes, on every machine where the first build was cached. That bug looks like a caching problem in the toolchain when it is a missing declaration in the script.

Review cargo rustc env and metadata

A build script can emit compiler settings and metadata that affect how the package compiles. These are part of the contract because they change the compilation of code that was not itself edited. The official documentation describes these mechanisms; exact names and precedence should be rechecked against the current reference.

Emitted information Effect Review question
A compiler setting or define Changes how the crate compiles Does any source assume this define?
A feature-related emission Can affect feature resolution Which features become visible, and to whom?
A link or search path Changes linking Does this hide an environment dependency?

The feature-related case is the one that crosses into the Cargo feature unification guide, which covers how features combine across selected packages to expose optional APIs. A build script that emits feature information is participating in that resolution, so a change to it can change the API surface of the build, not just the files on disk.

The link and search path case is the one that hides environment dependencies. A path that resolves on one machine and not another is a portability finding, and it belongs in the inventory rather than in a comment that says “works on my machine”.

Connect generated files to Rust modules

Generated source files become part of the crate through module declarations that include them. The generated file is not source; the module declaration is, and it names what the script produced. This is the boundary that keeps hand edits away from generated code.

Artifact Owned by Edit here or not
The module declaration including generated code Your source Yes, this is source
The generated file itself The build script No, regenerate instead
The script that produces the file The build script Yes, this is the real fix
Build dependencies of the script Manifest [build-dependencies] Yes, versioned with the repo

Read the table as an ownership map. When something about generated code is wrong, the fix belongs in the script or in the input that feeds it, not in the generated file. The official best-practices warning against editing generated clients is the same rule applied to a different generator, and it transfers directly to build artifacts.

This is where the batch’s generated-code posts connect. The C# source generators guide covers reviewing a compiler extension’s inputs, incremental behavior, diagnostics, and output ownership, which is the same contract discipline for a different generator. OpenAPI Generator Customization and GraphQL Code Generator Client Presets cover keeping templates and configuration in sync so generated diffs trace to inputs.

Review a build script change

A build script change is reviewable when the diff is judged against the contract, not against whether the build succeeds. The build succeeding is the entry condition, not the pass condition.

Change type What to verify Pass condition
New generated file Output directory and rerun condition declared Clean rebuild produces the file
New input read Rerun condition on the input Changing the input triggers a rebuild
New emitted setting Downstream code still compiles and behaves Build plus targeted test pass
Changed build dependency Generated output diff is intended Output diff matches the intent
Removed rerun condition Nothing regressed to stale output Touching an input forces a rebuild

Two defects to catch in review. A generated file edited by hand as part of the change, which will be overwritten on the next clean build. And a new input read with no rerun condition, which produces a build that works once and then goes stale.

bash
cargo build -vv

The verbose output shows the emitted instructions and the generated files. Treat it as raw material to search rather than something to read end to end.

The pass condition is concrete. A clean build produces the expected generated files, changing a declared input triggers a rerun, and the build succeeds on a machine that does not have the hidden environment the script used to depend on. The official best-practices guidance favors this kind of check over a prose report.

When a build script is the wrong tool

The contract discipline in this post assumes a build script is the right tool for the job. Sometimes it is not, and recognizing that is part of reviewing one. A script that only sets a compiler flag, only enables a feature, or only copies a static file may be doing work a manifest declaration or a normal dependency could do without a build-time program.

The script does Better fit may exist Why it matters
Set one compiler setting A profile or manifest declaration Removes a build-time program and its rerun cost
Enable a feature A feature declaration Features are resolved visibly, not emitted quietly
Copy a static file A normal include or dependency Avoids a generated artifact that can go stale

Read the table as a simplification pass, not a rule. Build scripts are genuinely needed for bindings generation, codegen from a schema, and platform detection. The review question is whether this script earns its build-time cost and its hidden-dependency risk, or whether a declarative alternative would be easier to reason about.

Removing an unnecessary build script is a real win, and it is also a behavior change worth its own review, because anything downstream that assumed the script’s output will notice. The same ownership discipline applies in reverse: record what the script used to provide before you delete it.

The concrete win, loss, and implication

The concrete win is a build script a reviewer can evaluate. Once the inputs, outputs, and rerun conditions are written down, a change to the script is judged against a contract instead of against whether the terminal turned green. That shortens the path from “the build is doing something weird” to a specific missing declaration.

The concrete loss is that a documented contract still does not prove the generated artifact is correct. Writing down what a script produces and when it reruns makes the mechanism reviewable, and it says nothing about whether the generated code is right. Validating generated output is a separate problem that needs its own check.

The practical implication is that generated files are outputs, not source. Teams that treat generated artifacts as outputs, and that route every fix through the script or its inputs, stop losing hand edits to rebuilds. Teams that patch generated files by hand keep rediscovering that the file is not theirs.

Build scripts are one generated-code boundary among several this batch covers. The Cargo feature unification guide covers how features combine across selected packages, which is the mechanism a feature-emitting build script participates in. The Cargo profile boundaries guide covers separating diagnostic and optimization settings from behavior-changing ones, and the Cargo workspace inheritance guide covers sharing manifest metadata across a workspace.

Other generators in the batch follow the same ownership discipline. The C# source generators guide covers a compiler extension contract. OpenAPI Generator Customization covers keeping templates and config in sync. GraphQL Code Generator Client Presets covers reviewing generated boundaries back to schema inputs. sqlc Query Annotations covers aligning SQL with generated types.

For schema and wire contracts, the Protocol Buffer Reserved Fields guide covers field-number reuse and reservation. Go Module Graph Pruning covers the Go module graph that sits underneath any generated Go bindings.

Review and verification habits around generated code

Generated code is easy to get wrong quietly, which makes verification habits relevant. Before calling a build-script change done, ask what Claude Code verification requires, and prevent false success from passing tests when the check is a green build that never exercised the generated code path. A build succeeding is not generation correctness.

The cost of a clean rebuild to verify a small script edit connects to Claude Code cost per verified change. A rerun-condition test is a cheap check that earns its place on every script change. When a script edit turns into a repo-wide reformat, that is the pattern the Claude Code overengineering guide warns about.

What a dependency does during installation, as distinct from what a build script does at build time, is covered by the Claude Code dependency install side effects guide. The risk of a proposed dependency that does not exist is covered by the Claude Code hallucinated packages guide. On the trust boundary around code that runs during your build, the Claude Code repository hooks guide covers hooks that execute in your checkout.

Evidence map showing a build script as a build-time interface owning inputs, generated outputs, metadata, and rerun conditions.
Editorial evidence map based on F019 and F020. A build script owns declared inputs, outputs, and rerun conditions; generated files are outputs, not source. Labels are the post author’s.

Checklist before you change a build script

Run this list before approving a build-script change. Each row is a pass condition.

Check Pass condition If it fails
Input inventory Every file and env var the script reads is listed Complete the inventory first
Rerun conditions Every real input has a declared rerun trigger Add the missing declaration
Generated file ownership Generated files are written to a Cargo output directory Move writes out of the source tree
No hand edits The diff does not include edits to generated files Route the fix through the script or input
Emitted settings reviewed Every emitted compiler setting is named Enumerate them before merging
Environment deps visible Hidden machine dependencies are declared or removed Declare them or drop the read
Clean build verified A clean rebuild reproduces the expected outputs Clean build before merging
Workflow from inventorying build script inputs and outputs through checking rerun conditions, reviewing emitted settings, and verifying a clean rebuild.
Editorial workflow based on F019 and F020. The sequence describes a reviewable routine; it is not an official Cargo command sequence.

Working with Claude Code on a build script

Give the agent three inputs: the build script and manifest, the behavior you want to change, and the definition of done. Ask for an inventory of inputs, outputs, and rerun conditions as the first step, and ask it to keep generated files out of the diff. The verification step should be a clean rebuild plus a rerun check on a declared input.

Reviewing the agent’s inventory is the reviewer’s job. The agent can read the script and run read-only build commands, but deciding whether a hidden environment dependency is acceptable is a portability decision that needs your input. The Claude Code verification guide covers the review questions: what changed, what proves it, and what was not checked.

Tradeoff between a documented generated-artifact contract that is reviewable and the clean-build verification cost each script change requires.
Editorial tradeoff diagram based on F019 and F020. A written contract makes script changes reviewable; the trade is that correctness of generated output still needs its own check.

Data gap and future update

The build-script page was not full-page fetched during the research pass behind this post, so the exact rerun directive names, their precedence, and the default rerun behavior should be confirmed against the current Cargo Book before relying on a specific detail. The general contract shape in F019 is documented behavior; the fine mechanics are left to the reference.

No build-time result, compile-time number, or generation benchmark is reported here, because none was measured. Whether a given script’s rerun policy adds measurable build time on a specific project would need a measurement pass with a fixed toolchain. No such data was collected.

Generated-artifact correctness is deliberately out of scope. This post covers the contract around generation, not whether any generated code is semantically correct, and no claim is made that a successful build validates the generation logic.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. It is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route, or read the quickstart for the request shape.

FAQ

Should Claude Code edit generated files?

Not by default. Generated files are build outputs that a rebuild overwrites, so a hand edit is lost on the next clean build. The fix belongs in the build script or in the input that feeds it. The official best-practices warning against editing generated clients is the same ownership rule.

What makes a build go stale with a build script?

A missing or wrong rerun condition. If the script reads an input without declaring a rerun trigger on it, Cargo has no reason to rerun the script when that input changes, and the build keeps using the old generated output. The fix is declaring the rerun condition for every real input.

Where do build script dependencies live?

In [build-dependencies]. They are compiled for the host and used only by the build script, so they are separate from the package’s normal runtime dependency graph. A change to a build dependency can change generated output without any change to package source.

Does a successful build prove the generated code is correct?

No. A successful build proves the generated code compiles. Whether it is semantically correct is a separate question that needs its own check. This post deliberately makes no correctness claim about generated artifacts.

Why does the build work on one machine and fail on another?

Usually a hidden environment dependency. A path, variable, or tool the script reads without declaring makes the build machine-dependent. The inventory in this post is the remedy: declare every environment input or remove the hidden read.

This post is one of six language and build-system guides written together. The Rust side continues with Cargo Feature Unification, Cargo Profile Boundaries, and Cargo Workspace Inheritance. The Go side is covered by Go Module Compatibility, Go Workspace Boundaries, and Go Module Graph Pruning.

JVM and .NET posts cover version and variant selection: Gradle Constraints vs Dependencies, Gradle Capability Conflicts, Gradle Variant Attributes, Maven Optional Dependencies, and NuGet Central Package Management.

Generated-code boundaries across the batch include C# Source Generators, OpenAPI Generator Customization, GraphQL Code Generator Client Presets, sqlc Query Annotations, and Protocol Buffer Reserved Fields. Framework maintenance is covered by Django Deprecation Runway, Rails Upgrade Sequence, and Angular Update Guide.

More from this batch

More Claude Code troubleshooting

Sources

Control checklist covering input inventory, rerun conditions, generated-file ownership, emitted settings, and a verified clean rebuild.
Editorial control checklist derived from F019 and F020. Passing the checklist shows the script change was reviewed honestly; it does not prove generated output is semantically correct.
Verdict that treating a build script as a documented build-time interface keeps generated files out of hand edits and makes reruns predictable.
Editorial verdict based on F019 and F020. Generated files are outputs; fixes belong in the script or its inputs, and the contract makes a change reviewable.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →