writing-zig
Skill2 starsChanged 4 months agoMITView on GitHub
Write, test, review, migrate, or debug Zig code and build scripts. Use for Zig language, standard-library, build-system, package, allocator, C ABI, performance, and compiler-version work; establish the project's pinned Zig version before applying any API guidance.
In this repository34 other files it gives its agents.
- capture-collaboration-evidenceSkill
- clarify-before-buildingSkill
- cross-platform-project-build-archSkill
- deep-code-reviewSkill
- dispatchSkill
- erect-agent-stackSkill
- fix-zig-deps-hashSkill
- gather-project-intentionsSkill
- handoffSkill
- hulk-bug-handoffSkill
- i18nSkill
- llvm-guided-optimizationSkill
- mechatron-ciSkill
- memoriesSkill
- mficSkill
- multi-implementation-contractsSkill
- no-ai-slopSkill
- onboardSkill
- performance-profilingSkill
- planning-workSkill
- scaffold-zig-projectSkill
- ship-itSkill
- test-isolationSkill
- universal-app-frontendSkill
- upgrading-zig-16-to-17Skill
- walking-decisionsSkill
- writing-bendSkill
- writing-elmSkill
- writing-leanSkill
- writing-nixSkill
- writing-rocSkill
- writing-rustSkill
- writing-webassemblySkill
- zig-microbenchmarksSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
18 rules. About 0 are common, 10 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈10
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
Treat Zig's compiler version as part of the source contract.
- Distinctive: line 13
When stamping build identity, follow the shared build revision rule.
- Very specific: line 18
Read the project AGENTS.md, INTENT.md, PLAN.md, flake.nix, lockfile, build.zig.zon, and any version-specific Zig guide before substantive …
- Distinctive: line 24
Read only API guidance matching that exact Zig version.
- Distinctive: line 28
Keep toolchain changes separate from feature changes.
- Very specific: line 53
Follow TDD: write a focused failing test for behavior, confirm the red phase, implement the smallest correction, then run the complete …
- Very specific: line 59
Keep pure decoding and business logic separate from I/O.
- Distinctive: line 65
Prefer a complete struct literal where lifetime and pointer-stability rules permit it.
- Distinctive: line 72
Document ownership, allocator pairing, lifetime, nullability, alignment, error representation and thread-safety.
- Distinctive: line 75
Do not silently downgrade failed concurrency or reference-tool setup.
- Distinctive: line 78
Run cross-target build and packaged-artifact smoke checks for every supported platform.
- Very specific: line 98
Use the compiler source already selected by the project.
- Distinctive: line 101
Keep language package metadata and Nix fetch/cache inputs synchronized.
- Very specific: line 106
Use fix-zig-deps-hash only for a genuine dependency-content change.
- Very specific: line 121
Do not pass -j"$NIX_BUILD_CORES" unguarded (even with a :-1 unset/empty fallback): when Nix runs with cores = 0, NIX_BUILD_CORES=0 produces …
- Very specific: line 134
Never share ZIG_LOCAL_CACHE_DIR or --cache-dir across separate checkouts, git worktrees, copied trees, mutation runs, or baseline/oracle …
- Very specific: line 225
Use the memories skill to retrieve the exact evidence before applying a lesson.
- Distinctive: line 229
When a Zig-specific failure repeats, add a concise, versioned lesson to the appropriate project or shared memory and improve this skill or …
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Writing Zig
Treat Zig's compiler version as part of the source contract. Zig is still pre-1.0 and releases can change language, standard-library, package, and build APIs substantially. Never infer an API from memory or from an unversioned example.
When stamping build identity, follow the shared build revision rule.
Establish the project's actual toolchain first
- Read the project
AGENTS.md,INTENT.md,PLAN.md,flake.nix, lockfile,build.zig.zon, and any version-specific Zig guide before substantive work. - Determine the compiler actually selected by the flake. Use the project's
Nix path, for example
nix develop -c zig version, and build throughnix build. Do not use a global Zig binary or a populated host cache as proof of the pinned build. - Read only API guidance matching that exact Zig version. Older snippets are migration clues, not current templates. When guidance conflicts, verify against the versioned release notes, language reference, standard-library source and a minimal compile using the pinned compiler.
- Keep toolchain changes separate from feature changes. Do not upgrade a project merely because a newer stable compiler exists; record the baseline, migrate one project at a time, and run its complete test/build contract.
Current version map
As of 2026-11-05, Zig 0.17.1 is the latest stable release. It was announced
November 3 as a 0.17.0 bug-fix release; verify individual issues before
claiming they are resolved. Development builds are on 0.18. For an authorized
0.16-to-0.17 migration, use upgrading-zig-16-to-17 and the interim migration
reference.
The owner's Obsidian ZIG_RECENT_API_CHANGES.md is a detailed historical
quick reference for projects pinned to 0.14–0.16. Its 0.16 section is not a
0.17 guide. Preserve its version scope; do not silently rewrite old examples
as universal advice. Use the pinned project's own notes and the migration
reference for newer work.
For a new Zig repository, also invoke scaffold-zig-project. That skill owns
greenfield project layout and initial wiring; this skill owns language/API
correctness. Review generated templates against the selected compiler and
current Nix policy before using them.
Implementation discipline
- Follow TDD: write a focused failing test for behavior, confirm the red phase,
implement the smallest correction, then run the complete
./testand canonicalnix buildpaths. Zig tests only run when reachable from a test root; ensure each test-bearing module is included and has its own test artifact when it is a separate build module. A filtered run that reports zero matching tests is not evidence. - Keep pure decoding and business logic separate from I/O. Pass allocators,
std.Io, clocks, randomness and external effects explicitly where the selected API permits it. UseReleaseSafefor tests andReleaseFastfor shipped artifacts unless the project has a stronger verified policy. - Initialize every field after raw allocation such as
allocator.create(T); struct field defaults apply to struct-literal construction, not raw memory. Prefer a complete struct literal where lifetime and pointer-stability rules permit it. - Make integer widths explicit around arithmetic, shifts,
@min/@max, and parsed lengths. Never rely on inferred narrow result types where later math requires a wider type. Keep safety checks enabled in tests so overflow, bounds and cast errors remain observable. - For C ABIs, pass arbitrary bytes as pointer-plus-length, not as C strings. Document ownership, allocator pairing, lifetime, nullability, alignment, error representation and thread-safety. Do not allow Zig errors, panics, Rust panics or C++ exceptions to unwind across a C boundary.
- Do not silently downgrade failed concurrency or reference-tool setup. A fallback that preserves correctness but removes parallelism must be visible and covered by a performance check.
- Run cross-target build and packaged-artifact smoke checks for every supported platform. A successful compile does not prove the loader, libc, ABI, or runtime dependencies are usable. For the Linux libc choice, see "Linux libc and dead code" below.
Dependencies and Nix
For interchangeable cores or CLIs that must exercise a public ABI, use multi-implementation-contracts. An internal Zig module import does not test whether external consumers can use the exported library.
Nix is required. Before adding or changing Zig dependencies, follow
writing-nix, especially its
dependency portability reference.
That reference is authoritative for choosing between a ZON package, a pinned
flake input, and Nix-staged source; it also defines Zig package hashes versus
Nix fixed-output hashes, transitive cache prefetching, private sources, and
clean source-bounded builds. Do not duplicate or weaken it here.
Use the compiler source already selected by the project. A shared fleet memory
records zig-overlay as the usual exact-version source, but inspect the
current flake rather than assuming an old memory overrides its actual pin.
Keep language package metadata and Nix fetch/cache inputs synchronized. Never
depend on a host's global Zig cache, a sibling checkout, a local file URL, or a
literal Nix-store path. Run the complete derivation after changing dependency
staging; a devShell-only build is insufficient.
Use fix-zig-deps-hash only for a genuine dependency-content change. A moved
URL or tag does not by itself prove the package contents changed.
Inside Nix derivations, cap zig build parallelism to NIX_BUILD_CORES when
it is positive, and omit -j when NIX_BUILD_CORES=0 (Nix's cores = 0
all-cores setting):
zig_jobs=()
if [ "${NIX_BUILD_CORES:-0}" -gt 0 ]; then
zig_jobs=(-j"$NIX_BUILD_CORES")
fi
zig build "${zig_jobs[@]}" ...Do not pass -j"$NIX_BUILD_CORES" unguarded (even with a :-1 unset/empty
fallback): when Nix runs with cores = 0, NIX_BUILD_CORES=0 produces -j0
and Zig 0.16's build runner exits with error: number of jobs must be at least
1. Without a -j cap under a positive NIX_BUILD_CORES, Zig's build runner
schedules work for every logical CPU on the host, and in Zig 0.16.0
zig build -j<N> caps concurrent build steps without forwarding -j to child
zig compiler processes (each still allocates a host-CPU-sized thread pool,
roughly 127 threads on a 128-CPU host), which lets a few parallel derivations
exhaust nix-daemon's cgroup TasksMax and fail subprocess spawns with
SystemResources.
Local caches across checkouts and worktrees
Never share ZIG_LOCAL_CACHE_DIR or --cache-dir across separate checkouts,
git worktrees, copied trees, mutation runs, or baseline/oracle builds. Give
every checkout its own local cache: leave ZIG_LOCAL_CACHE_DIR unset (so each
checkout uses its own .zig-cache directory or per-checkout devcache link),
or pass a distinct ZIG_LOCAL_CACHE_DIR / --cache-dir per worktree. Sharing
ZIG_GLOBAL_CACHE_DIR across checkouts is safe.
Why: in Zig 0.15.2 and 0.16.0, a compile step's manifest key hashes relative
root source paths and build flags rather than the checkout directory, while
transitively @imported files are recorded in h/*.txt by absolute path into
the first checkout. When a second checkout or worktree shares that local cache
and its root entry files match, std.Build.Cache.Manifest.hitWithCurrentLock
opens the recorded absolute paths via openat(cwd, sub_path), which ignores
cwd for absolute paths, stats the first checkout's unchanged files, and
declares a cache hit. The second checkout silently receives the first
checkout's executable or test binary without reading its own modified
transitive files. Zig 0.17.1 stores relative paths in its binary manifests and
avoids that specific collision in a two-checkout reproducer, but keeping local
caches per checkout remains the rule across versions so builds on 0.15/0.16 stay
sound and concurrent worktrees never contend on local cache state.
Linux libc and dead code
Each project uses one libc for all of its Linux builds. Static musl is the default; dynamic glibc is for programs that must load host GPU, display or audio libraries. Neither may depend on a Nix store path. The policy, the reasons (never static glibc) and the blocking gate live in writing-nix's runtime-independence gate. These are the Zig mechanics, verified on Zig 0.16.0.
- Static musl: build for
-Dtarget=<cpu>-linux-musl. Zig bundles musl and links the executable statically, so there is no interpreter to repoint. The native gnu target on NixOS instead yields a dynamic glibc binary whose baked-in FHS loader path does not exist there, which is why projects reach forpatchelf. - glibc: name the target and its glibc floor explicitly, for example
-Dtarget=x86_64-linux-gnu.2.28. Zig then uses its own glibc stubs for that version rather than the build host's glibc. An explicit gnu target gets the standard/lib64/ld-linux-x86-64.so.2interpreter and no RUNPATH. With.2.28, a glibc 2.38 function (strlcpy) was undeclared at compile time; with.2.39it linked, and the newest symbol version wasGLIBC_2.38. An unversioned gnu target also refused it, so state the floor rather than rely on the default. Confirm the result with the writing-nix gate. - Archives a program links (C or Rust) must be built for the same libc.
- Zig code is compiled lazily, so a function nothing references gets no code.
A static library is different: every
export fnis a root, so the whole exported surface is emitted. Setlib.link_function_sections = trueandlib.link_data_sections = trueon shipped libraries so that a consumer's--gc-sectionscan drop exports it never calls. - C sources added with
addCSourceFileneed-ffunction-sectionsand-fdata-sectionsin their flags. Setexe.link_gc_sections = trueon the executable rather than relying on the optimize-mode default. - Strip debug information from shipped executables (
strip --strip-debugin the package, or the module'sstripoption). Keep the symbol table when tests inspect it withnm. - Measure rather than assume. In one CLI (x86_64, ReleaseFast), the section flags dropped two unused exports, 720 bytes of a 461 KB executable, because lazy compilation had already removed the rest. Static musl added about 63 KB of code. Stripping debug information mattered most: the file went from 1.9 MB to 461 KB.
Performance and deeper checks
For hot paths, establish a repeatable optimized baseline before considering
algorithm changes, SIMD, LLVM-level tuning, or cache changes. Use
performance-profiling for ./bm,
./big_o, memory growth, history and acceptance rules. Measure before and
after; include correctness and cross-platform dispatch checks for SIMD.
For risky parsers and decoders, add bounded fuzzing and differential tests
where useful, but put fixed regressions and acceptance-critical checks in
./test. Verify that malformed inputs return structured errors rather than
crashing or silently accepting invalid data.
Fleet lessons worth checking
The shared memory root contains evidence-backed Zig findings. Search its metadata before debugging a familiar-looking failure, especially for:
- Zig 0.16
std.Ioand process-spawn setup; Thread.spawnwith libc and too-small stacks;@min/@maxresult-width refinement;- allocator-created uninitialized structs;
- unreachable module tests and false-green filtered runs;
- C translation gaps such as
_Atomicparameters andchar **out-parameters; - Linux loader/static-link requirements;
- stale cross-checkout Zig caches;
- Nix Darwin SDK linker flags; and
- stdlib checksums that are read but not verified.
Use the memories skill to retrieve the exact evidence before applying a
lesson. Memories are diagnostic leads, not substitutes for reproducing the
issue under the project's pinned compiler.
When a Zig-specific failure repeats, add a concise, versioned lesson to the appropriate project or shared memory and improve this skill or its references only when the evidence generalizes. Do not record speculative fixes as rules.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

