<!-- skill: Rust Systems | version: 1.0.0 | description: Own Rust ownership, Cargo workspaces, Tokio async and clippy clean code | category: System & Productivity -->
## Instructions
- Ownership first: every value has one owner; moves invalidate old binding — use `clone()` only when measured, prefer borrows `&T` / `&mut T`.
- Borrowing rules: one mutable XOR many immutable refs; keep borrow scopes tiny with blocks `{ }` to satisfy the borrow checker fast.
- Lifetimes: annotate only when elided rules fail (`fn longest<'a>(x: &'a str, y: &'a str) -> &'a str`); prefer owned `String` at API edges to avoid lifetime sprawl.
- Error handling: `Result<T, E>` + `Option<T>` everywhere; propagate with `?`, define `thiserror::Error` enums for libs, `anyhow::Result` + `.context()` for binaries.
- Cargo workspaces: root `Cargo.toml` with `[workspace] members = ["crates/*"]`, shared `[workspace.dependencies]`, per-crate `Cargo.toml` with `crate.package.version.workspace = true`.
- Tokio async: `#[tokio::main]`, `.await` on I/O, `tokio::spawn` for tasks, `mpsc`/`oneshot` channels, `Arc<Mutex<T>>` for shared state; never block — use `spawn_blocking`.
- Clippy + fmt: `cargo clippy --all-targets -- -D warnings`, `cargo fmt --check` in CI; fix lints instead of `#[allow]`, run `cargo audit` / `cargo deny` for supply chain.
- Testing: unit tests in-module `#[cfg(test)]`, integration in `tests/`, `cargo test --workspace`, doc-tests as usage examples; property tests with `proptest`.
- Cross-compile: `rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-gnu`, `cargo build --release --target <triple>`; use `cross` or `cargo-zigbuild` for C-link issues.
- Profiling: `--release` + `cargo flamegraph`, `RUST_LOG=debug` with `tracing` + `tracing-subscriber`; `RUST_BACKTRACE=1` for panics, `#[must_use]` on fallible APIs.
- Struct design: `struct` + `impl` + `trait` bounds, builder pattern for >4 fields, `serde::{Serialize, Deserialize}` for config/JSON, `#[derive(Debug, Clone)]` by default.
- Concurrency: `Send + Sync` bounds, prefer channels over locks, `RwLock` for read-heavy, `parking_lot` only when profiled; `rayon` for data-parallel CPU work.
## Examples
- CLI tool: clap v4 derive CLI, anyhow errors, tokio file walk, workspace `crates/cli` + `crates/core`, clippy-clean, musl static binary release.
- HTTP fetcher: reqwest + tokio concurrent downloads with `JoinSet`, semaphore limit 8, thiserror `FetchError`, tracing logs, integration test with mock server.
- Parser lib: nom/winnow parser, `Result<Output, ParseError>`, proptest round-trips, doc examples, published via `cargo publish --dry-run` check.
## Workflows
1. Scaffold workspace: `cargo new --bin app`, split lib/bin crates, wire workspace deps.
2. Model types: structs/enums + thiserror/anyhow error strategy + serde derives.
3. Implement logic with borrows first, then async boundaries (tokio tasks/channels).
4. Add tests (unit + integration + doc) and run `cargo test --workspace`.
5. Gate quality: `cargo fmt`, `cargo clippy -- -D warnings`, `cargo audit`.
6. Release: `cargo build --release --target <triple>`, strip, attach to GitHub release.
## Templates
- Workspace layout:
```toml
# Cargo.toml (root)
[workspace]
resolver = "2"
members = ["crates/core", "crates/cli"]
[workspace.dependencies]
anyhow = "1"
thiserror = "2"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
# crates/cli/Cargo.toml
[package]
name = "mycli"
version.workspace = true
edition.workspace = true
[dependencies]
core = { path = "../core" }
anyhow.workspace = true
tokio.workspace = true
```
- Error handling done right:
```rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
    #[error("io failed on {path}: {source}")]
    Io { path: String, #[source] source: std::io::Error },
    #[error("config invalid: {0}")]
    Config(String),
}
pub fn load(path: &str) -> Result<String, AppError> {
    std::fs::read_to_string(path)
        .map_err(|source| AppError::Io { path: path.into(), source })?
        .pipe(Ok)
}
trait Pipe: Sized { fn pipe(self, f: impl FnOnce(Self) -> Self) -> Self { f(self) } }
impl<T> Pipe for T {}
```
- Tokio worker pattern:
```rust
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::init();
    let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(64);
    let worker = tokio::spawn(async move {
        while let Some(job) = rx.recv().await {
            tracing::info!(%job, "done");
        }
    });
    for i in 0..10 { tx.send(format!("job-{i}")).await?; }
    drop(tx); worker.await?;
    Ok(())
}
```
## Tools
- SARAH shell_run for `cargo new/build/test/clippy/fmt/audit`, `rustup target list`, `cross build`.
- SARAH file_write for workspace scaffolds, error enums, tokio mains; web_fetch for docs.rs crates.
## Advanced
- Zero-cost patterns: `Cow<'_, str>` to avoid allocs, `SmallVec` for tiny vecs, `#[inline]` on hot paths, `cargo bloat` / `cargo-llvm-lines` to trim binaries.
- FFI + unsafe: `unsafe` only in tiny audited modules, `# Safety` doc contracts, `miri` (`cargo +nightly miri test`) for UB checks, `bindgen` for C headers.
- Dist: `cargo-dist` or goreleaser-style GH Action matrix (linux-musl/windows/macos-arm), `strip` + `upx` optional, SBOM via `cargo cyclonedx`.
## Documentation
- https://doc.rust-lang.org/book/
- https://doc.rust-lang.org/cargo/
- https://tokio.rs/tokio/tutorial
- https://rust-cli.github.io/book/
- https://rust-lang.github.io/rust-clippy/master/
