Antigravity workspace rule for Rust systems code with borrow-first APIs, thiserror 2 error enums that keep sources, non-blocking Tokio and documented unsafe.
.agents/rules/antigravity-rust-systems.md. Downloaded files need to be placed in that repository path.---
trigger: glob
globs: "**/*"
---
# Rust Systems Programming
Applies to: Rust crates for systems work such as CLIs, daemons, network services and libraries, including async code on Tokio.
Version baseline: checked against Rust 1.85+ (2024 edition), thiserror 2, anyhow 1 and Tokio 1. Read `Cargo.toml` (`edition`, `rust-version`, dependency versions) first and stay within the declared MSRV.
## Before editing
- Read the module you are changing, its error type and its tests. Run `cargo check` before and after the change so you know which errors you introduced.
- Ask before adding a dependency or enabling new feature flags. Prefer the standard library when it covers the need.
## Ownership and borrowing
- Take borrowed views in function parameters (`&str`, `&[T]`, `&Path`, `impl AsRef<Path>`) unless the function needs to store or consume the value.
- Take ownership (`String`, `Vec<T>`) when the function stores the value or returns a transformed version of it. That avoids a clone at the call site.
- Clone only when two owners really need independent copies. When you add a `.clone()` to satisfy the borrow checker, say why in a comment or restructure the code instead.
- Prefer returning owned data or using indices over adding lifetimes to structs. Add explicit lifetimes only when elision can't express the relationship.
```rust
/// Borrow when you only read.
pub fn checksum(data: &[u8]) -> u32 {
data.iter().map(|&b| u32::from(b)).sum()
}
/// Take ownership when you transform and return; no extra allocation.
pub fn strip_zeros(mut data: Vec<u8>) -> Vec<u8> {
data.retain(|&b| b != 0);
data
}
```
## Error handling
- Libraries define a typed error enum with `thiserror`, with one variant per failure the caller can act on. Binaries may use `anyhow::Result` with `.context("...")` at the boundaries.
- Keep each underlying error as a `#[source]` or `#[from]`. Don't map a parse failure to an unrelated variant or throw away its message.
- No `unwrap()`/`expect()` on fallible input or I/O in library code. `expect("reason")` is acceptable for real invariants.
```rust
use std::path::{Path, PathBuf};
#[derive(Debug, serde::Deserialize)]
pub struct Config {
pub listen_addr: String,
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("reading {path}")]
Read { path: PathBuf, #[source] source: std::io::Error },
#[error("parsing {path}")]
Parse { path: PathBuf, #[source] source: toml::de::Error },
}
pub fn read_config(path: &Path) -> Result<Config, ConfigError> {
let text = std::fs::read_to_string(path)
.map_err(|source| ConfigError::Read { path: path.to_owned(), source })?;
toml::from_str(&text).map_err(|source| ConfigError::Parse { path: path.to_owned(), source })
}
```
## Async with Tokio
- Never block the runtime. Use `tokio::fs`/`tokio::net`, or move CPU-heavy or blocking calls into `tokio::task::spawn_blocking`.
- Don't hold a `std::sync::Mutex` guard across `.await`. Restructure the code, or use `tokio::sync::Mutex` when the lock must be held across an await.
- Bound concurrency and queues with `Semaphore`, bounded `mpsc` channels or `JoinSet`. Cancel work with a cancellation token or by dropping the task, and handle shutdown signals.
## unsafe and performance
- Avoid `unsafe` unless there's no safe alternative. Every `unsafe` block gets a `// SAFETY:` comment stating the invariant it relies on, plus a test that exercises it (run under Miri when possible).
- Measure before optimizing (`cargo bench`, criterion, `perf`/flamegraph). Report the numbers, and don't trade safety for an unmeasured speedup.
## Verify before finishing
Run when available in the project:
- `cargo fmt --check`
- `cargo clippy --all-targets -- -D warnings` (or the project's clippy settings)
- `cargo test`
- `cargo +nightly miri test` for crates with `unsafe` code, if Miri is installed
Cursor rules for Rust systems code: borrowing-first APIs, thiserror/anyhow error layers, Tokio async with correct mutex choice, allocation-aware performance and project layout.
CLAUDE.md rules for Rust 2024 crates with borrow-first APIs, Cow, thiserror 2 typed errors kept apart from anyhow, sqlx lookups and non-blocking Tokio workers.
Create particle effect systems
Antigravity
systems
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An Antigravity agent adds configuration loading and a background worker to a Rust 2024-edition daemon that uses Tokio.
Add load_config(path) that reads a TOML file into Config { listen_addr: String } and reports whether reading or parsing failed, with the path. Then start a worker that hashes files without blocking the runtime. Cargo.toml: edition = "2024", thiserror = "2", toml = "0.9", tokio = { features = ["full"] }.Illustrative; not a recorded model run. A ConfigError enum with Read and Parse variants that keep the path and the io::Error/toml::de::Error as #[source]; a function taking &Path; no unwrap on I/O; hashing moved into tokio::task::spawn_blocking; no std::sync::Mutex guard held across .await; bounded channel for work items; a summary listing cargo fmt --check, cargo clippy -D warnings and cargo test results.
Google describes Antigravity as its agentic development platform. Antigravity reads workspace rules from AGENTS.md or GEMINI.md and from Markdown files in .agents/rules/, with a trigger front matter field that sets when a rule is active. Global rules live under ~/.gemini/.
.agents/rules/antigravity-rust-systems.mdStarting point, not a tested configuration for your repository. Active when files matching globs are involved (trigger: glob). Review the instructions, adapt the file paths and run your project's existing checks.
---
trigger: glob
globs: "**/*"
---
# Rust Systems Programming
Applies to: Rust crates for systems work such as CLIs, daemons, network services and libraries, including async code on Tokio.
Version baseline: checked against Rust 1.85+ (2024 edition), thiserror 2, anyhow 1 and Tokio 1. Read `Cargo.toml` (`edition`, `rust-version`, dependency versions) first and stay within the declared MSRV.
## Before editing
- Read the module you are changing, its error type and its tests. Run `cargo check` before and after the change so you know which errors you introduced.
- Ask before adding a dependency or enabling new feature flags. Prefer the standard library when it covers the need.
## Ownership and borrowing
- Take borrowed views in function parameters (`&str`, `&[T]`, `&Path`, `impl AsRef<Path>`) unless the function needs to store or consume the value.
- Take ownership (`String`, `Vec<T>`) when the function stores the value or returns a transformed version of it. That avoids a clone at the call site.
- Clone only when two owners really need independent copies. When you add a `.clone()` to satisfy the borrow checker, say why in a comment or restructure the code instead.
- Prefer returning owned data or using indices over adding lifetimes to structs. Add explicit lifetimes only when elision can't express the relationship.
```rust
/// Borrow when you only read.
pub fn checksum(data: &[u8]) -> u32 {
data.iter().map(|&b| u32::from(b)).sum()
}
/// Take ownership when you transform and return; no extra allocation.
pub fn strip_zeros(mut data: Vec<u8>) -> Vec<u8> {
data.retain(|&b| b != 0);
data
}
```
## Error handling
- Libraries define a typed error enum with `thiserror`, with one variant per failure the caller can act on. Binaries may use `anyhow::Result` with `.context("...")` at the boundaries.
- Keep each underlying error as a `#[source]` or `#[from]`. Don't map a parse failure to an unrelated variant or throw away its message.
- No `unwrap()`/`expect()` on fallible input or I/O in library code. `expect("reason")` is acceptable for real invariants.
```rust
use std::path::{Path, PathBuf};
#[derive(Debug, serde::Deserialize)]
pub struct Config {
pub listen_addr: String,
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("reading {path}")]
Read { path: PathBuf, #[source] source: std::io::Error },
#[error("parsing {path}")]
Parse { path: PathBuf, #[source] source: toml::de::Error },
}
pub fn read_config(path: &Path) -> Result<Config, ConfigError> {
let text = std::fs::read_to_string(path)
.map_err(|source| ConfigError::Read { path: path.to_owned(), source })?;
toml::from_str(&text).map_err(|source| ConfigError::Parse { path: path.to_owned(), source })
}
```
## Async with Tokio
- Never block the runtime. Use `tokio::fs`/`tokio::net`, or move CPU-heavy or blocking calls into `tokio::task::spawn_blocking`.
- Don't hold a `std::sync::Mutex` guard across `.await`. Restructure the code, or use `tokio::sync::Mutex` when the lock must be held across an await.
- Bound concurrency and queues with `Semaphore`, bounded `mpsc` channels or `JoinSet`. Cancel work with a cancellation token or by dropping the task, and handle shutdown signals.
## unsafe and performance
- Avoid `unsafe` unless there's no safe alternative. Every `unsafe` block gets a `// SAFETY:` comment stating the invariant it relies on, plus a test that exercises it (run under Miri when possible).
- Measure before optimizing (`cargo bench`, criterion, `perf`/flamegraph). Report the numbers, and don't trade safety for an unmeasured speedup.
## Verify before finishing
Run when available in the project:
- `cargo fmt --check`
- `cargo clippy --all-targets -- -D warnings` (or the project's clippy settings)
- `cargo test`
- `cargo +nightly miri test` for crates with `unsafe` code, if Miri is installed
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Antigravity truncates any single rule file over 24,000 bytes, and global plus always_on rules share a 20,000-token budget, according to the docs. AGENTS.md (or GEMINI.md) in a workspace directory is one of the documented rule locations, and ~/.gemini/AGENTS.md works globally. Use .agents/rules/ when a rule should only apply in some situations.
Documentation checked 2026-11-05: Google Antigravity docs: RulesGoogle Antigravity home page
Cursor rules for Rust systems code: borrowing-first APIs, thiserror/anyhow error layers, Tokio async with correct mutex choice, allocation-aware performance and project layout.
CLAUDE.md rules for Rust 2024 crates with borrow-first APIs, Cow, thiserror 2 typed errors kept apart from anyhow, sqlx lookups and non-blocking Tokio workers.
Create particle effect systems